{"focal_file": "find_links/unit_and_integration_test.py", "focal_class": null, "focal_method": "filterization", "tests": "import unittest\n\nclass Test_filterization(unittest.TestCase):\n def testfilterization_method(self):\n first_obj = links_class('http://test-v.000webhostapp.com/test/')\n unfilterlist = ['photos.html', 'photos.html', 'videos.html', 'documents.html', 'music.html', 'https://web.telegram.org/#/im', 'http://test-v.000webhostapp.com/test/videos.html', 'http://test-v.000webhostapp.com/test/video.html']\n result = ['photos.html', 'videos.html', 'documents.html', 'music.html', 'http://test-v.000webhostapp.com/test/videos.html']\n filterizedlist = first_obj.filterization(unfilterlist)\n listsEqual = len(filterizedlist) == len(result) and all((x in result for x in filterizedlist))\n self.assertTrue(listsEqual)\n\n def testintegration(self):\n url = 'http://test-v.000webhostapp.com/test/'\n first_obj2 = links_class(url)\n first_obj2.redirection(first_obj2.filterization(first_obj2.initlist))\n result = ['http://test-v.000webhostapp.com/test/', 'photos.html', 'documents.html', 'music.html', 'http://test-v.000webhostapp.com/test/', 'videos.html', 'album1.html', 'album2.html', 'album3.html']\n listsEqual = len(first_obj2.history_all) == len(result) and all((x in result for x in first_obj2.history_all))\n self.assertTrue(listsEqual)\n\n def testintegration2(self):\n first_obj3 = links_class('http://test-v.000webhostapp.com/test/video.html')\n first_obj3.redirection(first_obj3.filterization(first_obj3.initlist))\n result = ['website not found']\n self.assertEqual(result, first_obj3.history_all)\n", "method_code": " def filterization(self, unfilterized_list):\n self.history_all\n if len(unfilterized_list) != 0:\n for link in unfilterized_list:\n if link == './':\n unfilterized_list.remove(link)\n elif link in self.history_all:\n unfilterized_list.remove(link)\n elif 'http' in link:\n unfilterized_list.remove(link)\n elif 'https' in link:\n unfilterized_list.remove(link)\n else:\n self.history_all.append(link)\n return unfilterized_list\n ", "context": "class links_class():\n def filterization(self, unfilterized_list): ...\n def __init__(self, url): ...\n def redirection(self, filterized_list): ...\n\n self.url = url\n\n history_all = []\n all_links = {}\n initlist = []\n filterlist = []\n redirectlist = []\n", "repository": "Dinaamagdy/training_tasks", "test_name": "testfilterization_method", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000001.py"} {"focal_file": "find_links/unit_and_integration_test.py", "focal_class": null, "focal_method": "redirection", "tests": "import unittest\n\nclass Test_redirection(unittest.TestCase):\n def testredirection_method(self):\n url = 'http://test-v.000webhostapp.com/test/'\n first_obj2 = links_classs(url)\n inputredir = ['videos.html']\n first_obj2.redirection(inputredir)\n result = []\n self.assertEqual(result, first_obj2.redirectlist)\n", "method_code": " def redirection(self, filterized_list):\n self.all_links\n temp = {}\n if len(filterized_list) > 0:\n for link in filterized_list:\n list_all = []\n if 'http' in link:\n url = link\n else:\n url = self.url + link\n response = requests.get(url)\n data = response.text\n if response.status_code == requests.codes.ok:\n soup = BeautifulSoup(data)\n for link in soup.find_all('a'):\n list_all.append(str(link.get('href')))\n temp[link] = list_all\n self.redirectlist = list_all[:]\n self.all_links[url] = list_all\n for k in temp:\n temp[k] = self.filterization(temp[k])\n for k in temp:\n self.redirection(temp[k])\n ", "context": "class links_class():\n def redirection(self, filterized_list): ...\n def __init__(self, url): ...\n def filterization(self, unfilterized_list): ...\n\n self.url = url\n\n history_all = []\n all_links = {}\n initlist = []\n filterlist = []\n redirectlist = []\n", "repository": "Dinaamagdy/training_tasks", "test_name": "testredirection_method", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000002.py"} {"focal_file": "monon/currency.py", "focal_class": null, "focal_method": "set_default_provider", "tests": "import unittest\n\nclass Test_set_default_provider(unittest.TestCase):\n def test_set_default_provider(self):\n\n class TestCurrency(Currency):\n pass\n TestCurrency.set_default_provider(self.mock_provider)\n currency = TestCurrency('USD')\n self.assertEqual(self.mock_provider, currency._provider)\n", "method_code": " def set_default_provider(cls, provider: CurrenciesProvider) -> None:\n cls._default_provider = provider\n ", "context": "class Currency():\n @classmethod\n def set_default_provider(cls, provider: CurrenciesProvider) -> None: ...\n def __init__(self, isocode: str, provider: Optional[CurrenciesProvider]=None) -> None: ...\n def get_default_provider(cls) -> CurrenciesProvider: ...\n def clean_isocode(cls, isocode: str) -> str: ...\n def format_amount(self, amount: Decimal) -> str: ...\n def format_amount_as_is(self, amount: Decimal) -> str: ...\n def quantize_amount(self, amount: Decimal, force_rounding: Optional[str]=None) -> Decimal: ...\n def symbol(self) -> str: ...\n def _get_quantizer(self) -> Decimal: ...\n def _set_provider(self, provider: Optional[CurrenciesProvider]) -> None: ...\n def __repr__(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n\n self.isocode = cleaned_isocode\n\n _default_provider = DefaultCurrenciesProvider()\n", "repository": "pedroburon/python-monon", "test_name": "test_set_default_provider", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000003.py"} {"focal_file": "monon/currency.py", "focal_class": null, "focal_method": "get_default_provider", "tests": "import unittest\n\nclass Test_get_default_provider(unittest.TestCase):\n def test_get_default_provider(self):\n self.assertIsInstance(Currency.get_default_provider(), DefaultCurrenciesProvider)\n\n def test_defined_default_provider(self):\n\n class CurrencyForTest(Currency):\n _default_provider = mock.NonCallableMagicMock(spec=CurrenciesProvider)\n self.assertEqual(CurrencyForTest._default_provider, CurrencyForTest.get_default_provider())\n", "method_code": " def get_default_provider(cls) -> CurrenciesProvider:\n return cls._default_provider\n ", "context": "class Currency():\n @classmethod\n def get_default_provider(cls) -> CurrenciesProvider: ...\n def __init__(self, isocode: str, provider: Optional[CurrenciesProvider]=None) -> None: ...\n def set_default_provider(cls, provider: CurrenciesProvider) -> None: ...\n def clean_isocode(cls, isocode: str) -> str: ...\n def format_amount(self, amount: Decimal) -> str: ...\n def format_amount_as_is(self, amount: Decimal) -> str: ...\n def quantize_amount(self, amount: Decimal, force_rounding: Optional[str]=None) -> Decimal: ...\n def symbol(self) -> str: ...\n def _get_quantizer(self) -> Decimal: ...\n def _set_provider(self, provider: Optional[CurrenciesProvider]) -> None: ...\n def __repr__(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n\n self.isocode = cleaned_isocode\n\n _default_provider = DefaultCurrenciesProvider()\n", "repository": "pedroburon/python-monon", "test_name": "test_get_default_provider", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000004.py"} {"focal_file": "monon/currency.py", "focal_class": null, "focal_method": "format_amount_as_is", "tests": "import unittest\n\nclass Test_format_amount_as_is(unittest.TestCase):\n def test_format_amount_as_is_from_provider(self):\n amount = mock.MagicMock(spec=decimal.Decimal)\n self.currency.format_amount_as_is(amount)\n self.mock_provider.format_amount.assert_called_once_with(self.currency.isocode, amount)\n", "method_code": " def format_amount_as_is(self, amount: Decimal) -> str:\n return self._provider.format_amount(self.isocode, amount)\n ", "context": "class Currency():\n def format_amount_as_is(self, amount: Decimal) -> str: ...\n def __init__(self, isocode: str, provider: Optional[CurrenciesProvider]=None) -> None: ...\n def set_default_provider(cls, provider: CurrenciesProvider) -> None: ...\n def get_default_provider(cls) -> CurrenciesProvider: ...\n def clean_isocode(cls, isocode: str) -> str: ...\n def format_amount(self, amount: Decimal) -> str: ...\n def quantize_amount(self, amount: Decimal, force_rounding: Optional[str]=None) -> Decimal: ...\n def symbol(self) -> str: ...\n def _get_quantizer(self) -> Decimal: ...\n def _set_provider(self, provider: Optional[CurrenciesProvider]) -> None: ...\n def __repr__(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n\n self.isocode = cleaned_isocode\n\n _default_provider = DefaultCurrenciesProvider()\n", "repository": "pedroburon/python-monon", "test_name": "test_format_amount_as_is_from_provider", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000005.py"} {"focal_file": "monon/currency.py", "focal_class": null, "focal_method": "get_decimal_places", "tests": "import unittest\n\nclass Test_get_decimal_places(unittest.TestCase):\n def test_decimal_places(self):\n self.assertEqual(2, self.provider.get_decimal_places(self.isocode))\n", "method_code": " def get_decimal_places(self, isocode: str) -> int:\n pass\n ", "context": "class CurrenciesProvider():\n @abstractmethod\n def get_decimal_places(self, isocode: str) -> int: ...\n def get_symbol(self, isocode: str) -> str: ...\n def validate_currency(self, isocode: str) -> None: ...\n def format_amount(self, isocode: str, amount: Decimal) -> str: ...\n def get_rounding(self, isocode: str) -> str: ...\n", "repository": "pedroburon/python-monon", "test_name": "test_decimal_places", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000006.py"} {"focal_file": "monon/currency.py", "focal_class": null, "focal_method": "get_symbol", "tests": "import unittest\n\nclass Test_get_symbol(unittest.TestCase):\n def test_symbol(self):\n self.assertEqual('$', self.provider.get_symbol(self.isocode))\n", "method_code": " def get_symbol(self, isocode: str) -> str:\n pass\n ", "context": "class CurrenciesProvider():\n @abstractmethod\n def get_symbol(self, isocode: str) -> str: ...\n def get_decimal_places(self, isocode: str) -> int: ...\n def validate_currency(self, isocode: str) -> None: ...\n def format_amount(self, isocode: str, amount: Decimal) -> str: ...\n def get_rounding(self, isocode: str) -> str: ...\n", "repository": "pedroburon/python-monon", "test_name": "test_symbol", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000007.py"} {"focal_file": "monon/currency.py", "focal_class": null, "focal_method": "validate_currency", "tests": "import unittest\n\nclass Test_validate_currency(unittest.TestCase):\n def test_validate_currency(self):\n self.assertIsNone(self.provider.validate_currency(self.isocode))\n", "method_code": " def validate_currency(self, isocode: str) -> None:\n pass\n ", "context": "class CurrenciesProvider():\n @abstractmethod\n def validate_currency(self, isocode: str) -> None: ...\n def get_decimal_places(self, isocode: str) -> int: ...\n def get_symbol(self, isocode: str) -> str: ...\n def format_amount(self, isocode: str, amount: Decimal) -> str: ...\n def get_rounding(self, isocode: str) -> str: ...\n", "repository": "pedroburon/python-monon", "test_name": "test_validate_currency", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000008.py"} {"focal_file": "monon/currency.py", "focal_class": null, "focal_method": "format_amount", "tests": "import unittest\n\nclass Test_format_amount(unittest.TestCase):\n def test_format_positive_amount(self):\n amount = Decimal('43321.123')\n expected = '$43321.123'\n self.assertEqual(expected, self.provider.format_amount(self.isocode, amount))\n\n def test_format_negative_amount(self):\n amount = Decimal('-1234.123')\n expected = '-$1234.123'\n self.assertEqual(expected, self.provider.format_amount(self.isocode, amount))\n", "method_code": " def format_amount(self, isocode: str, amount: Decimal) -> str:\n pass\n ", "context": "class CurrenciesProvider():\n @abstractmethod\n def format_amount(self, isocode: str, amount: Decimal) -> str: ...\n def get_decimal_places(self, isocode: str) -> int: ...\n def get_symbol(self, isocode: str) -> str: ...\n def validate_currency(self, isocode: str) -> None: ...\n def get_rounding(self, isocode: str) -> str: ...\n", "repository": "pedroburon/python-monon", "test_name": "test_format_positive_amount", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000009.py"} {"focal_file": "monon/currency.py", "focal_class": null, "focal_method": "get_rounding", "tests": "import unittest\n\nclass Test_get_rounding(unittest.TestCase):\n def test_rounding(self):\n self.assertEqual(ROUND_UP, self.provider.get_rounding(self.isocode))\n", "method_code": " def get_rounding(self, isocode: str) -> str:\n return ROUND_UP\n ", "context": "class CurrenciesProvider():\n def get_rounding(self, isocode: str) -> str: ...\n def get_decimal_places(self, isocode: str) -> int: ...\n def get_symbol(self, isocode: str) -> str: ...\n def validate_currency(self, isocode: str) -> None: ...\n def format_amount(self, isocode: str, amount: Decimal) -> str: ...\n", "repository": "pedroburon/python-monon", "test_name": "test_rounding", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000010.py"} {"focal_file": "tbk/webpay/commerce.py", "focal_class": null, "focal_method": "create_commerce", "tests": "import unittest\n\nclass Test_create_commerce(unittest.TestCase):\n @mock.patch('tbk.webpay.commerce.os.environ', {'TBK_COMMERCE_ID': '54321', 'TBK_COMMERCE_TESTING': 'True'})\n def test_create_commerce_with_commerce_id(self):\n \"\"\"\n create_commerce create a commerce with environ TBK_COMMERCE_ID and TBK_COMMERCE_TESTING=True\n \"\"\"\n commerce = Commerce.create_commerce()\n self.assertEqual(commerce.id, '54321')\n self.assertTrue(commerce.testing)\n self.assertEqual(commerce.key, commerce.TEST_COMMERCE_KEY)\n\n @mock.patch.dict('tbk.webpay.commerce.os.environ', {'TBK_COMMERCE_TESTING': 'True'})\n def test_create_commerce_with_no_commerce_id(self):\n \"\"\"\n create_commerce create a commerce with environ TBK_COMMERCE_TESTING=True\n \"\"\"\n commerce = Commerce.create_commerce()\n self.assertEqual(commerce.id, commerce.TEST_COMMERCE_ID)\n self.assertTrue(commerce.testing)\n self.assertEqual(commerce.key, commerce.TEST_COMMERCE_KEY)\n", "method_code": " def create_commerce():\n \"\"\"\n Creates commerce from environment variables ``TBK_COMMERCE_ID``, ``TBK_COMMERCE_KEY``\n or for testing purposes ``TBK_COMMERCE_TESTING``.\n \"\"\"\n commerce_id = os.getenv('TBK_COMMERCE_ID')\n commerce_key = os.getenv('TBK_COMMERCE_KEY')\n commerce_testing = os.getenv('TBK_COMMERCE_TESTING') == 'True'\n if not commerce_testing:\n if commerce_id is None:\n raise ValueError('create_commerce needs TBK_COMMERCE_ID environment variable')\n if commerce_key is None:\n raise ValueError('create_commerce needs TBK_COMMERCE_KEY environment variable')\n return Commerce(id=commerce_id or Commerce.TEST_COMMERCE_ID, key=commerce_key, testing=commerce_testing)\n ", "context": "class Commerce(object):\n @staticmethod\n def create_commerce(): ...\n def __init__(self, id=None, key=None, testing=False): ...\n def __get_key(self, key): ...\n def __get_id(self, id): ...\n def webpay_decrypt(self, encrypted): ...\n def webpay_encrypt(self, decrypted): ...\n def get_webpay_key(self): ...\n def get_commerce_key(self): ...\n def get_public_key(self): ...\n def get_config_tbk(self, confirmation_url): ...\n def acknowledge(self): ...\n def reject(self): ...\n\n self.testing = testing\n self.id = self.__get_id(id)\n self.key = self.__get_key(key)\n\n TEST_COMMERCE_KEY = TEST_COMMERCE_KEY\n TEST_COMMERCE_ID = '597026007976'\n webpay_key_id = 101\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000011.py"} {"focal_file": "tbk/webpay/commerce.py", "focal_class": "Commerce", "focal_method": "webpay_encrypt", "tests": "import unittest\n\nclass Test_Commerce_webpay_encrypt(unittest.TestCase):\n @mock.patch('tbk.webpay.commerce.Commerce.get_commerce_key')\n @mock.patch('tbk.webpay.commerce.Commerce.get_webpay_key')\n @mock.patch('tbk.webpay.commerce.Encryption')\n def test_webpay_encrypt(self, Encryption, get_webpay_key, get_commerce_key):\n commerce = Commerce(id='12345', testing=True)\n message = 'decrypted'\n result = commerce.webpay_encrypt(message)\n Encryption.assert_called_once_with(get_commerce_key.return_value, get_webpay_key.return_value)\n encryption = Encryption.return_value\n encryption.encrypt.assert_called_once_with(message.encode('utf-8'))\n get_webpay_key.assert_called_once_with()\n get_commerce_key.assert_called_once_with()\n self.assertEqual(result, encryption.encrypt.return_value)\n\n @mock.patch('tbk.webpay.commerce.Commerce.get_commerce_key')\n @mock.patch('tbk.webpay.commerce.Commerce.get_webpay_key')\n @mock.patch('tbk.webpay.commerce.Encryption')\n def test_webpay_encrypt_binary(self, Encryption, get_webpay_key, get_commerce_key):\n commerce = Commerce(id='12345', testing=True)\n message = b'decrypted'\n result = commerce.webpay_encrypt(message)\n Encryption.assert_called_once_with(get_commerce_key.return_value, get_webpay_key.return_value)\n encryption = Encryption.return_value\n encryption.encrypt.assert_called_once_with(message)\n get_webpay_key.assert_called_once_with()\n get_commerce_key.assert_called_once_with()\n self.assertEqual(result, encryption.encrypt.return_value)\n", "method_code": " def webpay_encrypt(self, decrypted):\n commerce_key = self.get_commerce_key()\n webpay_key = self.get_webpay_key()\n encryption = Encryption(commerce_key, webpay_key)\n if not isinstance(decrypted, six.binary_type):\n decrypted = decrypted.encode('utf-8')\n return encryption.encrypt(decrypted)\n ", "context": "class Commerce(object):\n def webpay_encrypt(self, decrypted): ...\n def __init__(self, id=None, key=None, testing=False): ...\n def create_commerce(): ...\n def __get_key(self, key): ...\n def __get_id(self, id): ...\n def webpay_decrypt(self, encrypted): ...\n def get_webpay_key(self): ...\n def get_commerce_key(self): ...\n def get_public_key(self): ...\n def get_config_tbk(self, confirmation_url): ...\n def acknowledge(self): ...\n def reject(self): ...\n\n self.testing = testing\n self.id = self.__get_id(id)\n self.key = self.__get_key(key)\n\n TEST_COMMERCE_KEY = TEST_COMMERCE_KEY\n TEST_COMMERCE_ID = '597026007976'\n webpay_key_id = 101\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000012.py"} {"focal_file": "tbk/webpay/commerce.py", "focal_class": "Commerce", "focal_method": "webpay_decrypt", "tests": "import unittest\n\nclass Test_Commerce_webpay_decrypt(unittest.TestCase):\n @mock.patch('tbk.webpay.commerce.Commerce.get_commerce_key')\n @mock.patch('tbk.webpay.commerce.Commerce.get_webpay_key')\n @mock.patch('tbk.webpay.commerce.Decryption')\n def test_webpay_decrypt(self, Decryption, get_webpay_key, get_commerce_key):\n commerce = Commerce(id=12345, testing=True)\n message = 'encrypted'\n result = commerce.webpay_decrypt(message)\n Decryption.assert_called_once_with(get_commerce_key.return_value, get_webpay_key.return_value)\n decryption = Decryption.return_value\n decryption.decrypt.assert_called_once_with(message.encode('utf-8'))\n get_webpay_key.assert_called_once_with()\n get_commerce_key.assert_called_once_with()\n self.assertEqual(result, decryption.decrypt.return_value)\n\n @mock.patch('tbk.webpay.commerce.Commerce.get_commerce_key')\n @mock.patch('tbk.webpay.commerce.Commerce.get_webpay_key')\n @mock.patch('tbk.webpay.commerce.Decryption')\n def test_webpay_decrypt_binary(self, Decryption, get_webpay_key, get_commerce_key):\n commerce = Commerce(id=12345, testing=True)\n message = b'encrypted'\n result = commerce.webpay_decrypt(message)\n Decryption.assert_called_once_with(get_commerce_key.return_value, get_webpay_key.return_value)\n decryption = Decryption.return_value\n decryption.decrypt.assert_called_once_with(message)\n get_webpay_key.assert_called_once_with()\n get_commerce_key.assert_called_once_with()\n self.assertEqual(result, decryption.decrypt.return_value)\n", "method_code": " def webpay_decrypt(self, encrypted):\n commerce_key = self.get_commerce_key()\n webpay_key = self.get_webpay_key()\n decryption = Decryption(commerce_key, webpay_key)\n if not isinstance(encrypted, six.binary_type):\n encrypted = encrypted.encode('utf-8')\n return decryption.decrypt(encrypted)\n ", "context": "class Commerce(object):\n def webpay_decrypt(self, encrypted): ...\n def __init__(self, id=None, key=None, testing=False): ...\n def create_commerce(): ...\n def __get_key(self, key): ...\n def __get_id(self, id): ...\n def webpay_encrypt(self, decrypted): ...\n def get_webpay_key(self): ...\n def get_commerce_key(self): ...\n def get_public_key(self): ...\n def get_config_tbk(self, confirmation_url): ...\n def acknowledge(self): ...\n def reject(self): ...\n\n self.testing = testing\n self.id = self.__get_id(id)\n self.key = self.__get_key(key)\n\n TEST_COMMERCE_KEY = TEST_COMMERCE_KEY\n TEST_COMMERCE_ID = '597026007976'\n webpay_key_id = 101\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000013.py"} {"focal_file": "tbk/webpay/commerce.py", "focal_class": "Commerce", "focal_method": "get_commerce_key", "tests": "import unittest\n\nclass Test_Commerce_get_commerce_key(unittest.TestCase):\n def test_get_commerce_key(self):\n testing_path = os.path.join(os.path.dirname(__file__), 'keys', 'test_commerce.pem')\n with open(testing_path, 'r') as testing_file:\n commerce = Commerce(id=12345, testing=True)\n commerce.key = Commerce.TEST_COMMERCE_KEY\n expected_key = RSA.importKey(testing_file.read())\n self.assertEqual(expected_key, commerce.get_commerce_key())\n", "method_code": " def get_commerce_key(self):\n return RSA.importKey(self.key)\n ", "context": "class Commerce(object):\n def get_commerce_key(self): ...\n def __init__(self, id=None, key=None, testing=False): ...\n def create_commerce(): ...\n def __get_key(self, key): ...\n def __get_id(self, id): ...\n def webpay_decrypt(self, encrypted): ...\n def webpay_encrypt(self, decrypted): ...\n def get_webpay_key(self): ...\n def get_public_key(self): ...\n def get_config_tbk(self, confirmation_url): ...\n def acknowledge(self): ...\n def reject(self): ...\n\n self.testing = testing\n self.id = self.__get_id(id)\n self.key = self.__get_key(key)\n\n TEST_COMMERCE_KEY = TEST_COMMERCE_KEY\n TEST_COMMERCE_ID = '597026007976'\n webpay_key_id = 101\n", "repository": "pedroburon/tbk", "test_name": "test_get_commerce_key", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000014.py"} {"focal_file": "tbk/webpay/commerce.py", "focal_class": "Commerce", "focal_method": "get_webpay_key", "tests": "import unittest\n\nclass Test_Commerce_get_webpay_key(unittest.TestCase):\n def test_get_webpay_key_testing(self):\n webpay_testing_path = os.path.join(os.path.dirname(__file__), 'keys', 'webpay_test.101.pem')\n with open(webpay_testing_path, 'r') as testing_file:\n commerce = Commerce(id=12345, testing=True)\n commerce.testing = True\n expected_key = RSA.importKey(testing_file.read())\n key = commerce.get_webpay_key()\n self.assertEqual(expected_key, key)\n\n def test_get_webpay_key(self):\n webpay_path = os.path.join(os.path.dirname(__file__), 'keys', 'webpay.101.pem')\n with open(webpay_path, 'r') as testing_file:\n commerce = Commerce(id=12345, testing=True)\n commerce.testing = False\n expected_key = RSA.importKey(testing_file.read())\n key = commerce.get_webpay_key()\n self.assertEqual(expected_key, key)\n", "method_code": " def get_webpay_key(self):\n return RSA.importKey(TEST_WEBPAY_KEY if self.testing else WEBPAY_KEY)\n ", "context": "class Commerce(object):\n def get_webpay_key(self): ...\n def __init__(self, id=None, key=None, testing=False): ...\n def create_commerce(): ...\n def __get_key(self, key): ...\n def __get_id(self, id): ...\n def webpay_decrypt(self, encrypted): ...\n def webpay_encrypt(self, decrypted): ...\n def get_commerce_key(self): ...\n def get_public_key(self): ...\n def get_config_tbk(self, confirmation_url): ...\n def acknowledge(self): ...\n def reject(self): ...\n\n self.testing = testing\n self.id = self.__get_id(id)\n self.key = self.__get_key(key)\n\n TEST_COMMERCE_KEY = TEST_COMMERCE_KEY\n TEST_COMMERCE_ID = '597026007976'\n webpay_key_id = 101\n", "repository": "pedroburon/tbk", "test_name": "test_get_webpay_key_testing", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000015.py"} {"focal_file": "tbk/webpay/commerce.py", "focal_class": "Commerce", "focal_method": "get_public_key", "tests": "import unittest\n\nclass Test_Commerce_get_public_key(unittest.TestCase):\n def test_get_public_key(self):\n private_key = RSA.generate(2048)\n commerce_key = private_key.exportKey()\n commerce = Commerce(id='12345', key=commerce_key)\n self.assertEqual(private_key.publickey().exportKey(), commerce.get_public_key())\n", "method_code": " def get_public_key(self):\n \"\"\"\n Returns Commerce public key from PEM private key.\n \n \"\"\"\n return self.get_commerce_key().publickey().exportKey()\n ", "context": "class Commerce(object):\n def get_public_key(self): ...\n def __init__(self, id=None, key=None, testing=False): ...\n def create_commerce(): ...\n def __get_key(self, key): ...\n def __get_id(self, id): ...\n def webpay_decrypt(self, encrypted): ...\n def webpay_encrypt(self, decrypted): ...\n def get_webpay_key(self): ...\n def get_commerce_key(self): ...\n def get_config_tbk(self, confirmation_url): ...\n def acknowledge(self): ...\n def reject(self): ...\n\n self.testing = testing\n self.id = self.__get_id(id)\n self.key = self.__get_key(key)\n\n TEST_COMMERCE_KEY = TEST_COMMERCE_KEY\n TEST_COMMERCE_ID = '597026007976'\n webpay_key_id = 101\n", "repository": "pedroburon/tbk", "test_name": "test_get_public_key", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000016.py"} {"focal_file": "tbk/webpay/commerce.py", "focal_class": "Commerce", "focal_method": "get_config_tbk", "tests": "import unittest\n\nclass Test_Commerce_get_config_tbk(unittest.TestCase):\n def test_get_config_tbk_testing(self):\n config_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'tbk_config.dat.testing')\n with open(config_path, 'r') as config_file:\n expected = config_file.read()\n commerce = Commerce(testing=True)\n self.assertEqual(expected, commerce.get_config_tbk(confirmation_url='http://54.198.45.69:8080/webpay/confirmation'))\n\n def test_get_config_tbk_production(self):\n config_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'tbk_config.dat.production')\n with open(config_path, 'r') as config_file:\n expected = config_file.read()\n commerce = Commerce(id='597026007977', key=Commerce.TEST_COMMERCE_KEY, testing=False)\n self.assertEqual(expected, commerce.get_config_tbk(confirmation_url='http://54.198.45.70:80/prodwebpay/result'))\n", "method_code": " def get_config_tbk(self, confirmation_url):\n \"\"\"\n Returns a string with the ``TBK_CONFIG.dat``.\n \n :param confirmation_url: URL where callback is made.\n \"\"\"\n config = 'IDCOMERCIO = {commerce_id}\\nMEDCOM = 1\\nTBK_KEY_ID = 101\\nPARAMVERIFCOM = 1\\nURLCGICOM = {confirmation_path}\\nSERVERCOM = {confirmation_host}\\nPORTCOM = {confirmation_port}\\nWHITELISTCOM = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789./:=&?_\\nHOST = {confirmation_host}\\nWPORT = {confirmation_port}\\nURLCGITRA = /filtroUnificado/bp_revision.cgi\\nURLCGIMEDTRA = /filtroUnificado/bp_validacion.cgi\\nSERVERTRA = {webpay_server}\\nPORTTRA = {webpay_port}\\nPREFIJO_CONF_TR = HTML_\\nHTML_TR_NORMAL = http://127.0.0.1/notify\\n'\n confirmation_uri = six.moves.urllib.parse.urlparse(confirmation_url)\n webpay_server = 'https://certificacion.webpay.cl' if self.testing else 'https://webpay.transbank.cl'\n webpay_port = 6443 if self.testing else 443\n return config.format(commerce_id=self.id, confirmation_path=confirmation_uri.path, confirmation_host=confirmation_uri.hostname, confirmation_port=confirmation_uri.port, webpay_port=webpay_port, webpay_server=webpay_server)\n ", "context": "class Commerce(object):\n def get_config_tbk(self, confirmation_url): ...\n def __init__(self, id=None, key=None, testing=False): ...\n def create_commerce(): ...\n def __get_key(self, key): ...\n def __get_id(self, id): ...\n def webpay_decrypt(self, encrypted): ...\n def webpay_encrypt(self, decrypted): ...\n def get_webpay_key(self): ...\n def get_commerce_key(self): ...\n def get_public_key(self): ...\n def acknowledge(self): ...\n def reject(self): ...\n\n self.testing = testing\n self.id = self.__get_id(id)\n self.key = self.__get_key(key)\n\n TEST_COMMERCE_KEY = TEST_COMMERCE_KEY\n TEST_COMMERCE_ID = '597026007976'\n webpay_key_id = 101\n", "repository": "pedroburon/tbk", "test_name": "test_get_config_tbk_testing", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000017.py"} {"focal_file": "tbk/webpay/confirmation.py", "focal_class": "Confirmation", "focal_method": "is_success", "tests": "import unittest\n\nclass Test_Confirmation_is_success(unittest.TestCase):\n @mock.patch('tbk.webpay.confirmation.Confirmation.parse')\n def test_is_success(self, parse, logger, ConfirmationPayload):\n parse.return_value = {'TBK_RESPUESTA': '0'}\n data = {'TBK_PARAM': mock.Mock()}\n payload = ConfirmationPayload.return_value\n payload.response = payload.SUCCESS_RESPONSE_CODE\n confirmation = Confirmation(self.commerce, self.request_ip, data)\n self.assertTrue(confirmation.is_success(check_timeout=False))\n", "method_code": " def is_success(self, check_timeout=True):\n \"\"\"\n Check if Webpay response ``TBK_RESPUESTA`` is equal to ``0`` and if the lapse between initialization\n and this call is less than ``self.timeout`` when ``check_timeout`` is ``True`` (default).\n \n :param check_timeout: When ``True``, check time between initialization and call.\n \"\"\"\n if check_timeout and self.is_timeout():\n return False\n return self.payload.response == self.payload.SUCCESS_RESPONSE_CODE\n ", "context": "class Confirmation(object):\n def is_success(self, check_timeout=True): ...\n def __init__(self, commerce, request_ip, data, timeout=CONFIRMATION_TIMEOUT): ...\n def parse(self, tbk_param): ...\n def is_timeout(self): ...\n def amount(self): ...\n def order_id(self): ...\n def acknowledge(self): ...\n def reject(self): ...\n def message(self): ...\n def paid_at(self): ...\n def transaction_id(self): ...\n def params(self): ...\n\n self.init_time = datetime.datetime.now()\n self.timeout = timeout\n self.commerce = commerce\n self.request_ip = request_ip\n self.payload = ConfirmationPayload(self.parse(data['TBK_PARAM']))\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000018.py"} {"focal_file": "tbk/webpay/confirmation.py", "focal_class": "Confirmation", "focal_method": "is_timeout", "tests": "import unittest\n\nclass Test_Confirmation_is_timeout(unittest.TestCase):\n @mock.patch('tbk.webpay.confirmation.Confirmation.parse')\n def test_timeout(self, parse, logger, ConfirmationPayload):\n data = {'TBK_PARAM': mock.Mock()}\n timeout = 25\n confirmation = Confirmation(self.commerce, self.request_ip, data, timeout)\n confirmation.init_time = confirmation.init_time - datetime.timedelta(seconds=timeout)\n self.assertTrue(confirmation.is_timeout())\n\n @mock.patch('tbk.webpay.confirmation.Confirmation.parse')\n def test_not_timeout(self, parse, logger, ConfirmationPayload):\n data = {'TBK_PARAM': mock.Mock()}\n timeout = 20\n confirmation = Confirmation(self.commerce, self.request_ip, data, timeout)\n confirmation.init_time = confirmation.init_time + datetime.timedelta(seconds=timeout)\n self.assertFalse(confirmation.is_timeout())\n", "method_code": " def is_timeout(self):\n \"\"\"\n Check if the lapse between initialization and now is more than ``self.timeout``.\n \"\"\"\n lapse = datetime.datetime.now() - self.init_time\n return lapse > datetime.timedelta(seconds=self.timeout)\n ", "context": "class Confirmation(object):\n def is_timeout(self): ...\n def __init__(self, commerce, request_ip, data, timeout=CONFIRMATION_TIMEOUT): ...\n def parse(self, tbk_param): ...\n def is_success(self, check_timeout=True): ...\n def amount(self): ...\n def order_id(self): ...\n def acknowledge(self): ...\n def reject(self): ...\n def message(self): ...\n def paid_at(self): ...\n def transaction_id(self): ...\n def params(self): ...\n\n self.init_time = datetime.datetime.now()\n self.timeout = timeout\n self.commerce = commerce\n self.request_ip = request_ip\n self.payload = ConfirmationPayload(self.parse(data['TBK_PARAM']))\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000019.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Encryption", "focal_method": "encrypt", "tests": "import unittest\n\nclass Test_Encryption_encrypt(unittest.TestCase):\n @mock.patch('tbk.webpay.encryption.Encryption.get_iv')\n @mock.patch('tbk.webpay.encryption.Encryption.get_key')\n @mock.patch('tbk.webpay.encryption.Encryption.encrypt_key')\n @mock.patch('tbk.webpay.encryption.Encryption.encrypt_message')\n @mock.patch('tbk.webpay.encryption.Encryption.sign_message')\n def test_encrypt(self, sign_message, encrypt_message, encrypt_key, get_key, get_iv):\n message = Random.new().read(2000)\n encryption = Encryption(self.sender_key, self.recipient_key)\n sender_key_bytes = int(self.sender_key.publickey().n.bit_length() / 8)\n encrypt_message.return_value = Random.new().read(len(message))\n encrypt_key.return_value = Random.new().read(sender_key_bytes)\n get_iv.return_value = Random.new().read(16)\n encrypted_message = encryption.encrypt(message)\n data = base64.b64decode(encrypted_message)\n iv = data[0:16]\n encrypted_key = data[16:16 + sender_key_bytes]\n encrypted_message = data[16 + sender_key_bytes:]\n self.assertEqual(encrypt_message.return_value, encrypted_message)\n self.assertEqual(encrypt_key.return_value, encrypted_key)\n self.assertEqual(get_iv.return_value, iv)\n encrypt_key.assert_called_once_with(get_key.return_value)\n encrypt_message.assert_called_once_with(sign_message.return_value, message, get_key.return_value, get_iv.return_value)\n sign_message.assert_called_once_with(message)\n", "method_code": " def encrypt(self, message):\n if not isinstance(message, six.binary_type):\n raise EncryptionError('Message must be binary type.')\n key = self.get_key()\n iv = self.get_iv()\n encrypted_key = self.encrypt_key(key)\n signed_message = self.sign_message(message)\n encrypted_message = self.encrypt_message(signed_message, message, key, iv)\n return base64.b64encode(iv + encrypted_key + encrypted_message)\n ", "context": "class Encryption(object):\n def encrypt(self, message): ...\n def __init__(self, sender_key, recipient_key): ...\n def sign_message(self, message): ...\n def encrypt_message(self, signed_message, message, key, iv): ...\n def encrypt_key(self, key): ...\n def get_key(self): ...\n def get_iv(self): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000020.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Decryption", "focal_method": "get_iv", "tests": "import unittest\n\nclass Test_Decryption_get_iv(unittest.TestCase):\n def test_get_iv(self):\n decryption = Decryption(self.recipient_key, self.sender_key)\n raw = Random.new().read(2000)\n iv = raw[:16]\n self.assertEqual(iv, decryption.get_iv(raw))\n", "method_code": " def get_iv(self):\n return Random.new().read(16)\n ", "context": "class Encryption(object):\n def get_iv(self): ...\n def __init__(self, sender_key, recipient_key): ...\n def encrypt(self, message): ...\n def sign_message(self, message): ...\n def encrypt_message(self, signed_message, message, key, iv): ...\n def encrypt_key(self, key): ...\n def get_key(self): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "test_get_iv", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000021.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Decryption", "focal_method": "get_key", "tests": "import unittest\n\nclass Test_Decryption_get_key(unittest.TestCase):\n def test_get_key(self):\n decryption = Decryption(self.recipient_key, self.sender_key)\n raw = Random.new().read(16)\n key = Random.new().read(32)\n cipher = PKCS1_OAEP.new(self.recipient_key.publickey())\n encrypted_key = cipher.encrypt(key)\n raw += encrypted_key + Random.new().read(2000)\n self.assertEqual(key, decryption.get_key(raw))\n", "method_code": " def get_key(self):\n return Random.new().read(32)\n ", "context": "class Encryption(object):\n def get_key(self): ...\n def __init__(self, sender_key, recipient_key): ...\n def encrypt(self, message): ...\n def sign_message(self, message): ...\n def encrypt_message(self, signed_message, message, key, iv): ...\n def encrypt_key(self, key): ...\n def get_iv(self): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "test_get_key", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000022.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Encryption", "focal_method": "encrypt_key", "tests": "import unittest\n\nclass Test_Encryption_encrypt_key(unittest.TestCase):\n def test_encrypt_key(self):\n key = Random.new().read(32)\n cipher = PKCS1_OAEP.new(self.recipient_key_private)\n encryption = Encryption(self.sender_key, self.recipient_key)\n encrypted_key = encryption.encrypt_key(key)\n self.assertEqual(cipher.decrypt(encrypted_key), key)\n", "method_code": " def encrypt_key(self, key):\n public_key = self.recipient_key.publickey()\n cipher = PKCS1_OAEP.new(public_key)\n return cipher.encrypt(key)\n ", "context": "class Encryption(object):\n def encrypt_key(self, key): ...\n def __init__(self, sender_key, recipient_key): ...\n def encrypt(self, message): ...\n def sign_message(self, message): ...\n def encrypt_message(self, signed_message, message, key, iv): ...\n def get_key(self): ...\n def get_iv(self): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "test_encrypt_key", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000023.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Encryption", "focal_method": "sign_message", "tests": "import unittest\n\nclass Test_Encryption_sign_message(unittest.TestCase):\n def test_sign_message(self):\n message = Random.new().read(2000)\n encryption = Encryption(self.sender_key, self.recipient_key)\n signed_message = encryption.sign_message(message)\n public_key = self.sender_key.publickey()\n hash = SHA512.new(message)\n verifier = PKCS1_v1_5.new(public_key)\n self.assertTrue(verifier.verify(hash, signed_message))\n", "method_code": " def sign_message(self, message):\n hash = SHA512.new(message)\n signer = PKCS1_v1_5.new(self.sender_key)\n return signer.sign(hash)\n ", "context": "class Encryption(object):\n def sign_message(self, message): ...\n def __init__(self, sender_key, recipient_key): ...\n def encrypt(self, message): ...\n def encrypt_message(self, signed_message, message, key, iv): ...\n def encrypt_key(self, key): ...\n def get_key(self): ...\n def get_iv(self): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "test_sign_message", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000024.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Encryption", "focal_method": "encrypt_message", "tests": "import unittest\n\nclass Test_Encryption_encrypt_message(unittest.TestCase):\n def test_encrypt_message(self):\n encryption = Encryption(self.sender_key, self.recipient_key)\n key = encryption.get_key()\n iv = encryption.get_iv()\n message = Random.new().read(10)\n signed_message = encryption.sign_message(message)\n encrypted = encryption.encrypt_message(signed_message, message, key, iv)\n cipher = AES.new(key, AES.MODE_CBC, iv)\n unpad = lambda s: s[:-ord(s[len(s) - 1:])]\n decrypted = unpad(cipher.decrypt(encrypted))\n self.assertEqual(decrypted, signed_message + message)\n", "method_code": " def encrypt_message(self, signed_message, message, key, iv):\n raw = signed_message + message\n block_size = AES.block_size\n pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size).encode('utf-8')\n message_to_encrypt = pad(raw)\n cipher = AES.new(key, AES.MODE_CBC, iv)\n return cipher.encrypt(message_to_encrypt)\n ", "context": "class Encryption(object):\n def encrypt_message(self, signed_message, message, key, iv): ...\n def __init__(self, sender_key, recipient_key): ...\n def encrypt(self, message): ...\n def sign_message(self, message): ...\n def encrypt_key(self, key): ...\n def get_key(self): ...\n def get_iv(self): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "test_encrypt_message", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000025.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Decryption", "focal_method": "decrypt", "tests": "import unittest\n\nclass Test_Decryption_decrypt(unittest.TestCase):\n @mock.patch('tbk.webpay.encryption.binascii.hexlify')\n @mock.patch('tbk.webpay.encryption.Decryption.get_iv')\n @mock.patch('tbk.webpay.encryption.Decryption.get_key')\n @mock.patch('tbk.webpay.encryption.Decryption.get_decrypted_message')\n @mock.patch('tbk.webpay.encryption.Decryption.get_signature')\n @mock.patch('tbk.webpay.encryption.Decryption.get_message')\n @mock.patch('tbk.webpay.encryption.Decryption.verify')\n def test_decrypt(self, verify, get_message, get_signature, get_decrypted_message, get_key, get_iv, hexlify):\n decryption = Decryption(self.recipient_key, self.sender_key)\n raw = Random.new().read(2000)\n encrypted = base64.b64encode(raw)\n message = get_message.return_value\n signature = get_signature.return_value\n hexlify_signature = hexlify.return_value\n decrypted_message = get_decrypted_message.return_value\n iv = get_iv.return_value\n key = get_key.return_value\n verify.return_value = True\n returned_message, returned_signature = decryption.decrypt(encrypted)\n self.assertEqual(message, returned_message)\n self.assertEqual(hexlify_signature, returned_signature)\n get_message.assert_called_once_with(decrypted_message)\n get_decrypted_message.assert_called_once_with(iv, key, raw)\n get_iv.assert_called_once_with(raw)\n get_key.assert_called_once_with(raw)\n get_signature.assert_called_once_with(decrypted_message)\n verify.assert_called_once_with(signature, message)\n hexlify.assert_called_once_with(signature)\n", "method_code": " def decrypt(self, message):\n if not isinstance(message, six.binary_type):\n raise DecryptionError('Message must be binary type.')\n raw = base64.b64decode(message)\n iv = self.get_iv(raw)\n key = self.get_key(raw)\n decrypted_message = self.get_decrypted_message(iv, key, raw)\n signature = self.get_signature(decrypted_message)\n message = self.get_message(decrypted_message)\n if self.verify(signature, message):\n return (message, binascii.hexlify(signature))\n raise InvalidMessageException('Invalid message signature')\n ", "context": "class Decryption(object):\n def decrypt(self, message): ...\n def __init__(self, recipient_key, sender_key): ...\n def get_iv(self, raw): ...\n def get_key(self, raw): ...\n def get_decrypted_message(self, iv, key, raw): ...\n def get_signature(self, decrypted_message): ...\n def get_message(self, decrypted_message): ...\n def verify(self, signature, message): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000026.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Decryption", "focal_method": "get_decrypted_message", "tests": "import unittest\n\nclass Test_Decryption_get_decrypted_message(unittest.TestCase):\n def test_get_decrypted_message(self):\n recipient_key_bytes = int(self.recipient_key.publickey().n.bit_length() / 8)\n decryption = Decryption(self.recipient_key, self.sender_key)\n iv = Random.new().read(16)\n key = Random.new().read(32)\n encrypted_key = Random.new().read(recipient_key_bytes)\n message = ('a' * 2000).encode('utf-8')\n block_size = AES.block_size\n pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size).encode('utf-8')\n message_to_encrypt = pad(message)\n cipher = AES.new(key, mode=AES.MODE_CBC, IV=iv)\n encrypted_message = cipher.encrypt(message_to_encrypt)\n self.assertEqual(message, decryption.get_decrypted_message(iv, key, iv + encrypted_key + encrypted_message))\n", "method_code": " def get_decrypted_message(self, iv, key, raw):\n recipient_key_bytes = int(self.recipient_key.publickey().n.bit_length() / 8)\n encrypted_message = raw[16 + recipient_key_bytes:]\n unpad = lambda s: s[:-ord(s[len(s) - 1:])]\n cipher = AES.new(key, AES.MODE_CBC, iv)\n return unpad(cipher.decrypt(encrypted_message))\n ", "context": "class Decryption(object):\n def get_decrypted_message(self, iv, key, raw): ...\n def __init__(self, recipient_key, sender_key): ...\n def decrypt(self, message): ...\n def get_iv(self, raw): ...\n def get_key(self, raw): ...\n def get_signature(self, decrypted_message): ...\n def get_message(self, decrypted_message): ...\n def verify(self, signature, message): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "test_get_decrypted_message", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000027.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Decryption", "focal_method": "get_signature", "tests": "import unittest\n\nclass Test_Decryption_get_signature(unittest.TestCase):\n def test_get_signature(self):\n sender_key_bytes = int(self.sender_key.publickey().n.bit_length() / 8)\n decryption = Decryption(self.recipient_key, self.sender_key)\n signature = Random.new().read(sender_key_bytes)\n message = Random.new().read(500)\n decrypted_message = signature + message\n self.assertEqual(signature, decryption.get_signature(decrypted_message))\n", "method_code": " def get_signature(self, decrypted_message):\n sender_key_bytes = int(self.sender_key.publickey().n.bit_length() / 8)\n return decrypted_message[:sender_key_bytes]\n ", "context": "class Decryption(object):\n def get_signature(self, decrypted_message): ...\n def __init__(self, recipient_key, sender_key): ...\n def decrypt(self, message): ...\n def get_iv(self, raw): ...\n def get_key(self, raw): ...\n def get_decrypted_message(self, iv, key, raw): ...\n def get_message(self, decrypted_message): ...\n def verify(self, signature, message): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "test_get_signature", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000028.py"} {"focal_file": "tbk/webpay/encryption.py", "focal_class": "Decryption", "focal_method": "get_message", "tests": "import unittest\n\nclass Test_Decryption_get_message(unittest.TestCase):\n def test_get_message(self):\n sender_key_bytes = int(self.sender_key.publickey().n.bit_length() / 8)\n decryption = Decryption(self.recipient_key, self.sender_key)\n signature = Random.new().read(sender_key_bytes)\n message = Random.new().read(500)\n decrypted_message = signature + message\n self.assertEqual(message, decryption.get_message(decrypted_message))\n", "method_code": " def get_message(self, decrypted_message):\n sender_key_bytes = int(self.sender_key.publickey().n.bit_length() / 8)\n return decrypted_message[sender_key_bytes:]\n ", "context": "class Decryption(object):\n def get_message(self, decrypted_message): ...\n def __init__(self, recipient_key, sender_key): ...\n def decrypt(self, message): ...\n def get_iv(self, raw): ...\n def get_key(self, raw): ...\n def get_decrypted_message(self, iv, key, raw): ...\n def get_signature(self, decrypted_message): ...\n def verify(self, signature, message): ...\n\n self.sender_key = sender_key\n self.recipient_key = recipient_key\n", "repository": "pedroburon/tbk", "test_name": "test_get_message", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000029.py"} {"focal_file": "tbk/webpay/payment.py", "focal_class": "Payment", "focal_method": "get_process_url", "tests": "import unittest\n\nclass Test_Payment_get_process_url(unittest.TestCase):\n def test_get_process_url_development(self):\n \"\"\"\n payment.get_process_url on dev must return https://certificacion.webpay.cl:6443/filtroUnificado/bp_revision.cgi\n \"\"\"\n commerce = mock.Mock()\n commerce.testing = True\n self.payment_kwargs['commerce'] = commerce\n payment = Payment(**self.payment_kwargs)\n self.assertEqual('https://certificacion.webpay.cl:6443/filtroUnificado/bp_revision.cgi', payment.get_process_url())\n\n def test_get_process_url_production(self):\n \"\"\"\n payment.get_process_url on prod must return https://webpay.transbank.cl:443/filtroUnificado/bp_revision.cgi\n \"\"\"\n commerce = mock.Mock()\n commerce.testing = False\n self.payment_kwargs['commerce'] = commerce\n payment = Payment(**self.payment_kwargs)\n self.assertEqual('https://webpay.transbank.cl:443/filtroUnificado/bp_revision.cgi', payment.get_process_url())\n", "method_code": " def get_process_url(self):\n if self.commerce.testing:\n return 'https://certificacion.webpay.cl:6443/filtroUnificado/bp_revision.cgi'\n return 'https://webpay.transbank.cl:443/filtroUnificado/bp_revision.cgi'\n ", "context": "class Payment(object):\n def get_process_url(self): ...\n def __init__(self, request_ip, amount, order_id, success_url, confirmation_url, session_id=None, failure_url=None, commerce=None): ...\n def redirect_url(self): ...\n def token(self): ...\n def fetch_token(self): ...\n def get_validation_url(self): ...\n def params(self): ...\n def verify(self): ...\n def transaction_id(self): ...\n def get_raw_params(self, splitter='#', include_pseudomac=True): ...\n\n self.commerce = commerce or Commerce.create_commerce()\n self.request_ip = request_ip\n self.amount = clean_amount(amount)\n self.order_id = order_id\n self.success_url = success_url\n self.confirmation_url = confirmation_url\n self.session_id = session_id\n self.failure_url = failure_url or success_url\n\n _token = None\n _params = None\n _transaction_id = None\n", "repository": "pedroburon/tbk", "test_name": "test_get_process_url_development", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000030.py"} {"focal_file": "tbk/webpay/payment.py", "focal_class": "Payment", "focal_method": "fetch_token", "tests": "import unittest\n\nclass Test_Payment_fetch_token(unittest.TestCase):\n @mock.patch('tbk.webpay.payment.requests')\n @mock.patch('tbk.webpay.payment.Payment.get_validation_url')\n @mock.patch('tbk.webpay.payment.Payment.params')\n def test_fetch_token(self, params, get_validation_url, requests):\n \"\"\"\n payment.fetch_token must post data to get_validation_url and get token from response\n \"\"\"\n python_version = '%d.%d' % (sys.version_info.major, sys.version_info.minor)\n user_agent = 'TBK/%(TBK_VERSION_KCC)s (Python/%(PYTHON_VERSION)s)' % {'TBK_VERSION_KCC': TBK_VERSION_KCC, 'PYTHON_VERSION': python_version}\n commerce = self.payment_kwargs['commerce']\n payment = Payment(**self.payment_kwargs)\n response = requests.post.return_value\n response.status_code = 200\n response.is_redirect = False\n decrypted = 'ERROR=0\\nTOKEN=e975ffc4f0605ddf3afc299eee6aeffb59efba24769548acf58e34a89ae4e228\\n'\n signature = 'signature' * 20\n commerce.webpay_decrypt.return_value = (decrypted, signature)\n token = payment.fetch_token()\n requests.post.assert_called_once_with(get_validation_url.return_value, data={'TBK_VERSION_KCC': TBK_VERSION_KCC, 'TBK_CODIGO_COMERCIO': commerce.id, 'TBK_KEY_ID': commerce.webpay_key_id, 'TBK_PARAM': params}, headers={'User-Agent': user_agent}, allow_redirects=False)\n commerce.webpay_decrypt.assert_called_once_with(response.content)\n self.assertEqual(token, 'e975ffc4f0605ddf3afc299eee6aeffb59efba24769548acf58e34a89ae4e228')\n\n @mock.patch('tbk.webpay.payment.requests')\n @mock.patch('tbk.webpay.payment.Payment.get_validation_url')\n @mock.patch('tbk.webpay.payment.Payment.params')\n def test_fetch_token_with_redirect(self, params, get_validation_url, requests):\n \"\"\"\n payment.fetch_token must post data to get_validation_url and get token from response after redirect.\n \"\"\"\n commerce = self.payment_kwargs['commerce']\n payment = Payment(**self.payment_kwargs)\n response1 = mock.Mock()\n response1.is_redirect = True\n response1.status_code = 302\n response2 = mock.Mock()\n response2.is_redirect = False\n response2.status_code = 200\n requests.post.side_effect = [response1, response2]\n decrypted = 'ERROR=0\\nTOKEN=e975ffc4f0605ddf3afc299eee6aeffb59efba24769548acf58e34a89ae4e228\\n'\n signature = 'signature' * 20\n commerce.webpay_decrypt.return_value = (decrypted, signature)\n token = payment.fetch_token()\n commerce.webpay_decrypt.assert_called_once_with(response2.content)\n self.assertEqual(token, 'e975ffc4f0605ddf3afc299eee6aeffb59efba24769548acf58e34a89ae4e228')\n", "method_code": " def fetch_token(self):\n validation_url = self.get_validation_url()\n is_redirect = True\n while is_redirect:\n response = requests.post(validation_url, data={'TBK_VERSION_KCC': TBK_VERSION_KCC, 'TBK_CODIGO_COMERCIO': self.commerce.id, 'TBK_KEY_ID': self.commerce.webpay_key_id, 'TBK_PARAM': self.params}, headers={'User-Agent': USER_AGENT}, allow_redirects=False)\n is_redirect = response.is_redirect\n validation_url = response.headers.get('location')\n if response.status_code != 200:\n raise PaymentError('Payment token generation failed')\n try:\n body, _ = self.commerce.webpay_decrypt(response.content)\n except DecryptionError:\n if get_token_from_body(response.content):\n raise PaymentError('Suspicious message from server: %s' % response.content)\n return get_token_from_body(body)\n ", "context": "class Payment(object):\n def fetch_token(self): ...\n def __init__(self, request_ip, amount, order_id, success_url, confirmation_url, session_id=None, failure_url=None, commerce=None): ...\n def redirect_url(self): ...\n def token(self): ...\n def get_process_url(self): ...\n def get_validation_url(self): ...\n def params(self): ...\n def verify(self): ...\n def transaction_id(self): ...\n def get_raw_params(self, splitter='#', include_pseudomac=True): ...\n\n self.commerce = commerce or Commerce.create_commerce()\n self.request_ip = request_ip\n self.amount = clean_amount(amount)\n self.order_id = order_id\n self.success_url = success_url\n self.confirmation_url = confirmation_url\n self.session_id = session_id\n self.failure_url = failure_url or success_url\n\n _token = None\n _params = None\n _transaction_id = None\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000031.py"} {"focal_file": "tbk/webpay/payment.py", "focal_class": "Payment", "focal_method": "get_validation_url", "tests": "import unittest\n\nclass Test_Payment_get_validation_url(unittest.TestCase):\n def test_get_validation_url_production(self):\n \"\"\"\n payment.get_validation_url on prod. must returns\n https://webpay.transbank.cl:443/filtroUnificado/bp_validacion.cgi\n \"\"\"\n commerce = mock.Mock()\n commerce.testing = False\n self.payment_kwargs['commerce'] = commerce\n payment = Payment(**self.payment_kwargs)\n self.assertEqual('https://webpay.transbank.cl:443/filtroUnificado/bp_validacion.cgi', payment.get_validation_url())\n\n def test_get_validation_url_development(self):\n \"\"\"\n payment.get_validation_url on dev. must returns\n https://certificacion.webpay.cl:6443/filtroUnificado/bp_validacion.cgi\n \"\"\"\n commerce = mock.Mock()\n commerce.testing = True\n self.payment_kwargs['commerce'] = commerce\n payment = Payment(**self.payment_kwargs)\n self.assertEqual('https://certificacion.webpay.cl:6443/filtroUnificado/bp_validacion.cgi', payment.get_validation_url())\n", "method_code": " def get_validation_url(self):\n if self.commerce.testing:\n return 'https://certificacion.webpay.cl:6443/filtroUnificado/bp_validacion.cgi'\n return 'https://webpay.transbank.cl:443/filtroUnificado/bp_validacion.cgi'\n ", "context": "class Payment(object):\n def get_validation_url(self): ...\n def __init__(self, request_ip, amount, order_id, success_url, confirmation_url, session_id=None, failure_url=None, commerce=None): ...\n def redirect_url(self): ...\n def token(self): ...\n def fetch_token(self): ...\n def get_process_url(self): ...\n def params(self): ...\n def verify(self): ...\n def transaction_id(self): ...\n def get_raw_params(self, splitter='#', include_pseudomac=True): ...\n\n self.commerce = commerce or Commerce.create_commerce()\n self.request_ip = request_ip\n self.amount = clean_amount(amount)\n self.order_id = order_id\n self.success_url = success_url\n self.confirmation_url = confirmation_url\n self.session_id = session_id\n self.failure_url = failure_url or success_url\n\n _token = None\n _params = None\n _transaction_id = None\n", "repository": "pedroburon/tbk", "test_name": "test_get_validation_url_production", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000032.py"} {"focal_file": "tbk/webpay/payment.py", "focal_class": "Payment", "focal_method": "get_raw_params", "tests": "import unittest\n\nclass Test_Payment_get_raw_params(unittest.TestCase):\n @mock.patch('tbk.webpay.payment.hashlib')\n def test_get_raw_params(self, hashlib):\n \"\"\"\n payment.get_raw_params returns params as seen on raw_params.txt\n \"\"\"\n h = hashlib.new.return_value\n h.hexdigest.return_value = '8455b5720ff48c0efae649a42b6d1aa2'\n commerce = self.payment_kwargs['commerce']\n commerce.id = '1234567890'\n commerce.webpay_key_id = '101'\n payment = Payment(**self.payment_kwargs)\n payment._transaction_id = 123456789\n get_raw_params_file_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'raw_params.txt')\n with open(get_raw_params_file_path, 'r') as get_raw_params_file:\n get_raw_params = get_raw_params_file.read()\n result = payment.get_raw_params()\n h.hexdigest.assert_called_once_with()\n h.update.assert_any_call(payment.get_raw_params('&', False))\n h.update.assert_any_call(str(payment.commerce.id))\n h.update.assert_any_call('webpay')\n self.assertEqual(get_raw_params, result)\n\n def test_get_raw_params_sharp_no_pseudomac(self):\n \"\"\"\n payment.get_raw_params returns params as seen on get_raw_params_sharp_no_pseudomac.txt\n \"\"\"\n commerce = self.payment_kwargs['commerce']\n commerce.id = '1234567890'\n commerce.webpay_key_id = '101'\n payment = Payment(**self.payment_kwargs)\n payment._transaction_id = 123456789\n get_raw_params_file_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'raw_params_sharp_no_pseudomac.txt')\n with open(get_raw_params_file_path, 'r') as get_raw_params_file:\n get_raw_params = get_raw_params_file.read()\n result = payment.get_raw_params(include_pseudomac=False)\n self.assertEqual(get_raw_params, result)\n", "method_code": " def get_raw_params(self, splitter='#', include_pseudomac=True):\n params = []\n params += ['TBK_ORDEN_COMPRA=%s' % self.order_id]\n params += ['TBK_CODIGO_COMERCIO=%s' % self.commerce.id]\n params += ['TBK_ID_TRANSACCION=%s' % self.transaction_id]\n uri = six.moves.urllib.parse.urlparse(self.confirmation_url)\n params += ['TBK_URL_CGI_COMERCIO=%s' % uri.path]\n params += ['TBK_SERVIDOR_COMERCIO=%s' % uri.hostname]\n params += ['TBK_PUERTO_COMERCIO=%s' % uri.port]\n params += ['TBK_VERSION_KCC=%s' % TBK_VERSION_KCC]\n params += ['TBK_KEY_ID=%s' % self.commerce.webpay_key_id]\n params += ['PARAMVERIFCOM=1']\n if include_pseudomac:\n h = hashlib.new('md5')\n h.update(self.get_raw_params('&', False))\n h.update(str(self.commerce.id))\n h.update('webpay')\n mac = str(h.hexdigest())\n params += ['TBK_MAC=%s' % mac]\n params += ['TBK_MONTO=%d' % int(self.amount * 100)]\n if self.session_id:\n params += ['TBK_ID_SESION=%s' % self.session_id]\n params += ['TBK_URL_EXITO=%s' % self.success_url]\n params += ['TBK_URL_FRACASO=%s' % self.failure_url]\n params += ['TBK_TIPO_TRANSACCION=TR_NORMAL']\n return splitter.join(params)\n ", "context": "class Payment(object):\n def get_raw_params(self, splitter='#', include_pseudomac=True): ...\n def __init__(self, request_ip, amount, order_id, success_url, confirmation_url, session_id=None, failure_url=None, commerce=None): ...\n def redirect_url(self): ...\n def token(self): ...\n def fetch_token(self): ...\n def get_process_url(self): ...\n def get_validation_url(self): ...\n def params(self): ...\n def verify(self): ...\n def transaction_id(self): ...\n\n self.commerce = commerce or Commerce.create_commerce()\n self.request_ip = request_ip\n self.amount = clean_amount(amount)\n self.order_id = order_id\n self.success_url = success_url\n self.confirmation_url = confirmation_url\n self.session_id = session_id\n self.failure_url = failure_url or success_url\n\n _token = None\n _params = None\n _transaction_id = None\n", "repository": "pedroburon/tbk", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000033.py"} {"focal_file": "tbk/webpay/payment.py", "focal_class": "Payment", "focal_method": "verify", "tests": "import unittest\n\nclass Test_Payment_verify(unittest.TestCase):\n def test_verify(self):\n payment = Payment(**self.payment_kwargs)\n self.assertEqual(None, payment.verify())\n", "method_code": " def verify(self):\n if self.commerce is None:\n raise PaymentError('Commerce required')\n if self.amount is None or self.amount <= 0:\n raise PaymentError('Invalid amount %s' % self.amount)\n if self.order_id is None:\n raise PaymentError('Order ID required')\n if self.success_url is None:\n raise PaymentError('Success URL required')\n if self.confirmation_url is None:\n raise PaymentError('Confirmation URL required')\n confirmation_uri = six.moves.urllib.parse.urlparse(self.confirmation_url)\n if re.match('\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}', confirmation_uri.hostname) is None:\n raise PaymentError('Confirmation URL host MUST be an IP address')\n ", "context": "class Payment(object):\n def verify(self): ...\n def __init__(self, request_ip, amount, order_id, success_url, confirmation_url, session_id=None, failure_url=None, commerce=None): ...\n def redirect_url(self): ...\n def token(self): ...\n def fetch_token(self): ...\n def get_process_url(self): ...\n def get_validation_url(self): ...\n def params(self): ...\n def transaction_id(self): ...\n def get_raw_params(self, splitter='#', include_pseudomac=True): ...\n\n self.commerce = commerce or Commerce.create_commerce()\n self.request_ip = request_ip\n self.amount = clean_amount(amount)\n self.order_id = order_id\n self.success_url = success_url\n self.confirmation_url = confirmation_url\n self.session_id = session_id\n self.failure_url = failure_url or success_url\n\n _token = None\n _params = None\n _transaction_id = None\n", "repository": "pedroburon/tbk", "test_name": "test_verify", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000034.py"} {"focal_file": "roman.py", "focal_class": null, "focal_method": "to_roman", "tests": "import unittest\n\nclass Test_to_roman(unittest.TestCase):\n def test_roman_digits(self):\n self.assertEqual('I', to_roman(1))\n self.assertEqual('V', to_roman(5))\n self.assertEqual('X', to_roman(10))\n self.assertEqual('L', to_roman(50))\n self.assertEqual('C', to_roman(100))\n self.assertEqual('D', to_roman(500))\n self.assertEqual('M', to_roman(1000))\n", "method_code": "def to_roman(number):\n result = ''\n while number > 0:\n for key_number, roman in roman_map:\n if key_number <= number:\n result += roman\n number -= key_number\n break\n return result", "context": "def to_roman(number): ...\ndef to_roman(number): ...\n", "repository": "pedroburon/katas", "test_name": "test_roman_digits", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000035.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "exactly", "tests": "import unittest\n\nclass Test_exactly(unittest.TestCase):\n def test_exactly(self):\n \"\"\"\n Test generation of code for the 'exactly' pattern.\n \"\"\"\n x = self.builder.exactly('x')\n self.assertEqual(writePython(x), dd(\"\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n _G_exactly_1\\n \"))\n", "method_code": " def exactly(self, expr):\n return ['Exactly', expr]\n ", "context": "class TreeBuilder(object):\n def exactly(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_exactly", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000036.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "apply", "tests": "import unittest\n\nclass Test_apply(unittest.TestCase):\n def test_apply(self):\n \"\"\"\n Test generation of code for rule application.\n \"\"\"\n one = self.builder.expr('1')\n x = self.builder.expr('x')\n a = self.builder.apply('foo', 'main', one, x)\n self.assertEqual(writePython(a), dd('\\n _G_python_1, lastError = eval(\\'1\\', self.globals, _locals), None\\n self.considerError(lastError)\\n _G_python_2, lastError = eval(\\'x\\', self.globals, _locals), None\\n self.considerError(lastError)\\n _G_apply_3, lastError = self._apply(self.rule_foo, \"foo\", [_G_python_1, _G_python_2])\\n self.considerError(lastError)\\n _G_apply_3\\n '))\n", "method_code": " def apply(self, ruleName, codeName, *exprs):\n return ['Apply', ruleName, codeName, exprs]\n ", "context": "class TreeBuilder(object):\n def apply(self, ruleName, codeName, *exprs): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_apply", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000037.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "many", "tests": "import unittest\n\nclass Test_many(unittest.TestCase):\n def test_many(self):\n \"\"\"\n Test generation of code for matching zero or more instances of\n a pattern.\n \"\"\"\n xs = self.builder.many(self.builder.exactly('x'))\n self.assertEqual(writePython(xs), dd(\"\\n def _G_many_1():\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n _G_many_2, lastError = self.many(_G_many_1)\\n self.considerError(lastError)\\n _G_many_2\\n \"))\n", "method_code": " def many(self, expr):\n return ['Many', expr]\n ", "context": "class TreeBuilder(object):\n def many(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_many", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000038.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "many1", "tests": "import unittest\n\nclass Test_many1(unittest.TestCase):\n def test_many1(self):\n \"\"\"\n Test generation of code for matching one or more instances of\n a pattern.\n \"\"\"\n xs = self.builder.many1(self.builder.exactly('x'))\n self.assertEqual(writePython(xs), dd(\"\\n def _G_many1_1():\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n _G_many1_2, lastError = self.many(_G_many1_1, _G_many1_1())\\n self.considerError(lastError)\\n _G_many1_2\\n \"))\n", "method_code": " def many1(self, expr):\n return ['Many1', expr]\n ", "context": "class TreeBuilder(object):\n def many1(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_many1", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000039.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "_or", "tests": "import unittest\n\nclass Test_or(unittest.TestCase):\n def test_or(self):\n \"\"\"\n Test code generation for a sequence of alternatives.\n \"\"\"\n xy = self.builder._or([self.builder.exactly('x'), self.builder.exactly('y')])\n self.assertEqual(writePython(xy), dd(\"\\n def _G_or_1():\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n def _G_or_2():\\n _G_exactly_1, lastError = self.exactly('y')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n _G_or_3, lastError = self._or([_G_or_1, _G_or_2])\\n self.considerError(lastError)\\n _G_or_3\\n \"))\n", "method_code": " def _or(self, exprs):\n return ['Or', exprs]\n ", "context": "class TreeBuilder(object):\n def _or(self, exprs): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_or", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000040.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "optional", "tests": "import unittest\n\nclass Test_optional(unittest.TestCase):\n def test_optional(self):\n \"\"\"\n Test code generation for optional terms.\n \"\"\"\n x = self.builder.optional(self.builder.exactly('x'))\n self.assertEqual(writePython(x), dd(\"\\n def _G_optional_1():\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n def _G_optional_2():\\n return (None, self.input.nullError())\\n _G_or_3, lastError = self._or([_G_optional_1, _G_optional_2])\\n self.considerError(lastError)\\n _G_or_3\\n \"))\n", "method_code": " def optional(self, expr):\n return ['Optional', expr]\n ", "context": "class TreeBuilder(object):\n def optional(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_optional", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000041.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "_not", "tests": "import unittest\n\nclass Test_not(unittest.TestCase):\n def test_not(self):\n \"\"\"\n Test code generation for negated terms.\n \"\"\"\n x = self.builder._not(self.builder.exactly('x'))\n self.assertEqual(writePython(x), dd(\"\\n def _G_not_1():\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n _G_not_2, lastError = self._not(_G_not_1)\\n self.considerError(lastError)\\n _G_not_2\\n \"))\n", "method_code": " def _not(self, expr):\n return ['Not', expr]\n ", "context": "class TreeBuilder(object):\n def _not(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_not", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000042.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "lookahead", "tests": "import unittest\n\nclass Test_lookahead(unittest.TestCase):\n def test_lookahead(self):\n \"\"\"\n Test code generation for lookahead expressions.\n \"\"\"\n x = self.builder.lookahead(self.builder.exactly('x'))\n self.assertEqual(writePython(x), dd(\"\\n def _G_lookahead_1():\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n _G_lookahead_2, lastError = self.lookahead(_G_lookahead_1)\\n self.considerError(lastError)\\n _G_lookahead_2\\n \"))\n", "method_code": " def lookahead(self, expr):\n return ['Lookahead', expr]\n ", "context": "class TreeBuilder(object):\n def lookahead(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_lookahead", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000043.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "sequence", "tests": "import unittest\n\nclass Test_sequence(unittest.TestCase):\n def test_sequence(self):\n \"\"\"\n Test generation of code for sequence patterns.\n \"\"\"\n x = self.builder.exactly('x')\n y = self.builder.exactly('y')\n z = self.builder.sequence([x, y])\n self.assertEqual(writePython(z), dd(\"\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n _G_exactly_2, lastError = self.exactly('y')\\n self.considerError(lastError)\\n _G_exactly_2\\n \"))\n", "method_code": " def sequence(self, exprs):\n return ['And', exprs]\n ", "context": "class TreeBuilder(object):\n def sequence(self, exprs): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_sequence", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000044.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "bind", "tests": "import unittest\n\nclass Test_bind(unittest.TestCase):\n def test_bind(self):\n \"\"\"\n Test code generation for variable assignment.\n \"\"\"\n x = self.builder.exactly('x')\n b = self.builder.bind(x, 'var')\n self.assertEqual(writePython(b), dd(\"\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n _locals['var'] = _G_exactly_1\\n _locals['var']\\n \"))\n", "method_code": " def bind(self, expr, name):\n return ['Bind', name, expr]\n ", "context": "class TreeBuilder(object):\n def bind(self, expr, name): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_bind", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000045.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "pred", "tests": "import unittest\n\nclass Test_pred(unittest.TestCase):\n def test_pred(self):\n \"\"\"\n Test code generation for predicate expressions.\n \"\"\"\n x = self.builder.pred(self.builder.exactly('x'))\n self.assertEqual(writePython(x), dd(\"\\n def _G_pred_1():\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n _G_pred_2, lastError = self.pred(_G_pred_1)\\n self.considerError(lastError)\\n _G_pred_2\\n \"))\n", "method_code": " def pred(self, expr):\n return ['Predicate', expr]\n ", "context": "class TreeBuilder(object):\n def pred(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_pred", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000046.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "action", "tests": "import unittest\n\nclass Test_action(unittest.TestCase):\n def test_action(self):\n \"\"\"\n Test code generation for semantic actions.\n \"\"\"\n x = self.builder.action('doStuff()')\n self.assertEqual(writePython(x), dd(\"\\n _G_python_1, lastError = eval('doStuff()', self.globals, _locals), None\\n self.considerError(lastError)\\n _G_python_1\\n \"))\n", "method_code": " def action(self, expr):\n return ['Action', expr]\n ", "context": "class TreeBuilder(object):\n def action(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_action", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000047.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "expr", "tests": "import unittest\n\nclass Test_expr(unittest.TestCase):\n def test_expr(self):\n \"\"\"\n Test code generation for semantic predicates.\n \"\"\"\n x = self.builder.expr('returnStuff()')\n code = dd(\"\\n _G_python_1, lastError = eval('returnStuff()', self.globals, _locals), None\\n self.considerError(lastError)\\n _G_python_1\\n \")\n self.assertEqual(writePython(x), code)\n", "method_code": " def expr(self, expr):\n return ['Python', expr]\n ", "context": "class TreeBuilder(object):\n def expr(self, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_expr", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000048.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "listpattern", "tests": "import unittest\n\nclass Test_listpattern(unittest.TestCase):\n def test_listpattern(self):\n \"\"\"\n Test code generation for list patterns.\n \"\"\"\n x = self.builder.listpattern(self.builder.exactly('x'))\n self.assertEqual(writePython(x), dd(\"\\n def _G_listpattern_1():\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n _G_listpattern_2, lastError = self.listpattern(_G_listpattern_1)\\n self.considerError(lastError)\\n _G_listpattern_2\\n \"))\n", "method_code": " def listpattern(self, exprs):\n return ['List', exprs]\n ", "context": "class TreeBuilder(object):\n def listpattern(self, exprs): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def rule(self, name, expr): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_listpattern", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000049.py"} {"focal_file": "pymeta/builder.py", "focal_class": null, "focal_method": "rule", "tests": "import unittest\n\nclass Test_rule(unittest.TestCase):\n def test_rule(self):\n \"\"\"\n Test generation of entire rules.\n \"\"\"\n x = self.builder.rule('foo', self.builder.exactly('x'))\n self.assertEqual(writePython(x), dd(\"\\n def rule_foo(self):\\n _locals = {'self': self}\\n self.locals['foo'] = _locals\\n _G_exactly_1, lastError = self.exactly('x')\\n self.considerError(lastError)\\n return (_G_exactly_1, self.currentError)\\n \"))\n", "method_code": " def rule(self, name, expr):\n return ['Rule', name, expr]\n ", "context": "class TreeBuilder(object):\n def rule(self, name, expr): ...\n def __init__(self, name, grammar=None, *args): ...\n def makeGrammar(self, rules): ...\n def apply(self, ruleName, codeName, *exprs): ...\n def exactly(self, expr): ...\n def match_string(self, expr): ...\n def many(self, expr): ...\n def many1(self, expr): ...\n def optional(self, expr): ...\n def _or(self, exprs): ...\n def _not(self, expr): ...\n def lookahead(self, expr): ...\n def sequence(self, exprs): ...\n def bind(self, expr, name): ...\n def pred(self, expr): ...\n def action(self, expr): ...\n def expr(self, expr): ...\n def listpattern(self, exprs): ...\n\n self.name = name\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_rule", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000050.py"} {"focal_file": "pymeta/runtime.py", "focal_class": "OMetaBase", "focal_method": "rule_anything", "tests": "import unittest\n\nclass Test_OMetaBase_rule_anything(unittest.TestCase):\n def test_anything(self):\n \"\"\"\n L{OMetaBase.rule_anything} returns each item from the input along with\n its position.\n \"\"\"\n data = 'foo'\n o = OMetaBase(data)\n for i, c in enumerate(data):\n v, e = o.rule_anything()\n self.assertEqual((c, i), (v, e[0]))\n", "method_code": " def rule_anything(self):\n \"\"\"\n Match a single item from the input of any kind.\n \"\"\"\n h, p = self.input.head()\n self.input = self.input.tail()\n return (h, p)\n ", "context": "class OMetaBase(object):\n def rule_anything(self): ...\n def __init__(self, string, globals=None): ...\n def parse(cls, source): ...\n def considerError(self, error): ...\n def superApply(self, ruleName, *args): ...\n def apply(self, ruleName, *args): ...\n def _apply(self, rule, ruleName, args): ...\n def exactly(self, wanted): ...\n def many(self, fn, *initial): ...\n def _or(self, fns): ...\n def _not(self, fn): ...\n def eatWhitespace(self): ...\n def pred(self, expr): ...\n def listpattern(self, expr): ...\n def end(self): ...\n def lookahead(self, f): ...\n def match_string(self, tok): ...\n def token(self, tok): ...\n def letter(self): ...\n def letterOrDigit(self): ...\n def anychar(self, chars): ...\n def digit(self): ...\n def pythonExpr(self, endChars='\\r\\n'): ...\n\n self.input = InputStream.fromIterable(string)\n self.locals = {}\n self.currentError = self.input.nullError()\n\n globals = None\n rule_apply = apply\n rule_exactly = exactly\n rule_spaces = eatWhitespace\n rule_end = end\n rule_match_string = match_string\n rule_token = token\n rule_letter = letter\n rule_letterOrDigit = letterOrDigit\n rule_anychar = anychar\n rule_digit = digit\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_anything", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000051.py"} {"focal_file": "pymeta/runtime.py", "focal_class": "OMetaBase", "focal_method": "many", "tests": "import unittest\n\nclass Test_OMetaBase_many(unittest.TestCase):\n def test_many(self):\n \"\"\"\n L{OMetaBase.many} returns a list of parsed values and the error that\n caused the end of the loop.\n \"\"\"\n data = 'ooops'\n o = OMetaBase(data)\n self.assertEqual(o.many(lambda: o.rule_exactly('o')), (['o'] * 3, _MaybeParseError(3, expected(None, 'o'))))\n", "method_code": " def many(self, fn, *initial):\n \"\"\"\n Call C{fn} until it fails to match the input. Collect the resulting\n values into a list.\n \n @param fn: A callable of no arguments.\n @param initial: Initial values to populate the returned list with.\n \"\"\"\n ans = []\n for x, e in initial:\n ans.append(x)\n while True:\n try:\n m = self.input\n v, _ = fn()\n ans.append(v)\n except _MaybeParseError as e:\n self.input = m\n break\n return (ans, e)\n ", "context": "class OMetaBase(object):\n def many(self, fn, *initial): ...\n def __init__(self, string, globals=None): ...\n def parse(cls, source): ...\n def considerError(self, error): ...\n def superApply(self, ruleName, *args): ...\n def apply(self, ruleName, *args): ...\n def _apply(self, rule, ruleName, args): ...\n def rule_anything(self): ...\n def exactly(self, wanted): ...\n def _or(self, fns): ...\n def _not(self, fn): ...\n def eatWhitespace(self): ...\n def pred(self, expr): ...\n def listpattern(self, expr): ...\n def end(self): ...\n def lookahead(self, f): ...\n def match_string(self, tok): ...\n def token(self, tok): ...\n def letter(self): ...\n def letterOrDigit(self): ...\n def anychar(self, chars): ...\n def digit(self): ...\n def pythonExpr(self, endChars='\\r\\n'): ...\n\n self.input = InputStream.fromIterable(string)\n self.locals = {}\n self.currentError = self.input.nullError()\n\n globals = None\n rule_apply = apply\n rule_exactly = exactly\n rule_spaces = eatWhitespace\n rule_end = end\n rule_match_string = match_string\n rule_token = token\n rule_letter = letter\n rule_letterOrDigit = letterOrDigit\n rule_anychar = anychar\n rule_digit = digit\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_many", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000052.py"} {"focal_file": "pymeta/runtime.py", "focal_class": "OMetaBase", "focal_method": "_or", "tests": "import unittest\n\nclass Test_OMetaBase_or(unittest.TestCase):\n def test_or(self):\n \"\"\"\n L{OMetaBase._or} returns the result of the first of its arguments to succeed.\n \"\"\"\n data = 'a'\n o = OMetaBase(data)\n called = [False, False, False]\n targets = ['b', 'a', 'c']\n matchers = []\n for i, m in enumerate(targets):\n\n def match(i=i, m=m):\n called[i] = True\n return o.exactly(m)\n matchers.append(match)\n v, e = o._or(matchers)\n self.assertEqual(called, [True, True, False])\n self.assertEqual(v, 'a')\n self.assertEqual(e[0], 0)\n", "method_code": " def _or(self, fns):\n \"\"\"\n Call each of a list of functions in sequence until one succeeds,\n rewinding the input between each.\n \n @param fns: A list of no-argument callables.\n \"\"\"\n errors = []\n for f in fns:\n try:\n m = self.input\n ret, err = f()\n errors.append(err)\n return (ret, joinErrors(errors))\n except _MaybeParseError as e:\n errors.append(e)\n self.input = m\n raise _MaybeParseError(*joinErrors(errors))\n ", "context": "class OMetaBase(object):\n def _or(self, fns): ...\n def __init__(self, string, globals=None): ...\n def parse(cls, source): ...\n def considerError(self, error): ...\n def superApply(self, ruleName, *args): ...\n def apply(self, ruleName, *args): ...\n def _apply(self, rule, ruleName, args): ...\n def rule_anything(self): ...\n def exactly(self, wanted): ...\n def many(self, fn, *initial): ...\n def _not(self, fn): ...\n def eatWhitespace(self): ...\n def pred(self, expr): ...\n def listpattern(self, expr): ...\n def end(self): ...\n def lookahead(self, f): ...\n def match_string(self, tok): ...\n def token(self, tok): ...\n def letter(self): ...\n def letterOrDigit(self): ...\n def anychar(self, chars): ...\n def digit(self): ...\n def pythonExpr(self, endChars='\\r\\n'): ...\n\n self.input = InputStream.fromIterable(string)\n self.locals = {}\n self.currentError = self.input.nullError()\n\n globals = None\n rule_apply = apply\n rule_exactly = exactly\n rule_spaces = eatWhitespace\n rule_end = end\n rule_match_string = match_string\n rule_token = token\n rule_letter = letter\n rule_letterOrDigit = letterOrDigit\n rule_anychar = anychar\n rule_digit = digit\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_or", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000053.py"} {"focal_file": "pymeta/runtime.py", "focal_class": "OMetaBase", "focal_method": "listpattern", "tests": "import unittest\n\nclass Test_OMetaBase_listpattern(unittest.TestCase):\n def test_listpattern(self):\n \"\"\"\n L{OMetaBase.rule_listpattern} matches contents of lists.\n \"\"\"\n o = OMetaBase([['a']])\n v, e = o.listpattern(lambda: o.exactly('a'))\n self.assertEqual((v, e), (['a'], [0, None]))\n", "method_code": " def listpattern(self, expr):\n \"\"\"\n Call the given function, treating the next object on the stack as an\n iterable to be used for input.\n \n @param expr: A callable of no arguments.\n \"\"\"\n v, e = self.rule_anything()\n oldInput = self.input\n try:\n self.input = InputStream.fromIterable(v)\n except TypeError:\n raise _MaybeParseError(e[0], expected('an iterable'))\n expr()\n self.end()\n self.input = oldInput\n return (v, e)\n ", "context": "class OMetaBase(object):\n def listpattern(self, expr): ...\n def __init__(self, string, globals=None): ...\n def parse(cls, source): ...\n def considerError(self, error): ...\n def superApply(self, ruleName, *args): ...\n def apply(self, ruleName, *args): ...\n def _apply(self, rule, ruleName, args): ...\n def rule_anything(self): ...\n def exactly(self, wanted): ...\n def many(self, fn, *initial): ...\n def _or(self, fns): ...\n def _not(self, fn): ...\n def eatWhitespace(self): ...\n def pred(self, expr): ...\n def end(self): ...\n def lookahead(self, f): ...\n def match_string(self, tok): ...\n def token(self, tok): ...\n def letter(self): ...\n def letterOrDigit(self): ...\n def anychar(self, chars): ...\n def digit(self): ...\n def pythonExpr(self, endChars='\\r\\n'): ...\n\n self.input = InputStream.fromIterable(string)\n self.locals = {}\n self.currentError = self.input.nullError()\n\n globals = None\n rule_apply = apply\n rule_exactly = exactly\n rule_spaces = eatWhitespace\n rule_end = end\n rule_match_string = match_string\n rule_token = token\n rule_letter = letter\n rule_letterOrDigit = letterOrDigit\n rule_anychar = anychar\n rule_digit = digit\n", "repository": "regimantas/nova-pyvascript", "test_name": "test_listpattern", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000054.py"} {"focal_file": "lib/MsneddonContigFilter/MsneddonContigFilterImpl.py", "focal_class": null, "focal_method": "filter_contigs", "tests": "import unittest\n\nclass Test_filter_contigs(unittest.TestCase):\n def test_filter_contigs(self):\n obj_name = 'contigset.1'\n contig1 = {'id': '1', 'length': 10, 'md5': 'md5', 'sequence': 'agcttttcat'}\n contig2 = {'id': '2', 'length': 20, 'md5': 'md5', 'sequence': 'agcttttcatagcttttcat'}\n obj = {'contigs': [contig1, contig2], 'id': 'id', 'md5': 'md5', 'name': 'name', 'source': 'source', 'source_id': 'source_id', 'type': 'type'}\n self.getWsClient().save_objects({'workspace': self.getWsName(), 'objects': [{'type': 'KBaseGenomes.ContigSet', 'name': obj_name, 'data': obj}]})\n ret = self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': obj_name, 'min_length': 15})\n self.assertEqual(ret[0]['n_initial_contigs'], 2)\n self.assertEqual(ret[0]['n_contigs_removed'], 1)\n self.assertEqual(ret[0]['n_contigs_remaining'], 1)\n", "method_code": " def filter_contigs(self, ctx, params):\n print('Starting filter contigs method.')\n workspace_name = params['workspace']\n contigset_id = params['contigset_id']\n min_length = int(params['min_length'])\n token = ctx['token']\n ws = workspaceService(self.workspaceURL, token=token)\n contigSet = ws.get_objects([{'ref': workspace_name + '/' + contigset_id}])[0]['data']\n provenance = None\n if 'provenance' in ctx:\n provenance = ctx['provenance']\n print('Got ContigSet data.')\n good_contigs = []\n n_total = 0\n n_remaining = 0\n for contig in contigSet['contigs']:\n n_total += 1\n if len(contig['sequence']) >= min_length:\n good_contigs.append(contig)\n n_remaining += 1\n contigSet['contigs'] = good_contigs\n print('Filtered ContigSet to ' + str(n_remaining) + ' contigs out of ' + str(n_total))\n obj_info_list = ws.save_objects({'workspace': workspace_name, 'objects': [{'type': 'KBaseGenomes.ContigSet', 'data': contigSet, 'name': contigset_id, 'provenance': provenance}]})\n info = obj_info_list[0]\n print('saved:' + str(info))\n returnVal = {'new_contigset_ref': str(info[6]) + '/' + str(info[0]) + '/' + str(info[4]), 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining}\n print('returning:' + str(returnVal))\n if not isinstance(returnVal, dict):\n raise ValueError('Method filter_contigs return value ' + 'returnVal is not type dict as required.')\n return [returnVal]\n ", "context": "class MsneddonContigFilter():\n def filter_contigs(self, ctx, params): ...\n def __init__(self, config): ...\n\n self.workspaceURL = config['workspace-url']\n\n workspaceURL = None\n", "repository": "msneddon/ContigFilterTest4", "test_name": "test_filter_contigs", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000055.py"} {"focal_file": "lib/ContigFilter/ContigFilterImpl.py", "focal_class": null, "focal_method": "filter_contigs", "tests": "import unittest\n\nclass Test_filter_contigs(unittest.TestCase):\n def test_filter_contigs_ok(self):\n fasta_content = '>seq1 something soemthing asdf\\nagcttttcat\\n>seq2\\nagctt\\n>seq3\\nagcttttcatgg'\n assembly_ref = self.load_fasta_file(os.path.join(self.scratch, 'test1.fasta'), 'TestAssembly', fasta_content)\n ret = self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': assembly_ref, 'min_length': 10})\n self.assertEqual(ret[0]['n_initial_contigs'], 3)\n self.assertEqual(ret[0]['n_contigs_removed'], 1)\n self.assertEqual(ret[0]['n_contigs_remaining'], 2)\n\n def test_filter_contigs_err1(self):\n with self.assertRaises(ValueError) as errorContext:\n self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': '1/fake/3', 'min_length': '-10'})\n self.assertIn('min_length parameter cannot be negative', str(errorContext.exception))\n\n def test_filter_contigs_err2(self):\n with self.assertRaises(ValueError) as errorContext:\n self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': '1/fake/3', 'min_length': 'ten'})\n self.assertIn('Cannot parse integer from min_length parameter', str(errorContext.exception))\n", "method_code": " def filter_contigs(self, ctx, params):\n \"\"\"\n The actual function is declared using 'funcdef' to specify the name\n and input/return arguments to the function. For all typical KBase\n Apps that run in the Narrative, your function should have the \n 'authentication required' modifier.\n :param params: instance of type \"FilterContigsParams\" (A 'typedef'\n can also be used to define compound or container objects, like\n lists, maps, and structures. The standard KBase convention is to\n use structures, as shown here, to define the input and output of\n your function. Here the input is a reference to the Assembly data\n object, a workspace to save output, and a length threshold for\n filtering. To define lists and maps, use a syntax similar to C++\n templates to indicate the type contained in the list or map. For\n example: list list_of_strings; mapping \n map_of_ints;) -> structure: parameter \"assembly_input_ref\" of type\n \"assembly_ref\" (A 'typedef' allows you to provide a more specific\n name for a type. Built-in primitive types include 'string',\n 'int', 'float'. Here we define a type named assembly_ref to\n indicate a string that should be set to a KBase ID reference to an\n Assembly data object.), parameter \"workspace_name\" of String,\n parameter \"min_length\" of Long\n :returns: instance of type \"FilterContigsResults\" (Here is the\n definition of the output of the function. The output can be used\n by other SDK modules which call your code, or the output\n visualizations in the Narrative. 'report_name' and 'report_ref'\n are special output fields- if defined, the Narrative can\n automatically render your Report.) -> structure: parameter\n \"report_name\" of String, parameter \"report_ref\" of String,\n parameter \"assembly_output\" of type \"assembly_ref\" (A 'typedef'\n allows you to provide a more specific name for a type. Built-in\n primitive types include 'string', 'int', 'float'. Here we define\n a type named assembly_ref to indicate a string that should be set\n to a KBase ID reference to an Assembly data object.), parameter\n \"n_initial_contigs\" of Long, parameter \"n_contigs_removed\" of\n Long, parameter \"n_contigs_remaining\" of Long\n \"\"\"\n print('Starting Filter Contigs function. Params=')\n pprint(params)\n print('Validating parameters.')\n if 'workspace_name' not in params:\n raise ValueError('Parameter workspace_name is not set in input arguments')\n workspace_name = params['workspace_name']\n if 'assembly_input_ref' not in params:\n raise ValueError('Parameter assembly_input_ref is not set in input arguments')\n assembly_input_ref = params['assembly_input_ref']\n if 'min_length' not in params:\n raise ValueError('Parameter min_length is not set in input arguments')\n min_length_orig = params['min_length']\n min_length = None\n try:\n min_length = int(min_length_orig)\n except ValueError:\n raise ValueError('Cannot parse integer from min_length parameter (' + str(min_length_orig) + ')')\n if min_length < 0:\n raise ValueError('min_length parameter cannot be negative (' + str(min_length) + ')')\n print('Downloading Assembly data as a Fasta file.')\n assemblyUtil = AssemblyUtil(self.callback_url)\n fasta_file = assemblyUtil.get_assembly_as_fasta({'ref': assembly_input_ref})\n good_contigs = []\n n_total = 0\n n_remaining = 0\n for record in SeqIO.parse(fasta_file['path'], 'fasta'):\n n_total += 1\n if len(record.seq) >= min_length:\n good_contigs.append(record)\n n_remaining += 1\n print('Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total))\n filtered_fasta_file = os.path.join(self.shared_folder, 'filtered.fasta')\n SeqIO.write(good_contigs, filtered_fasta_file, 'fasta')\n print('Uploading filtered Assembly data.')\n new_assembly = assemblyUtil.save_assembly_from_fasta({'file': {'path': filtered_fasta_file}, 'workspace_name': workspace_name, 'assembly_name': fasta_file['assembly_name']})\n reportObj = {'objects_created': [{'ref': new_assembly, 'description': 'Filtered contigs'}], 'text_message': 'Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total)}\n report = KBaseReport(self.callback_url)\n report_info = report.create({'report': reportObj, 'workspace_name': params['workspace_name']})\n output = {'report_name': report_info['name'], 'report_ref': report_info['ref'], 'assembly_output': new_assembly, 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining}\n print('returning:' + pformat(output))\n if not isinstance(output, dict):\n raise ValueError('Method filter_contigs return value ' + 'output is not type dict as required.')\n return [output]\n ", "context": "class ContigFilter():\n def filter_contigs(self, ctx, params): ...\n def __init__(self, config): ...\n def status(self, ctx): ...\n\n self.callback_url = os.environ['SDK_CALLBACK_URL']\n self.shared_folder = config['scratch']\n\n VERSION = '0.0.1'\n GIT_URL = ''\n GIT_COMMIT_HASH = ''\n", "repository": "msneddon/ContigFilter", "test_name": "test_filter_contigs_ok", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000056.py"} {"focal_file": "lib/MsneddonContigFilter3/MsneddonContigFilter3Impl.py", "focal_class": null, "focal_method": "filter_contigs", "tests": "import unittest\n\nclass Test_filter_contigs(unittest.TestCase):\n def test_filter_contigs_ok(self):\n fasta_content = '>seq1 something soemthing asdf\\nagcttttcat\\n>seq2\\nagctt\\n>seq3\\nagcttttcatgg'\n assembly_ref = self.load_fasta_file(os.path.join(self.scratch, 'test1.fasta'), 'TestAssembly', fasta_content)\n ret = self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': assembly_ref, 'min_length': 10})\n self.assertEqual(ret[0]['n_initial_contigs'], 3)\n self.assertEqual(ret[0]['n_contigs_removed'], 1)\n self.assertEqual(ret[0]['n_contigs_remaining'], 2)\n\n def test_filter_contigs_err1(self):\n with self.assertRaises(ValueError) as errorContext:\n self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': '1/fake/3', 'min_length': '-10'})\n self.assertIn('min_length parameter cannot be negative', str(errorContext.exception))\n\n def test_filter_contigs_err2(self):\n with self.assertRaises(ValueError) as errorContext:\n self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': '1/fake/3', 'min_length': 'ten'})\n self.assertIn('Cannot parse integer from min_length parameter', str(errorContext.exception))\n", "method_code": " def filter_contigs(self, ctx, params):\n print('Starting Filter Contigs function. Params=')\n pprint(params)\n print('Validating parameters.')\n if 'workspace_name' not in params:\n raise ValueError('Parameter workspace_name is not set in input arguments')\n workspace_name = params['workspace_name']\n if 'assembly_input_ref' not in params:\n raise ValueError('Parameter assembly_input_ref is not set in input arguments')\n assembly_input_ref = params['assembly_input_ref']\n if 'min_length' not in params:\n raise ValueError('Parameter min_length is not set in input arguments')\n min_length_orig = params['min_length']\n min_length = None\n try:\n min_length = int(min_length_orig)\n except ValueError:\n raise ValueError('Cannot parse integer from min_length parameter (' + str(min_length_orig) + ')')\n if min_length < 0:\n raise ValueError('min_length parameter cannot be negative (' + str(min_length) + ')')\n print('Downloading Assembly data as a Fasta file.')\n assemblyUtil = AssemblyUtil(self.callback_url)\n fasta_file = assemblyUtil.get_assembly_as_fasta({'ref': assembly_input_ref})\n good_contigs = []\n n_total = 0\n n_remaining = 0\n for record in SeqIO.parse(fasta_file['path'], 'fasta'):\n n_total += 1\n if len(record.seq) >= min_length:\n good_contigs.append(record)\n n_remaining += 1\n print('Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total))\n filtered_fasta_file = os.path.join(self.shared_folder, 'filtered.fasta')\n SeqIO.write(good_contigs, filtered_fasta_file, 'fasta')\n print('Uploading filtered Assembly data.')\n new_assembly = assemblyUtil.save_assembly_from_fasta({'file': {'path': filtered_fasta_file}, 'workspace_name': workspace_name, 'assembly_name': fasta_file['assembly_name']})\n reportObj = {'objects_created': [{'ref': new_assembly, 'description': 'Filtered contigs'}], 'text_message': 'Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total)}\n report = KBaseReport(self.callback_url)\n report_info = report.create({'report': reportObj, 'workspace_name': params['workspace_name']})\n output = {'report_name': report_info['name'], 'report_ref': report_info['ref'], 'assembly_output': new_assembly, 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining}\n print('returning:' + pformat(output))\n if not isinstance(output, dict):\n raise ValueError('Method filter_contigs return value ' + 'output is not type dict as required.')\n return [output]\n ", "context": "class MsneddonContigFilter3():\n def filter_contigs(self, ctx, params): ...\n def __init__(self, config): ...\n def status(self, ctx): ...\n\n self.callback_url = os.environ['SDK_CALLBACK_URL']\n self.shared_folder = config['scratch']\n\n VERSION = '0.0.1'\n GIT_URL = ''\n GIT_COMMIT_HASH = ''\n", "repository": "msneddon/MsneddonContigFilter3", "test_name": "test_filter_contigs_ok", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000057.py"} {"focal_file": "lib/QIIME/QIIMEImpl.py", "focal_class": null, "focal_method": "pick_closed_reference_otus", "tests": "import unittest\n\nclass Test_pick_closed_reference_otus(unittest.TestCase):\n def test_pick_closed_reference_otus(self):\n ps_lib_info = self.getPostSplitLibInfo()\n pprint(ps_lib_info)\n params = {'workspace': ps_lib_info[7], 'post_split_lib': ps_lib_info[1], 'otu_table_name': 'OTU_Table', 'rev_strand_match': 1}\n result = self.getQiime().pick_closed_reference_otus(self.getContext(), params)\n print('RESULT:')\n pprint(result)\n return\n", "method_code": " def pick_closed_reference_otus(self, ctx, params):\n print('Running QIIME.pick_closed_reference_otus with params=')\n print(pformat(params))\n objref = ''\n if 'workspace' not in params:\n raise ValueError('workspace parameter is required')\n if 'post_split_lib' not in params:\n raise ValueError('post_split_lib parameter is required')\n if 'otu_table_name' not in params:\n raise ValueError('otu_table_name parameter is required')\n provenance = [{}]\n if 'provenance' in ctx:\n provenance = ctx['provenance']\n provenance[0]['input_ws_objects'] = [params['workspace'] + '/' + params['post_split_lib']]\n ws = workspaceService(self.workspaceURL, token=ctx['token'])\n try:\n objects = ws.get_objects([{'ref': params['workspace'] + '/' + params['post_split_lib']}])\n data = objects[0]['data']\n info = objects[0]['info']\n type_name = info[2].split('.')[1].split('-')[0]\n except Exception as e:\n raise ValueError('Unable to fetch read library object from workspace: ' + str(e))\n input_file_path = os.path.join(self.scratch, data['fasta']['file_name'])\n self.KBaseDataUtil.download_file_from_shock(shock_service_url=data['fasta']['url'], shock_id=data['fasta']['id'], filePath=input_file_path, token=ctx['token'])\n unique_id = str(hex(uuid.getnode()))\n params_file_path = os.path.join(self.scratch, 'parameters_' + unique_id + '.txt')\n if 'parameters_config' in params:\n if params['parameters_config']:\n try:\n objects = ws.get_objects([{'ref': params['workspace'] + '/' + params['parameters_config']}])\n except Exception as e:\n raise ValueError('Unable to fetch parameters configuration from workspace: ' + str(e))\n p_file = open(params_file_path, 'w')\n p_lines = objects[0]['data']['lines']\n for l in p_lines:\n p_file.write(l + '\\n')\n p_file.close()\n provenance[0]['input_ws_objects'].append(params['workspace'] + '/' + params['parameters_config'])\n p_file = open(params_file_path, 'a+')\n if 'rev_strand_match' in params:\n if params['rev_strand_match']:\n p_file.write('pick_otus:enable_rev_strand_match True\\n')\n p_file.close()\n f = open(params_file_path, 'r')\n print('\\nParameters File: ')\n print(f.read())\n print('END Parameters File.\\n')\n f.close()\n out_dir = os.path.join(self.scratch, 'out_' + unique_id)\n cmd = ['pick_closed_reference_otus.py', '-i', input_file_path, '-o', out_dir, '-p', params_file_path]\n print('running: ' + ' '.join(cmd))\n p = subprocess.Popen(cmd, cwd=self.scratch, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)\n stopLogStream = threading.Event()\n logThread = DisplayLogFileThread(out_dir, stopLogStream)\n logThread.start()\n console_messages = ''\n while True:\n line = p.stdout.readline()\n if not line:\n break\n console_messages += line\n print(line.replace('\\n', ''))\n p.stdout.close()\n p.wait()\n stopLogStream.set()\n print('command return code: ' + str(p.returncode))\n if p.returncode != 0:\n raise ValueError('Error running pick_closed_reference_otus.py, return code: ' + str(p.returncode) + ' - ' + console_messages)\n biom_file = os.path.join(out_dir, 'otu_table.biom')\n print('Collecting summary of output OTU Table (' + biom_file + ')')\n cmd = ['biom', 'summarize-table', '-i', biom_file]\n print('running: ' + ' '.join(cmd))\n p = subprocess.Popen(cmd, cwd=self.scratch, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)\n biom_file_summary = ''\n while True:\n line = p.stdout.readline()\n if not line:\n break\n biom_file_summary += line\n print('SUMMARY: ' + line.replace('\\n', ''))\n p.stdout.close()\n p.wait()\n print('command return code: ' + str(p.returncode))\n if p.returncode != 0:\n raise ValueError('Error running biom summarize-table, return code: ' + str(p.returncode) + ' - ' + biom_file_summary)\n print('saving BIOM output: ' + biom_file)\n shock_file = self.KBaseDataUtil.upload_file_to_shock(shock_service_url=self.shockURL, filePath=biom_file, token=ctx['token'])\n hs = HandleService(url=self.handleURL, token=ctx['token'])\n file_handle = hs.persist_handle({'id': shock_file['id'], 'type': 'shock', 'url': self.shockURL, 'file_name': shock_file['file']['name'], 'remote_md5': shock_file['file']['checksum']['md5']})\n otu_tbl = {'biom': {'hid': file_handle, 'file_name': shock_file['file']['name'], 'id': shock_file['id'], 'url': self.shockURL, 'remote_md5': shock_file['file']['checksum']['md5'], 'size': shock_file['file']['size']}, 'summary': biom_file_summary}\n otu_tbl_info = ws.save_objects({'id': info[6], 'objects': [{'type': 'QIIME.OTUTable', 'data': otu_tbl, 'name': params['otu_table_name'], 'meta': {}, 'provenance': provenance}]})[0]\n print(pformat(otu_tbl_info))\n report = ''\n report += 'OTU Table saved to: ' + otu_tbl_info[7] + '/' + otu_tbl_info[1] + '\\n'\n report += 'OTU Table Summary:\\n'\n report += biom_file_summary\n reportObj = {'objects_created': [{'ref': otu_tbl_info[7] + '/' + otu_tbl_info[1], 'description': 'The new OTU Table'}], 'text_message': report}\n reportName = 'QIIME.pick_closed_reference_otus_report_' + str(hex(uuid.getnode()))\n report_obj_info = ws.save_objects({'id': info[6], 'objects': [{'type': 'KBaseReport.Report', 'data': reportObj, 'name': reportName, 'meta': {}, 'hidden': 1, 'provenance': provenance}]})[0]\n returnVal = {'report_name': reportName, 'report_ref': str(report_obj_info[6]) + '/' + str(report_obj_info[0]) + '/' + str(report_obj_info[4]), 'otu_table_ref': str(otu_tbl_info[6]) + '/' + str(otu_tbl_info[0]) + '/' + str(otu_tbl_info[4])}\n if not isinstance(returnVal, dict):\n raise ValueError('Method pick_closed_reference_otus return value ' + 'returnVal is not type dict as required.')\n return [returnVal]\n ", "context": "class QIIME():\n def pick_closed_reference_otus(self, ctx, params): ...\n def __init__(self, config): ...\n def create_parameters_configuration(self, ctx, params): ...\n\n self.workspaceURL = config['workspace-url']\n self.shockURL = config['shock-url']\n self.handleURL = config['handle-service-url']\n self.scratch = os.path.abspath(config['scratch'])\n self.KBaseDataUtil = KBaseDataUtil()\n\n workspaceURL = None\n", "repository": "msneddon/kb_qiime", "test_name": "test_pick_closed_reference_otus", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_000058.py"} {"focal_file": "lib/SneddonContigFilter2/SneddonContigFilter2Impl.py", "focal_class": null, "focal_method": "filter_contigs", "tests": "import unittest\n\nclass Test_filter_contigs(unittest.TestCase):\n def test_filter_contigs_ok(self):\n obj_name = 'contigset.1'\n contig1 = {'id': '1', 'length': 10, 'md5': 'md5', 'sequence': 'agcttttcat'}\n contig2 = {'id': '2', 'length': 5, 'md5': 'md5', 'sequence': 'agctt'}\n contig3 = {'id': '3', 'length': 12, 'md5': 'md5', 'sequence': 'agcttttcatgg'}\n obj1 = {'contigs': [contig1, contig2, contig3], 'id': 'id', 'md5': 'md5', 'name': 'name', 'source': 'source', 'source_id': 'source_id', 'type': 'type'}\n self.getWsClient().save_objects({'workspace': self.getWsName(), 'objects': [{'type': 'KBaseGenomes.ContigSet', 'name': obj_name, 'data': obj1}]})\n ret = self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': obj_name, 'min_length': '10'})\n obj2 = self.getWsClient().get_objects([{'ref': self.getWsName() + '/' + obj_name}])[0]['data']\n self.assertEqual(len(obj2['contigs']), 2)\n self.assertTrue(len(obj2['contigs'][0]['sequence']) >= 10)\n self.assertTrue(len(obj2['contigs'][1]['sequence']) >= 10)\n self.assertEqual(ret[0]['n_initial_contigs'], 3)\n self.assertEqual(ret[0]['n_contigs_removed'], 1)\n self.assertEqual(ret[0]['n_contigs_remaining'], 2)\n\n def test_filter_contigs_err1(self):\n with self.assertRaises(ValueError) as context:\n self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': 'fake', 'min_length': 10})\n self.assertTrue('Error loading original ContigSet object' in str(context.exception))\n\n def test_filter_contigs_err2(self):\n with self.assertRaises(ValueError) as context:\n self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': 'fake', 'min_length': '-10'})\n self.assertTrue(\"min_length parameter shouldn't be negative\" in str(context.exception))\n\n def test_filter_contigs_err3(self):\n with self.assertRaises(ValueError) as context:\n self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': 'fake', 'min_length': 'ten'})\n self.assertTrue('Cannot parse integer from min_length parameter' in str(context.exception))\n", "method_code": " def filter_contigs(self, ctx, params):\n print('Starting filter contigs method.')\n if 'workspace' not in params:\n raise ValueError('Parameter workspace is not set in input arguments')\n workspace_name = params['workspace']\n if 'contigset_id' not in params:\n raise ValueError('Parameter contigset_id is not set in input arguments')\n contigset_id = params['contigset_id']\n if 'min_length' not in params:\n raise ValueError('Parameter min_length is not set in input arguments')\n min_length_orig = params['min_length']\n min_length = None\n try:\n min_length = int(min_length_orig)\n except ValueError:\n raise ValueError('Cannot parse integer from min_length parameter (' + str(min_length_orig) + ')')\n if min_length < 0:\n raise ValueError(\"min_length parameter shouldn't be negative (\" + str(min_length) + ')')\n token = ctx['token']\n wsClient = workspaceService(self.workspaceURL, token=token)\n try:\n contigSet = wsClient.get_objects([{'ref': workspace_name + '/' + contigset_id}])[0]['data']\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n orig_error = ''.join((' ' + line for line in lines))\n raise ValueError('Error loading original ContigSet object from workspace:\\n' + orig_error)\n print('Got ContigSet data.')\n good_contigs = []\n n_total = 0\n n_remaining = 0\n for contig in contigSet['contigs']:\n n_total += 1\n if len(contig['sequence']) >= min_length:\n good_contigs.append(contig)\n n_remaining += 1\n contigSet['contigs'] = good_contigs\n print('Filtered ContigSet to ' + str(n_remaining) + ' contigs out of ' + str(n_total))\n provenance = [{}]\n if 'provenance' in ctx:\n provenance = ctx['provenance']\n provenance[0]['input_ws_objects'] = [workspace_name + '/' + contigset_id]\n obj_info_list = None\n try:\n obj_info_list = wsClient.save_objects({'workspace': workspace_name, 'objects': [{'type': 'KBaseGenomes.ContigSet', 'data': contigSet, 'name': contigset_id, 'provenance': provenance}]})\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n orig_error = ''.join((' ' + line for line in lines))\n raise ValueError('Error saving filtered ContigSet object to workspace:\\n' + orig_error)\n info = obj_info_list[0]\n print('saved ContigSet:' + pformat(info))\n report = 'New ContigSet saved to: ' + str(info[7]) + '/' + str(info[1]) + '/' + str(info[4]) + '\\n'\n report += 'Number of initial contigs: ' + str(n_total) + '\\n'\n report += 'Number of contigs removed: ' + str(n_total - n_remaining) + '\\n'\n report += 'Number of contigs in final set: ' + str(n_remaining) + '\\n'\n reportObj = {'objects_created': [{'ref': str(info[6]) + '/' + str(info[0]) + '/' + str(info[4]), 'description': 'Filtered Contigs'}], 'text_message': report}\n reportName = 'filter_contigs_report_' + str(hex(uuid.getnode()))\n report_info_list = None\n try:\n report_info_list = wsClient.save_objects({'id': info[6], 'objects': [{'type': 'KBaseReport.Report', 'data': reportObj, 'name': reportName, 'meta': {}, 'hidden': 1, 'provenance': provenance}]})\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n orig_error = ''.join((' ' + line for line in lines))\n raise ValueError('Error saving filtered ContigSet object to workspace:\\n' + orig_error)\n report_info = report_info_list[0]\n print('saved Report: ' + pformat(report_info))\n returnVal = {'report_name': reportName, 'report_ref': str(report_info[6]) + '/' + str(report_info[0]) + '/' + str(report_info[4]), 'new_contigset_ref': str(info[6]) + '/' + str(info[0]) + '/' + str(info[4]), 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining}\n print('returning:' + pformat(returnVal))\n if not isinstance(returnVal, object):\n raise ValueError('Method count_contigs return value ' + 'returnVal is not type object as required.')\n return [returnVal]\n ", "context": "class SneddonContigFilter2():\n def filter_contigs(self, ctx, params): ...\n def __init__(self, config): ...\n\n self.workspaceURL = config['workspace-url']\n\n workspaceURL = None\n", "repository": "msneddon/ContigFilterTest2", "test_name": "test_filter_contigs_ok", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000059.py"} {"focal_file": "lib/MsneddonContigFilter4/MsneddonContigFilter4Impl.py", "focal_class": null, "focal_method": "filter_contigs", "tests": "import unittest\n\nclass Test_filter_contigs(unittest.TestCase):\n def test_filter_contigs_ok(self):\n fasta_content = '>seq1 something soemthing asdf\\nagcttttcat\\n>seq2\\nagctt\\n>seq3\\nagcttttcatgg'\n assembly_ref = self.load_fasta_file(os.path.join(self.scratch, 'test1.fasta'), 'TestAssembly', fasta_content)\n ret = self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': assembly_ref, 'min_length': 10})\n self.assertEqual(ret[0]['n_initial_contigs'], 3)\n self.assertEqual(ret[0]['n_contigs_removed'], 1)\n self.assertEqual(ret[0]['n_contigs_remaining'], 2)\n\n def test_filter_contigs_err1(self):\n with self.assertRaises(ValueError) as errorContext:\n self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': '1/fake/3', 'min_length': '-10'})\n self.assertIn('min_length parameter cannot be negative', str(errorContext.exception))\n\n def test_filter_contigs_err2(self):\n with self.assertRaises(ValueError) as errorContext:\n self.getImpl().filter_contigs(self.getContext(), {'workspace_name': self.getWsName(), 'assembly_input_ref': '1/fake/3', 'min_length': 'ten'})\n self.assertIn('Cannot parse integer from min_length parameter', str(errorContext.exception))\n", "method_code": " def filter_contigs(self, ctx, params):\n \"\"\"\n The actual function is declared using 'funcdef' to specify the name\n and input/return arguments to the function. For all typical KBase\n Apps that run in the Narrative, your function should have the \n 'authentication required' modifier.\n :param params: instance of type \"FilterContigsParams\" (A 'typedef'\n can also be used to define compound or container objects, like\n lists, maps, and structures. The standard KBase convention is to\n use structures, as shown here, to define the input and output of\n your function. Here the input is a reference to the Assembly data\n object, a workspace to save output, and a length threshold for\n filtering. To define lists and maps, use a syntax similar to C++\n templates to indicate the type contained in the list or map. For\n example: list list_of_strings; mapping \n map_of_ints;) -> structure: parameter \"assembly_input_ref\" of type\n \"assembly_ref\" (A 'typedef' allows you to provide a more specific\n name for a type. Built-in primitive types include 'string',\n 'int', 'float'. Here we define a type named assembly_ref to\n indicate a string that should be set to a KBase ID reference to an\n Assembly data object.), parameter \"workspace_name\" of String,\n parameter \"min_length\" of Long\n :returns: instance of type \"FilterContigsResults\" (Here is the\n definition of the output of the function. The output can be used\n by other SDK modules which call your code, or the output\n visualizations in the Narrative. 'report_name' and 'report_ref'\n are special output fields- if defined, the Narrative can\n automatically render your Report.) -> structure: parameter\n \"report_name\" of String, parameter \"report_ref\" of String,\n parameter \"assembly_output\" of type \"assembly_ref\" (A 'typedef'\n allows you to provide a more specific name for a type. Built-in\n primitive types include 'string', 'int', 'float'. Here we define\n a type named assembly_ref to indicate a string that should be set\n to a KBase ID reference to an Assembly data object.), parameter\n \"n_initial_contigs\" of Long, parameter \"n_contigs_removed\" of\n Long, parameter \"n_contigs_remaining\" of Long\n \"\"\"\n print('Starting Filter Contigs function. Params=')\n pprint(params)\n print('Validating parameters.')\n if 'workspace_name' not in params:\n raise ValueError('Parameter workspace_name is not set in input arguments')\n workspace_name = params['workspace_name']\n if 'assembly_input_ref' not in params:\n raise ValueError('Parameter assembly_input_ref is not set in input arguments')\n assembly_input_ref = params['assembly_input_ref']\n if 'min_length' not in params:\n raise ValueError('Parameter min_length is not set in input arguments')\n min_length_orig = params['min_length']\n min_length = None\n try:\n min_length = int(min_length_orig)\n except ValueError:\n raise ValueError('Cannot parse integer from min_length parameter (' + str(min_length_orig) + ')')\n if min_length < 0:\n raise ValueError('min_length parameter cannot be negative (' + str(min_length) + ')')\n print('Downloading Assembly data as a Fasta file.')\n assemblyUtil = AssemblyUtil(self.callback_url)\n fasta_file = assemblyUtil.get_assembly_as_fasta({'ref': assembly_input_ref})\n good_contigs = []\n n_total = 0\n n_remaining = 0\n for record in SeqIO.parse(fasta_file['path'], 'fasta'):\n n_total += 1\n if len(record.seq) >= min_length:\n good_contigs.append(record)\n n_remaining += 1\n print('Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total))\n filtered_fasta_file = os.path.join(self.shared_folder, 'filtered.fasta')\n SeqIO.write(good_contigs, filtered_fasta_file, 'fasta')\n print('Uploading filtered Assembly data.')\n new_assembly = assemblyUtil.save_assembly_from_fasta({'file': {'path': filtered_fasta_file}, 'workspace_name': workspace_name, 'assembly_name': fasta_file['assembly_name']})\n reportObj = {'objects_created': [{'ref': new_assembly, 'description': 'Filtered contigs'}], 'text_message': 'Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total)}\n report = KBaseReport(self.callback_url)\n report_info = report.create({'report': reportObj, 'workspace_name': params['workspace_name']})\n output = {'report_name': report_info['name'], 'report_ref': report_info['ref'], 'assembly_output': new_assembly, 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining}\n print('returning:' + pformat(output))\n if not isinstance(output, dict):\n raise ValueError('Method filter_contigs return value ' + 'output is not type dict as required.')\n return [output]\n ", "context": "class MsneddonContigFilter4():\n def filter_contigs(self, ctx, params): ...\n def __init__(self, config): ...\n def status(self, ctx): ...\n\n self.callback_url = os.environ['SDK_CALLBACK_URL']\n self.shared_folder = config['scratch']\n\n VERSION = '0.0.1'\n GIT_URL = ''\n GIT_COMMIT_HASH = ''\n", "repository": "msneddon/MsneddonContigFilter4", "test_name": "test_filter_contigs_ok", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000060.py"} {"focal_file": "lib/MsneddonContigFilter/MsneddonContigFilterImpl.py", "focal_class": null, "focal_method": "filter_contigs", "tests": "import unittest\n\nclass Test_filter_contigs(unittest.TestCase):\n def test_filter_contigs(self):\n obj_name = 'contigset.1'\n contig1 = {'id': '1', 'length': 10, 'md5': 'md5', 'sequence': 'agcttttcat'}\n contig2 = {'id': '2', 'length': 20, 'md5': 'md5', 'sequence': 'agcttttcatagcttttcat'}\n obj = {'contigs': [contig1, contig2], 'id': 'id', 'md5': 'md5', 'name': 'name', 'source': 'source', 'source_id': 'source_id', 'type': 'type'}\n self.getWsClient().save_objects({'workspace': self.getWsName(), 'objects': [{'type': 'KBaseGenomes.ContigSet', 'name': obj_name, 'data': obj}]})\n ret = self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': obj_name, 'min_length': 15})\n self.assertEqual(ret[0]['n_initial_contigs'], 2)\n self.assertEqual(ret[0]['n_contigs_removed'], 1)\n self.assertEqual(ret[0]['n_contigs_remaining'], 1)\n", "method_code": " def filter_contigs(self, ctx, params):\n print('Starting filter contigs method.')\n workspace_name = params['workspace']\n contigset_id = params['contigset_id']\n min_length = int(params['min_length'])\n token = ctx['token']\n ws = workspaceService(self.workspaceURL, token=token)\n contigSet = ws.get_objects([{'ref': workspace_name + '/' + contigset_id}])[0]['data']\n provenance = None\n if 'provenance' in ctx:\n provenance = ctx['provenance']\n print('Got ContigSet data.')\n good_contigs = []\n n_total = 0\n n_remaining = 0\n for contig in contigSet['contigs']:\n n_total += 1\n if len(contig['sequence']) >= min_length:\n good_contigs.append(contig)\n n_remaining += 1\n contigSet['contigs'] = good_contigs\n print('Filtered ContigSet to ' + str(n_remaining) + ' contigs out of ' + str(n_total))\n obj_info_list = ws.save_objects({'workspace': workspace_name, 'objects': [{'type': 'KBaseGenomes.ContigSet', 'data': contigSet, 'name': contigset_id, 'provenance': provenance}]})\n info = obj_info_list[0]\n print('saved:' + str(info))\n returnVal = {'new_contigset_ref': str(info[6]) + '/' + str(info[0]) + '/' + str(info[4]), 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining}\n print('returning:' + str(returnVal))\n if not isinstance(returnVal, dict):\n raise ValueError('Method filter_contigs return value ' + 'returnVal is not type dict as required.')\n return [returnVal]\n ", "context": "class MsneddonContigFilter():\n def filter_contigs(self, ctx, params): ...\n def __init__(self, config): ...\n\n self.workspaceURL = config['workspace-url']\n\n workspaceURL = None\n", "repository": "msneddon/ContigFilterTest", "test_name": "test_filter_contigs", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000061.py"} {"focal_file": "lib/MsneddonContigFilter2/MsneddonContigFilter2Impl.py", "focal_class": null, "focal_method": "filter_contigs", "tests": "import unittest\n\nclass Test_filter_contigs(unittest.TestCase):\n def test_filter_contigs_ok(self):\n obj_name = 'contigset.1'\n contig1 = {'id': '1', 'length': 10, 'md5': 'md5', 'sequence': 'agcttttcat'}\n contig2 = {'id': '2', 'length': 5, 'md5': 'md5', 'sequence': 'agctt'}\n contig3 = {'id': '3', 'length': 12, 'md5': 'md5', 'sequence': 'agcttttcatgg'}\n obj1 = {'contigs': [contig1, contig2, contig3], 'id': 'id', 'md5': 'md5', 'name': 'name', 'source': 'source', 'source_id': 'source_id', 'type': 'type'}\n self.getWsClient().save_objects({'workspace': self.getWsName(), 'objects': [{'type': 'KBaseGenomes.ContigSet', 'name': obj_name, 'data': obj1}]})\n ret = self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': obj_name, 'min_length': '10'})\n obj2 = self.getWsClient().get_objects([{'ref': self.getWsName() + '/' + obj_name}])[0]['data']\n self.assertEqual(len(obj2['contigs']), 2)\n self.assertTrue(len(obj2['contigs'][0]['sequence']) >= 10)\n self.assertTrue(len(obj2['contigs'][1]['sequence']) >= 10)\n self.assertEqual(ret[0]['n_initial_contigs'], 3)\n self.assertEqual(ret[0]['n_contigs_removed'], 1)\n self.assertEqual(ret[0]['n_contigs_remaining'], 2)\n\n def test_filter_contigs_err1(self):\n with self.assertRaises(ValueError) as context:\n self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': 'fake', 'min_length': 10})\n self.assertTrue('Error loading original ContigSet object' in str(context.exception))\n\n def test_filter_contigs_err2(self):\n with self.assertRaises(ValueError) as context:\n self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': 'fake', 'min_length': '-10'})\n self.assertTrue(\"min_length parameter shouldn't be negative\" in str(context.exception))\n\n def test_filter_contigs_err3(self):\n with self.assertRaises(ValueError) as context:\n self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': 'fake', 'min_length': 'ten'})\n self.assertTrue('Cannot parse integer from min_length parameter' in str(context.exception))\n", "method_code": " def filter_contigs(self, ctx, params):\n print('Starting filter contigs method.')\n if 'workspace' not in params:\n raise ValueError('Parameter workspace is not set in input arguments')\n workspace_name = params['workspace']\n if 'contigset_id' not in params:\n raise ValueError('Parameter contigset_id is not set in input arguments')\n contigset_id = params['contigset_id']\n if 'min_length' not in params:\n raise ValueError('Parameter min_length is not set in input arguments')\n min_length_orig = params['min_length']\n min_length = None\n try:\n min_length = int(min_length_orig)\n except ValueError:\n raise ValueError('Cannot parse integer from min_length parameter (' + str(min_length_orig) + ')')\n if min_length < 0:\n raise ValueError(\"min_length parameter shouldn't be negative (\" + str(min_length) + ')')\n token = ctx['token']\n wsClient = workspaceService(self.workspaceURL, token=token)\n try:\n contigSet = wsClient.get_objects([{'ref': workspace_name + '/' + contigset_id}])[0]['data']\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n orig_error = ''.join((' ' + line for line in lines))\n raise ValueError('Error loading original ContigSet object from workspace:\\n' + orig_error)\n print('Got ContigSet data.')\n good_contigs = []\n n_total = 0\n n_remaining = 0\n for contig in contigSet['contigs']:\n n_total += 1\n if len(contig['sequence']) >= min_length:\n good_contigs.append(contig)\n n_remaining += 1\n contigSet['contigs'] = good_contigs\n print('Filtered ContigSet to ' + str(n_remaining) + ' contigs out of ' + str(n_total))\n provenance = [{}]\n if 'provenance' in ctx:\n provenance = ctx['provenance']\n provenance[0]['input_ws_objects'] = [workspace_name + '/' + contigset_id]\n obj_info_list = None\n try:\n obj_info_list = wsClient.save_objects({'workspace': workspace_name, 'objects': [{'type': 'KBaseGenomes.ContigSet', 'data': contigSet, 'name': contigset_id, 'provenance': provenance}]})\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n orig_error = ''.join((' ' + line for line in lines))\n raise ValueError('Error saving filtered ContigSet object to workspace:\\n' + orig_error)\n info = obj_info_list[0]\n print('saved ContigSet:' + pformat(info))\n report = 'New ContigSet saved to: ' + str(info[7]) + '/' + str(info[1]) + '/' + str(info[4]) + '\\n'\n report += 'Number of initial contigs: ' + str(n_total) + '\\n'\n report += 'Number of contigs removed: ' + str(n_total - n_remaining) + '\\n'\n report += 'Number of contigs in final set: ' + str(n_remaining) + '\\n'\n reportObj = {'objects_created': [{'ref': str(info[6]) + '/' + str(info[0]) + '/' + str(info[4]), 'description': 'Filtered Contigs'}], 'text_message': report}\n reportName = 'filter_contigs_report_' + str(hex(uuid.getnode()))\n report_info_list = None\n try:\n report_info_list = wsClient.save_objects({'id': info[6], 'objects': [{'type': 'KBaseReport.Report', 'data': reportObj, 'name': reportName, 'meta': {}, 'hidden': 1, 'provenance': provenance}]})\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n orig_error = ''.join((' ' + line for line in lines))\n raise ValueError('Error saving filtered ContigSet object to workspace:\\n' + orig_error)\n report_info = report_info_list[0]\n print('saved Report: ' + pformat(report_info))\n returnVal = {'report_name': reportName, 'report_ref': str(report_info[6]) + '/' + str(report_info[0]) + '/' + str(report_info[4]), 'new_contigset_ref': str(info[6]) + '/' + str(info[0]) + '/' + str(info[4]), 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining}\n print('returning:' + pformat(returnVal))\n if not isinstance(returnVal, object):\n raise ValueError('Method count_contigs return value ' + 'returnVal is not type object as required.')\n return [returnVal]\n ", "context": "class MsneddonContigFilter2():\n def filter_contigs(self, ctx, params): ...\n def __init__(self, config): ...\n\n self.workspaceURL = config['workspace-url']\n\n workspaceURL = None\n", "repository": "msneddon/MsneddonContigFilter2", "test_name": "test_filter_contigs_ok", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000062.py"} {"focal_file": "lib/SneddonContigCounter/SneddonContigCounterImpl.py", "focal_class": null, "focal_method": "count_contigs", "tests": "import unittest\n\nclass Test_count_contigs(unittest.TestCase):\n def test_count_contigs(self):\n obj_name = 'contigset.1'\n contig = {'id': '1', 'length': 10, 'md5': 'md5', 'sequence': 'agcttttcat'}\n obj = {'contigs': [contig], 'id': 'id', 'md5': 'md5', 'name': 'name', 'source': 'source', 'source_id': 'source_id', 'type': 'type'}\n self.getWsClient().save_objects({'workspace': self.getWsName(), 'objects': [{'type': 'KBaseGenomes.ContigSet', 'name': obj_name, 'data': obj}]})\n ret = self.getImpl().count_contigs(self.getContext(), self.getWsName(), obj_name)\n self.assertEqual(ret[0]['contig_count'], 1)\n", "method_code": " def count_contigs(self, ctx, workspace_name, contigset_id):\n token = ctx['token']\n wsClient = workspaceService(self.workspaceURL, token=token)\n contigSet = wsClient.get_objects([{'ref': workspace_name + '/' + contigset_id}])[0]['data']\n returnVal = {'contig_count': len(contigSet['contigs'])}\n if not isinstance(returnVal, dict):\n raise ValueError('Method count_contigs return value ' + 'returnVal is not type dict as required.')\n return [returnVal]\n ", "context": "class SneddonContigCounter():\n def count_contigs(self, ctx, workspace_name, contigset_id): ...\n def __init__(self, config): ...\n\n self.workspaceURL = config['workspace-url']\n\n workspaceURL = None\n", "repository": "msneddon/contigcount3", "test_name": "test_count_contigs", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000063.py"} {"focal_file": "dataparserlib/dictionary.py", "focal_class": null, "focal_method": "flatten_dictionary_with_int", "tests": "import unittest\n\nclass Test_flatten_dictionary_with_int(unittest.TestCase):\n def test_flatten_dictionary_int_parser(self):\n \"\"\"Test flatten_dictionary_int function.\"\"\"\n flat_project_data_int = flatten_dictionary_with_int(self.dictionary_data)\n self.assertEqual(flat_project_data_int['report']['testinfo.project_name'], 'test')\n", "method_code": "def flatten_dictionary_with_int(dictionary_data):\n \"\"\"Return flat meta report dictionary from nested dictionary with ints.\"\"\"\n meta_dict = META\n meta_dict['report'] = {}\n for item in dictionary_data:\n if type(dictionary_data[item]) is dict:\n for values in dictionary_data[item]:\n if type(dictionary_data[item][values]) is dict:\n for second_values in dictionary_data[item][values]:\n if type(dictionary_data[item][values][second_values]) is dict:\n for third_values in dictionary_data[item][values][second_values]:\n if type(dictionary_data[item][values][second_values][third_values]) is not list or dict or None or (type(dictionary_data[item][values][second_values]) is int):\n debug_dictionary_data = dictionary_data[item][values][second_values][third_values]\n if debug_dictionary_data:\n meta_dict['report'][str(item + '.' + values + '.' + second_values + '.' + third_values)] = str(dictionary_data[item][values][second_values][third_values])\n elif type(dictionary_data[item][values][second_values]) is not list or None or type(dictionary_data[item][values][second_values]) is int:\n none_dictionary_data = str(dictionary_data[item][values][second_values])\n if none_dictionary_data:\n meta_dict['report'][str(item + '.' + values + '.' + second_values)] = str(dictionary_data[item][values][second_values])\n elif type(dictionary_data[item][values]) is not list or None:\n values_dictionary_data = dictionary_data[item][values]\n if values_dictionary_data and str(values_dictionary_data) != 'none' or type(values_dictionary_data) is int:\n meta_dict['report'][str(item + '.' + values)] = str(dictionary_data[item][values])\n elif type(dictionary_data[item]) is list:\n for list_items in dictionary_data[item]:\n dictionary_data_dict = list_items\n if type(dictionary_data_dict) is str:\n meta_dict['report'][item] = dictionary_data_dict\n else:\n meta_dict[item] = dictionary_data[item]\n elif type(dictionary_data[item]) is not list or None:\n dictionary_data_item = dictionary_data[item]\n if dictionary_data_item and str(dictionary_data_item) != 'none':\n meta_dict['report'][item] = dictionary_data[item]\n return meta_dict", "context": "def flatten_dictionary_with_int(dictionary_data): ...\ndef flatten_dictionary_with_int(dictionary_data): ...\ndef flatten_dictionary(json_data): ...\n", "repository": "AUCR/DataParserLib", "test_name": "test_flatten_dictionary_int_parser", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000064.py"} {"focal_file": "dataparserlib/dictionary.py", "focal_class": null, "focal_method": "flatten_dictionary", "tests": "import unittest\n\nclass Test_flatten_dictionary(unittest.TestCase):\n def test_flatten_dictionary_parser(self):\n \"\"\"Test flatten_dictionary_int function.\"\"\"\n flat_project_data = flatten_dictionary(self.dictionary_data)\n self.assertEqual(flat_project_data['report']['testinfo.project_name'], 'test')\n", "method_code": "def flatten_dictionary(json_data):\n \"\"\"Return flat meta report dictionary from nested dictionary.\"\"\"\n meta = {}\n meta['report'] = {}\n for item in json_data:\n if type(json_data[item]) is dict:\n for values in json_data[item]:\n if type(json_data[item][values]) is dict:\n for second_values in json_data[item][values]:\n if type(json_data[item][values][second_values]) is dict:\n for third_values in json_data[item][values][second_values]:\n if type(json_data[item][values][second_values][third_values]) is not list or dict or None:\n debug_test = json_data[item][values][second_values][third_values]\n if debug_test:\n meta['report'][str(item + '.' + values + '.' + second_values + '.' + third_values)] = str(json_data[item][values][second_values][third_values])\n elif type(json_data[item][values][second_values]) is not list or None:\n none_test = str(json_data[item][values][second_values])\n if none_test:\n meta['report'][str(item + '.' + values + '.' + second_values)] = str(json_data[item][values][second_values])\n elif type(json_data[item][values]) is not list or None:\n values_test = json_data[item][values]\n if values_test and str(values_test) != 'none':\n meta['report'][str(item + '.' + values)] = str(json_data[item][values])\n elif type(json_data[item]) is list:\n for list_items in json_data[item]:\n test_dict = list_items\n if type(test_dict) is str:\n meta['report'][item] = test_dict\n else:\n meta[item] = json_data[item]\n elif type(json_data[item]) is not list or None:\n test_item = json_data[item]\n if test_item and str(test_item) != '\"':\n meta['report'][item] = json_data[item]\n return meta", "context": "def flatten_dictionary(json_data): ...\ndef flatten_dictionary_with_int(dictionary_data): ...\ndef flatten_dictionary(json_data): ...\n", "repository": "AUCR/DataParserLib", "test_name": "test_flatten_dictionary_parser", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000065.py"} {"focal_file": "lib/Cython/Compiler/UtilityCode.py", "focal_class": null, "focal_method": "load_as_string", "tests": "import unittest\n\nclass Test_load_as_string(unittest.TestCase):\n def test_load_as_string(self):\n got = strip_2tup(self.cls.load_as_string(self.name, context=self.context))\n self.assertEquals(got, self.expected_tempita)\n", "method_code": " def load_as_string(cls, util_code_name, from_file=None, **kwargs):\n \"\"\"\n Load a utility code as a string. Returns (proto, implementation)\n \"\"\"\n util = cls.load(util_code_name, from_file, **kwargs)\n return (util.proto, util.impl)\n ", "context": "class CythonUtilityCode(Code.UtilityCodeBase):\n @classmethod\n def load_as_string(cls, util_code_name, from_file=None, **kwargs): ...\n def __init__(self, impl, name='__pyxutil', prefix='', requires=None, file=None, from_scope=None, context=None, compiler_directives=None, outer_module_scope=None): ...\n def __eq__(self, other): ...\n def _equality_params(self): ...\n def __hash__(self): ...\n def get_tree(self, entries_only=False, cython_scope=None): ...\n def put_code(self, output): ...\n def declare_in_scope(self, dest_scope, used=False, cython_scope=None, whitelist=None): ...\n\n self.impl = impl\n self.name = name\n self.file = file\n self.prefix = prefix\n self.requires = requires or []\n self.from_scope = from_scope\n self.outer_module_scope = outer_module_scope\n self.compiler_directives = compiler_directives\n\n is_cython_utility = True\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_load_as_string", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000066.py"} {"focal_file": "lib/Cython/StringIOTree.py", "focal_class": null, "focal_method": "allmarkers", "tests": "import unittest\n\nclass Test_allmarkers(unittest.TestCase):\n def test_markers(self):\n assert not self.tree.allmarkers()\n", "method_code": " def allmarkers(self):\n children = self.prepended_children\n return [m for c in children for m in c.allmarkers()] + self.markers\n ", "context": "class StringIOTree(object):\n def allmarkers(self): ...\n def __init__(self, stream=None): ...\n def getvalue(self): ...\n def copyto(self, target): ...\n def commit(self): ...\n def insert(self, iotree): ...\n def insertion_point(self): ...\n\n self.prepended_children = []\n self.stream = stream\n self.write = stream.write\n self.markers = []\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_markers", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000067.py"} {"focal_file": "lib/Cython/StringIOTree.py", "focal_class": null, "focal_method": "insertion_point", "tests": "import unittest\n\nclass Test_insertion_point(unittest.TestCase):\n def test_insertion(self):\n self.write_lines((1, 2, 3))\n line_4_to_6_insertion_point = self.tree.insertion_point()\n self.write_lines((7, 8))\n line_9_to_13_insertion_point = self.tree.insertion_point()\n self.write_lines((14, 15, 16))\n line_4_insertion_point = line_4_to_6_insertion_point.insertion_point()\n self.write_lines((5, 6), tree=line_4_to_6_insertion_point)\n line_9_to_12_insertion_point = line_9_to_13_insertion_point.insertion_point()\n self.write_line(13, tree=line_9_to_13_insertion_point)\n self.write_line(4, tree=line_4_insertion_point)\n self.write_line(9, tree=line_9_to_12_insertion_point)\n line_10_insertion_point = line_9_to_12_insertion_point.insertion_point()\n self.write_line(11, tree=line_9_to_12_insertion_point)\n self.write_line(10, tree=line_10_insertion_point)\n self.write_line(12, tree=line_9_to_12_insertion_point)\n self.assertEqual(self.tree.allmarkers(), list(range(1, 17)))\n self.assertEqual(code.strip(), self.tree.getvalue().strip())\n", "method_code": " def insertion_point(self):\n \"\"\"\n Returns a new StringIOTree, which is left behind at the current position\n (it what is written to the result will appear right before whatever is\n next written to self).\n \n Calling getvalue() or copyto() on the result will only return the\n contents written to it.\n \"\"\"\n self.commit()\n other = StringIOTree()\n self.prepended_children.append(other)\n return other\n ", "context": "class StringIOTree(object):\n def insertion_point(self): ...\n def __init__(self, stream=None): ...\n def getvalue(self): ...\n def copyto(self, target): ...\n def commit(self): ...\n def insert(self, iotree): ...\n def allmarkers(self): ...\n\n self.prepended_children = []\n self.stream = stream\n self.write = stream.write\n self.markers = []\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_insertion", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000068.py"} {"focal_file": "lib/DateTime/DateTime.py", "focal_class": "DateTime", "focal_method": "tzoffset", "tests": "import unittest\n\nclass Test_DateTime_tzoffset(unittest.TestCase):\n def test_tzoffset(self):\n dt = DateTime('Tue, 10 Sep 2001 09:41:03 GMT')\n self.assertEqual(dt.tzoffset(), 0)\n dt = DateTime('Tue, 2 Mar 2001 09:41:03 GMT+3')\n self.assertEqual(dt.tzoffset(), 10800)\n dt = DateTime('Tue, 21 Jan 2001 09:41:03 PST')\n self.assertEqual(dt.tzoffset(), -28800)\n dt = DateTime('Tue, 24 Aug 2001 09:41:03 PST')\n self.assertEqual(dt.tzoffset(), -25200)\n dt = DateTime('Tue, 24 Jul 2001 09:41:03 -0400')\n self.assertEqual(dt.tzoffset(), -14400)\n dt = DateTime('Tue, 6 Dec 1966 01:41:03 +0200')\n self.assertEqual(dt.tzoffset(), 7200)\n dt = DateTime('Tue, 24 Jul 2001 09:41:03 -0637')\n self.assertEqual(dt.tzoffset(), -23820)\n dt = DateTime('Tue, 24 Jul 2001 09:41:03 +0425')\n self.assertEqual(dt.tzoffset(), 15900)\n", "method_code": " def tzoffset(self):\n \"\"\"Return the timezone offset for the objects timezone.\"\"\"\n return _tzoffset(self._tz, self._t)\n ", "context": "class DateTime(object):\n def tzoffset(self): ...\n def __init__(self, *args, **kw): ...\n def __getstate__(self): ...\n def __setstate__(self, value): ...\n def _parse_args(self, *args, **kw): ...\n def localZone(self, ltm=None): ...\n def _calcTimezoneName(self, x, ms): ...\n def _parse(self, st, datefmt=getDefaultDateFormat()): ...\n def _validDate(self, y, m, d): ...\n def _validTime(self, h, m, s): ...\n def __getattr__(self, name): ...\n def timeTime(self): ...\n def toZone(self, z): ...\n def isFuture(self): ...\n def isPast(self): ...\n def isCurrentYear(self): ...\n def isCurrentMonth(self): ...\n def isCurrentDay(self): ...\n def isCurrentHour(self): ...\n def isCurrentMinute(self): ...\n def earliestTime(self): ...\n def latestTime(self): ...\n def greaterThan(self, t): ...\n def greaterThanEqualTo(self, t): ...\n def equalTo(self, t): ...\n def notEqualTo(self, t): ...\n def __eq__(self, t): ...\n def __ne__(self, t): ...\n def lessThan(self, t): ...\n def lessThanEqualTo(self, t): ...\n def isLeapYear(self): ...\n def dayOfYear(self): ...\n def parts(self): ...\n def timezone(self): ...\n def year(self): ...\n def month(self): ...\n def _fmon(self): ...\n def Month(self): ...\n def _amon(self): ...\n def aMonth(self): ...\n def Mon(self): ...\n def _pmon(self): ...\n def pMonth(self): ...\n def Mon_(self): ...\n def day(self): ...\n def _fday(self): ...\n def Day(self): ...\n def DayOfWeek(self): ...\n def _aday(self): ...\n def aDay(self): ...\n def _pday(self): ...\n def pDay(self): ...\n def Day_(self): ...\n def dow(self): ...\n def dow_1(self): ...\n def _pmhour(self): ...\n def h_12(self): ...\n def h_24(self): ...\n def _pm(self): ...\n def ampm(self): ...\n def hour(self): ...\n def minute(self): ...\n def second(self): ...\n def millis(self): ...\n def micros(self): ...\n def timezoneNaive(self): ...\n def strftime(self, format): ...\n def Date(self): ...\n def Time(self): ...\n def TimeMinutes(self): ...\n def AMPM(self): ...\n def AMPMMinutes(self): ...\n def PreciseTime(self): ...\n def PreciseAMPM(self): ...\n def yy(self): ...\n def mm(self): ...\n def dd(self): ...\n def rfc822(self): ...\n def fCommon(self): ...\n def fCommonZ(self): ...\n def aCommon(self): ...\n def aCommonZ(self): ...\n def pCommon(self): ...\n def pCommonZ(self): ...\n def ISO(self): ...\n def ISO8601(self): ...\n def HTML4(self): ...\n def asdatetime(self): ...\n def utcdatetime(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __repr__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __int__(self): ...\n def __long__(self): ...\n def __float__(self): ...\n def _t(self): ...\n def _parse_iso8601(self, s): ...\n def _parse_iso8601_preserving_tznaive(self, s): ...\n def __parse_iso8601(self, s): ...\n def JulianDay(self): ...\n def week(self): ...\n def encode(self, out): ...\n\n __roles__ = None\n __allow_access_to_unprotected_subobjects__ = 1\n __slots__ = ('_timezone_naive', '_tz', '_dayoffset', '_year', '_month', '_day', '_hour', '_minute', '_second', '_nearsec', '_d', '_micros', 'time')\n __gt__ = greaterThan\n __ge__ = greaterThanEqualTo\n __lt__ = lessThan\n __le__ = lessThanEqualTo\n __radd__ = __add__\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_tzoffset", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000069.py"} {"focal_file": "lib/DateTime/DateTime.py", "focal_class": "DateTime", "focal_method": "ISO8601", "tests": "import unittest\n\nclass Test_DateTime_ISO8601(unittest.TestCase):\n def testISO8601(self):\n ref0 = DateTime('2002/5/2 8:00am GMT')\n ref1 = DateTime('2002/5/2 8:00am US/Eastern')\n ref2 = DateTime('2006/11/6 10:30 GMT')\n ref3 = DateTime('2004/06/14 14:30:15 GMT-3')\n ref4 = DateTime('2006/01/01 GMT')\n isoDt = DateTime('2002-05-02T08:00:00')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002-05-02T08:00:00Z')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002-05-02T08:00:00+00:00')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002-05-02T08:00:00-04:00')\n self.assertTrue(ref1.equalTo(isoDt))\n isoDt = DateTime('2002-05-02 08:00:00-04:00')\n self.assertTrue(ref1.equalTo(isoDt))\n isoDt = DateTime('2002-05-02T08:00:00-0400')\n self.assertTrue(ref1.equalTo(isoDt))\n isoDt = DateTime('2006-01-01')\n self.assertTrue(ref4.equalTo(isoDt))\n isoDt = DateTime('200601-01')\n self.assertTrue(ref4.equalTo(isoDt))\n isoDt = DateTime('20060101')\n self.assertTrue(ref4.equalTo(isoDt))\n isoDt = DateTime('2006-01')\n self.assertTrue(ref4.equalTo(isoDt))\n isoDt = DateTime('200601')\n self.assertTrue(ref4.equalTo(isoDt))\n isoDt = DateTime('2006')\n self.assertTrue(ref4.equalTo(isoDt))\n isoDt = DateTime('20020502T08:00:00')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002-05-02T080000')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('20020502T080000')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('20020502T080000+0')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('20020502 080000-4')\n self.assertTrue(ref1.equalTo(isoDt))\n isoDt = DateTime('20020502T080000-400')\n self.assertTrue(ref1.equalTo(isoDt))\n isoDt = DateTime('20020502T080000-4:00')\n self.assertTrue(ref1.equalTo(isoDt))\n isoDt = DateTime('2002-05-02T0800')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002-05-02T08')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002-W18-4T0800')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002-W184T0800')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002W18-4T0800')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002W184T08')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2004-W25-1T14:30:15-03:00')\n self.assertTrue(ref3.equalTo(isoDt))\n isoDt = DateTime('2004-W25T14:30:15-03:00')\n self.assertTrue(ref3.equalTo(isoDt))\n isoDt = DateTime('2002-122T0800')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2002122T0800')\n self.assertTrue(ref0.equalTo(isoDt))\n isoDt = DateTime('2006-11-06T10.5')\n self.assertTrue(ref2.equalTo(isoDt))\n isoDt = DateTime('2006-11-06T10,5')\n self.assertTrue(ref2.equalTo(isoDt))\n isoDt = DateTime('20040614T1430.25-3')\n self.assertTrue(ref3.equalTo(isoDt))\n isoDt = DateTime('2004-06-14T1430,25-3')\n self.assertTrue(ref3.equalTo(isoDt))\n isoDt = DateTime('2004-06-14T14:30.25-3')\n self.assertTrue(ref3.equalTo(isoDt))\n isoDt = DateTime('20040614T14:30,25-3')\n self.assertTrue(ref3.equalTo(isoDt))\n iso8601_string = '2002-05-02T08:00:00-04:00'\n iso8601DT = DateTime(iso8601_string)\n self.assertEqual(iso8601_string, iso8601DT.ISO8601())\n isoDt = DateTime('2006-01-01 00:00:00')\n self.assertTrue(ref4.equalTo(isoDt))\n", "method_code": " def ISO8601(self):\n \"\"\"Return the object in ISO 8601-compatible format containing the\n date, time with seconds-precision and the time zone identifier.\n \n See: http://www.w3.org/TR/NOTE-datetime\n \n Dates are output as: YYYY-MM-DDTHH:MM:SSTZD\n T is a literal character.\n TZD is Time Zone Designator, format +HH:MM or -HH:MM\n \n If the instance is timezone naive (it was not specified with a timezone\n when it was constructed) then the timezone is ommitted.\n \n The HTML4 method below offers the same formatting, but converts\n to UTC before returning the value and sets the TZD \"Z\".\n \"\"\"\n if self.timezoneNaive():\n return '%0.4d-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d' % (self._year, self._month, self._day, self._hour, self._minute, self._second)\n tzoffset = _tzoffset2iso8601zone(_tzoffset(self._tz, self._t))\n return '%0.4d-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d%s' % (self._year, self._month, self._day, self._hour, self._minute, self._second, tzoffset)\n ", "context": "class DateTime(object):\n def ISO8601(self): ...\n def __init__(self, *args, **kw): ...\n def __getstate__(self): ...\n def __setstate__(self, value): ...\n def _parse_args(self, *args, **kw): ...\n def localZone(self, ltm=None): ...\n def _calcTimezoneName(self, x, ms): ...\n def _parse(self, st, datefmt=getDefaultDateFormat()): ...\n def _validDate(self, y, m, d): ...\n def _validTime(self, h, m, s): ...\n def __getattr__(self, name): ...\n def timeTime(self): ...\n def toZone(self, z): ...\n def isFuture(self): ...\n def isPast(self): ...\n def isCurrentYear(self): ...\n def isCurrentMonth(self): ...\n def isCurrentDay(self): ...\n def isCurrentHour(self): ...\n def isCurrentMinute(self): ...\n def earliestTime(self): ...\n def latestTime(self): ...\n def greaterThan(self, t): ...\n def greaterThanEqualTo(self, t): ...\n def equalTo(self, t): ...\n def notEqualTo(self, t): ...\n def __eq__(self, t): ...\n def __ne__(self, t): ...\n def lessThan(self, t): ...\n def lessThanEqualTo(self, t): ...\n def isLeapYear(self): ...\n def dayOfYear(self): ...\n def parts(self): ...\n def timezone(self): ...\n def tzoffset(self): ...\n def year(self): ...\n def month(self): ...\n def _fmon(self): ...\n def Month(self): ...\n def _amon(self): ...\n def aMonth(self): ...\n def Mon(self): ...\n def _pmon(self): ...\n def pMonth(self): ...\n def Mon_(self): ...\n def day(self): ...\n def _fday(self): ...\n def Day(self): ...\n def DayOfWeek(self): ...\n def _aday(self): ...\n def aDay(self): ...\n def _pday(self): ...\n def pDay(self): ...\n def Day_(self): ...\n def dow(self): ...\n def dow_1(self): ...\n def _pmhour(self): ...\n def h_12(self): ...\n def h_24(self): ...\n def _pm(self): ...\n def ampm(self): ...\n def hour(self): ...\n def minute(self): ...\n def second(self): ...\n def millis(self): ...\n def micros(self): ...\n def timezoneNaive(self): ...\n def strftime(self, format): ...\n def Date(self): ...\n def Time(self): ...\n def TimeMinutes(self): ...\n def AMPM(self): ...\n def AMPMMinutes(self): ...\n def PreciseTime(self): ...\n def PreciseAMPM(self): ...\n def yy(self): ...\n def mm(self): ...\n def dd(self): ...\n def rfc822(self): ...\n def fCommon(self): ...\n def fCommonZ(self): ...\n def aCommon(self): ...\n def aCommonZ(self): ...\n def pCommon(self): ...\n def pCommonZ(self): ...\n def ISO(self): ...\n def HTML4(self): ...\n def asdatetime(self): ...\n def utcdatetime(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __repr__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __int__(self): ...\n def __long__(self): ...\n def __float__(self): ...\n def _t(self): ...\n def _parse_iso8601(self, s): ...\n def _parse_iso8601_preserving_tznaive(self, s): ...\n def __parse_iso8601(self, s): ...\n def JulianDay(self): ...\n def week(self): ...\n def encode(self, out): ...\n\n __roles__ = None\n __allow_access_to_unprotected_subobjects__ = 1\n __slots__ = ('_timezone_naive', '_tz', '_dayoffset', '_year', '_month', '_day', '_hour', '_minute', '_second', '_nearsec', '_d', '_micros', 'time')\n __gt__ = greaterThan\n __ge__ = greaterThanEqualTo\n __lt__ = lessThan\n __le__ = lessThanEqualTo\n __radd__ = __add__\n", "repository": "designspired/TaskManagerGAE", "test_name": "testISO8601", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000070.py"} {"focal_file": "lib/DateTime/DateTime.py", "focal_class": "DateTime", "focal_method": "_calcTimezoneName", "tests": "import unittest\n\nclass Test_DateTime_calcTimezoneName(unittest.TestCase):\n def test_calcTimezoneName(self):\n from DateTime.interfaces import TimeError\n timezone_dependent_epoch = 2177452800\n try:\n DateTime()._calcTimezoneName(timezone_dependent_epoch, 0)\n except TimeError:\n self.fail('Zope Collector issue #484 (negative time bug): TimeError raised')\n", "method_code": " def _calcTimezoneName(self, x, ms):\n if not _multipleZones:\n return _localzone0\n fsetAtEpoch = _tzoffset(_localzone0, 0.0)\n nearTime = x - fsetAtEpoch - long(EPOCH) + 86400 + ms\n try:\n ltm = safelocaltime(nearTime)\n except:\n yr, mo, dy, hr, mn, sc = _calcYMDHMS(x, 0)\n yr = (yr - 1970) % 28 + 1970\n x = _calcDependentSecond2(yr, mo, dy, hr, mn, sc)\n nearTime = x - fsetAtEpoch - long(EPOCH) + 86400 + ms\n nearTime = max(0, nearTime)\n ltm = safelocaltime(nearTime)\n tz = self.localZone(ltm)\n return tz\n ", "context": "class DateTime(object):\n def _calcTimezoneName(self, x, ms): ...\n def __init__(self, *args, **kw): ...\n def __getstate__(self): ...\n def __setstate__(self, value): ...\n def _parse_args(self, *args, **kw): ...\n def localZone(self, ltm=None): ...\n def _parse(self, st, datefmt=getDefaultDateFormat()): ...\n def _validDate(self, y, m, d): ...\n def _validTime(self, h, m, s): ...\n def __getattr__(self, name): ...\n def timeTime(self): ...\n def toZone(self, z): ...\n def isFuture(self): ...\n def isPast(self): ...\n def isCurrentYear(self): ...\n def isCurrentMonth(self): ...\n def isCurrentDay(self): ...\n def isCurrentHour(self): ...\n def isCurrentMinute(self): ...\n def earliestTime(self): ...\n def latestTime(self): ...\n def greaterThan(self, t): ...\n def greaterThanEqualTo(self, t): ...\n def equalTo(self, t): ...\n def notEqualTo(self, t): ...\n def __eq__(self, t): ...\n def __ne__(self, t): ...\n def lessThan(self, t): ...\n def lessThanEqualTo(self, t): ...\n def isLeapYear(self): ...\n def dayOfYear(self): ...\n def parts(self): ...\n def timezone(self): ...\n def tzoffset(self): ...\n def year(self): ...\n def month(self): ...\n def _fmon(self): ...\n def Month(self): ...\n def _amon(self): ...\n def aMonth(self): ...\n def Mon(self): ...\n def _pmon(self): ...\n def pMonth(self): ...\n def Mon_(self): ...\n def day(self): ...\n def _fday(self): ...\n def Day(self): ...\n def DayOfWeek(self): ...\n def _aday(self): ...\n def aDay(self): ...\n def _pday(self): ...\n def pDay(self): ...\n def Day_(self): ...\n def dow(self): ...\n def dow_1(self): ...\n def _pmhour(self): ...\n def h_12(self): ...\n def h_24(self): ...\n def _pm(self): ...\n def ampm(self): ...\n def hour(self): ...\n def minute(self): ...\n def second(self): ...\n def millis(self): ...\n def micros(self): ...\n def timezoneNaive(self): ...\n def strftime(self, format): ...\n def Date(self): ...\n def Time(self): ...\n def TimeMinutes(self): ...\n def AMPM(self): ...\n def AMPMMinutes(self): ...\n def PreciseTime(self): ...\n def PreciseAMPM(self): ...\n def yy(self): ...\n def mm(self): ...\n def dd(self): ...\n def rfc822(self): ...\n def fCommon(self): ...\n def fCommonZ(self): ...\n def aCommon(self): ...\n def aCommonZ(self): ...\n def pCommon(self): ...\n def pCommonZ(self): ...\n def ISO(self): ...\n def ISO8601(self): ...\n def HTML4(self): ...\n def asdatetime(self): ...\n def utcdatetime(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __repr__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __int__(self): ...\n def __long__(self): ...\n def __float__(self): ...\n def _t(self): ...\n def _parse_iso8601(self, s): ...\n def _parse_iso8601_preserving_tznaive(self, s): ...\n def __parse_iso8601(self, s): ...\n def JulianDay(self): ...\n def week(self): ...\n def encode(self, out): ...\n\n __roles__ = None\n __allow_access_to_unprotected_subobjects__ = 1\n __slots__ = ('_timezone_naive', '_tz', '_dayoffset', '_year', '_month', '_day', '_hour', '_minute', '_second', '_nearsec', '_d', '_micros', 'time')\n __gt__ = greaterThan\n __ge__ = greaterThanEqualTo\n __lt__ = lessThan\n __le__ = lessThanEqualTo\n __radd__ = __add__\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_calcTimezoneName", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000071.py"} {"focal_file": "lib/DateTime/DateTime.py", "focal_class": "DateTime", "focal_method": "strftime", "tests": "import unittest\n\nclass Test_DateTime_strftime(unittest.TestCase):\n def testStrftimeTZhandling(self):\n format = '%Y-%m-%d %H:%M %Z'\n dt = DateTime('Wed, 19 Nov 2003 18:32:07 -0215')\n dt_string = dt.strftime(format)\n dt_local = dt.toZone(_findLocalTimeZoneName(0))\n dt_localstring = dt_local.strftime(format)\n self.assertEqual(dt_string, dt_localstring)\n\n def testStrftimeFarDates(self):\n dt = DateTime('1900/01/30')\n self.assertEqual(dt.strftime('%d/%m/%Y'), '30/01/1900')\n dt = DateTime('2040/01/30')\n self.assertEqual(dt.strftime('%d/%m/%Y'), '30/01/2040')\n\n def testStrftimeUnicode(self):\n if IS_PYPY:\n return\n dt = DateTime('2002-05-02T08:00:00+00:00')\n uchar = b'\\xc3\\xa0'.decode('utf-8')\n ok = dt.strftime('Le %d/%m/%Y a %Hh%M').replace('a', uchar)\n ustr = b'Le %d/%m/%Y \\xc3\\xa0 %Hh%M'.decode('utf-8')\n self.assertEqual(dt.strftime(ustr), ok)\n", "method_code": " def strftime(self, format):\n \"\"\"Format the date/time using the *current timezone representation*.\"\"\"\n x = _calcDependentSecond2(self._year, self._month, self._day, self._hour, self._minute, self._second)\n ltz = self._calcTimezoneName(x, 0)\n tzdiff = _tzoffset(ltz, self._t) - _tzoffset(self._tz, self._t)\n zself = self + tzdiff / 86400.0\n microseconds = int((zself._second - zself._nearsec) * 1000000)\n unicode_format = False\n if isinstance(format, explicit_unicode_type):\n format = format.encode('utf-8')\n unicode_format = True\n ds = datetime(zself._year, zself._month, zself._day, zself._hour, zself._minute, int(zself._nearsec), microseconds).strftime(format)\n if unicode_format:\n return ds.decode('utf-8')\n return ds\n ", "context": "class DateTime(object):\n def strftime(self, format): ...\n def __init__(self, *args, **kw): ...\n def __getstate__(self): ...\n def __setstate__(self, value): ...\n def _parse_args(self, *args, **kw): ...\n def localZone(self, ltm=None): ...\n def _calcTimezoneName(self, x, ms): ...\n def _parse(self, st, datefmt=getDefaultDateFormat()): ...\n def _validDate(self, y, m, d): ...\n def _validTime(self, h, m, s): ...\n def __getattr__(self, name): ...\n def timeTime(self): ...\n def toZone(self, z): ...\n def isFuture(self): ...\n def isPast(self): ...\n def isCurrentYear(self): ...\n def isCurrentMonth(self): ...\n def isCurrentDay(self): ...\n def isCurrentHour(self): ...\n def isCurrentMinute(self): ...\n def earliestTime(self): ...\n def latestTime(self): ...\n def greaterThan(self, t): ...\n def greaterThanEqualTo(self, t): ...\n def equalTo(self, t): ...\n def notEqualTo(self, t): ...\n def __eq__(self, t): ...\n def __ne__(self, t): ...\n def lessThan(self, t): ...\n def lessThanEqualTo(self, t): ...\n def isLeapYear(self): ...\n def dayOfYear(self): ...\n def parts(self): ...\n def timezone(self): ...\n def tzoffset(self): ...\n def year(self): ...\n def month(self): ...\n def _fmon(self): ...\n def Month(self): ...\n def _amon(self): ...\n def aMonth(self): ...\n def Mon(self): ...\n def _pmon(self): ...\n def pMonth(self): ...\n def Mon_(self): ...\n def day(self): ...\n def _fday(self): ...\n def Day(self): ...\n def DayOfWeek(self): ...\n def _aday(self): ...\n def aDay(self): ...\n def _pday(self): ...\n def pDay(self): ...\n def Day_(self): ...\n def dow(self): ...\n def dow_1(self): ...\n def _pmhour(self): ...\n def h_12(self): ...\n def h_24(self): ...\n def _pm(self): ...\n def ampm(self): ...\n def hour(self): ...\n def minute(self): ...\n def second(self): ...\n def millis(self): ...\n def micros(self): ...\n def timezoneNaive(self): ...\n def Date(self): ...\n def Time(self): ...\n def TimeMinutes(self): ...\n def AMPM(self): ...\n def AMPMMinutes(self): ...\n def PreciseTime(self): ...\n def PreciseAMPM(self): ...\n def yy(self): ...\n def mm(self): ...\n def dd(self): ...\n def rfc822(self): ...\n def fCommon(self): ...\n def fCommonZ(self): ...\n def aCommon(self): ...\n def aCommonZ(self): ...\n def pCommon(self): ...\n def pCommonZ(self): ...\n def ISO(self): ...\n def ISO8601(self): ...\n def HTML4(self): ...\n def asdatetime(self): ...\n def utcdatetime(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __repr__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __int__(self): ...\n def __long__(self): ...\n def __float__(self): ...\n def _t(self): ...\n def _parse_iso8601(self, s): ...\n def _parse_iso8601_preserving_tznaive(self, s): ...\n def __parse_iso8601(self, s): ...\n def JulianDay(self): ...\n def week(self): ...\n def encode(self, out): ...\n\n __roles__ = None\n __allow_access_to_unprotected_subobjects__ = 1\n __slots__ = ('_timezone_naive', '_tz', '_dayoffset', '_year', '_month', '_day', '_hour', '_minute', '_second', '_nearsec', '_d', '_micros', 'time')\n __gt__ = greaterThan\n __ge__ = greaterThanEqualTo\n __lt__ = lessThan\n __le__ = lessThanEqualTo\n __radd__ = __add__\n", "repository": "designspired/TaskManagerGAE", "test_name": "testStrftimeTZhandling", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000072.py"} {"focal_file": "lib/DateTime/DateTime.py", "focal_class": "DateTime", "focal_method": "timezoneNaive", "tests": "import unittest\n\nclass Test_DateTime_timezoneNaive(unittest.TestCase):\n def testTimezoneNaiveHandling(self):\n dt = DateTime('2007-10-04T08:00:00+00:00')\n self.assertFalse(dt.timezoneNaive(), 'error with naivity handling in __parse_iso8601')\n dt = DateTime('2007-10-04T08:00:00Z')\n self.assertFalse(dt.timezoneNaive(), 'error with naivity handling in __parse_iso8601')\n dt = DateTime('2007-10-04T08:00:00')\n self.assertTrue(dt.timezoneNaive(), 'error with naivity handling in __parse_iso8601')\n dt = DateTime('2007/10/04 15:12:33.487618 GMT+1')\n self.assertFalse(dt.timezoneNaive(), 'error with naivity handling in _parse')\n dt = DateTime('2007/10/04 15:12:33.487618')\n self.assertTrue(dt.timezoneNaive(), 'error with naivity handling in _parse')\n dt = DateTime()\n self.assertFalse(dt.timezoneNaive(), 'error with naivity for current time')\n s = '2007-10-04T08:00:00'\n dt = DateTime(s)\n self.assertEqual(s, dt.ISO8601())\n s = '2007-10-04T08:00:00+00:00'\n dt = DateTime(s)\n self.assertEqual(s, dt.ISO8601())\n", "method_code": " def timezoneNaive(self):\n \"\"\"The python datetime module introduces the idea of distinguishing\n between timezone aware and timezone naive datetime values. For lossless\n conversion to and from datetime.datetime record if we record this\n information using True / False. DateTime makes no distinction, when we\n don't have any information we return None here.\n \"\"\"\n try:\n return self._timezone_naive\n except AttributeError:\n return None\n ", "context": "class DateTime(object):\n def timezoneNaive(self): ...\n def __init__(self, *args, **kw): ...\n def __getstate__(self): ...\n def __setstate__(self, value): ...\n def _parse_args(self, *args, **kw): ...\n def localZone(self, ltm=None): ...\n def _calcTimezoneName(self, x, ms): ...\n def _parse(self, st, datefmt=getDefaultDateFormat()): ...\n def _validDate(self, y, m, d): ...\n def _validTime(self, h, m, s): ...\n def __getattr__(self, name): ...\n def timeTime(self): ...\n def toZone(self, z): ...\n def isFuture(self): ...\n def isPast(self): ...\n def isCurrentYear(self): ...\n def isCurrentMonth(self): ...\n def isCurrentDay(self): ...\n def isCurrentHour(self): ...\n def isCurrentMinute(self): ...\n def earliestTime(self): ...\n def latestTime(self): ...\n def greaterThan(self, t): ...\n def greaterThanEqualTo(self, t): ...\n def equalTo(self, t): ...\n def notEqualTo(self, t): ...\n def __eq__(self, t): ...\n def __ne__(self, t): ...\n def lessThan(self, t): ...\n def lessThanEqualTo(self, t): ...\n def isLeapYear(self): ...\n def dayOfYear(self): ...\n def parts(self): ...\n def timezone(self): ...\n def tzoffset(self): ...\n def year(self): ...\n def month(self): ...\n def _fmon(self): ...\n def Month(self): ...\n def _amon(self): ...\n def aMonth(self): ...\n def Mon(self): ...\n def _pmon(self): ...\n def pMonth(self): ...\n def Mon_(self): ...\n def day(self): ...\n def _fday(self): ...\n def Day(self): ...\n def DayOfWeek(self): ...\n def _aday(self): ...\n def aDay(self): ...\n def _pday(self): ...\n def pDay(self): ...\n def Day_(self): ...\n def dow(self): ...\n def dow_1(self): ...\n def _pmhour(self): ...\n def h_12(self): ...\n def h_24(self): ...\n def _pm(self): ...\n def ampm(self): ...\n def hour(self): ...\n def minute(self): ...\n def second(self): ...\n def millis(self): ...\n def micros(self): ...\n def strftime(self, format): ...\n def Date(self): ...\n def Time(self): ...\n def TimeMinutes(self): ...\n def AMPM(self): ...\n def AMPMMinutes(self): ...\n def PreciseTime(self): ...\n def PreciseAMPM(self): ...\n def yy(self): ...\n def mm(self): ...\n def dd(self): ...\n def rfc822(self): ...\n def fCommon(self): ...\n def fCommonZ(self): ...\n def aCommon(self): ...\n def aCommonZ(self): ...\n def pCommon(self): ...\n def pCommonZ(self): ...\n def ISO(self): ...\n def ISO8601(self): ...\n def HTML4(self): ...\n def asdatetime(self): ...\n def utcdatetime(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __repr__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __int__(self): ...\n def __long__(self): ...\n def __float__(self): ...\n def _t(self): ...\n def _parse_iso8601(self, s): ...\n def _parse_iso8601_preserving_tznaive(self, s): ...\n def __parse_iso8601(self, s): ...\n def JulianDay(self): ...\n def week(self): ...\n def encode(self, out): ...\n\n __roles__ = None\n __allow_access_to_unprotected_subobjects__ = 1\n __slots__ = ('_timezone_naive', '_tz', '_dayoffset', '_year', '_month', '_day', '_hour', '_minute', '_second', '_nearsec', '_d', '_micros', 'time')\n __gt__ = greaterThan\n __ge__ = greaterThanEqualTo\n __lt__ = lessThan\n __le__ = lessThanEqualTo\n __radd__ = __add__\n", "repository": "designspired/TaskManagerGAE", "test_name": "testTimezoneNaiveHandling", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000073.py"} {"focal_file": "lib/DateTime/DateTime.py", "focal_class": "DateTime", "focal_method": "timezone", "tests": "import unittest\n\nclass Test_DateTime_timezone(unittest.TestCase):\n def testEDTTimezone(self):\n dt = DateTime('Mon, 28 Jun 2010 10:12:25 EDT')\n self.assertEqual(dt.Day(), 'Monday')\n self.assertEqual(dt.day(), 28)\n self.assertEqual(dt.Month(), 'June')\n self.assertEqual(dt.timezone(), 'GMT-4')\n", "method_code": " def timezone(self):\n \"\"\"Return the timezone in which the object is represented.\"\"\"\n return self._tz\n ", "context": "class DateTime(object):\n def timezone(self): ...\n def __init__(self, *args, **kw): ...\n def __getstate__(self): ...\n def __setstate__(self, value): ...\n def _parse_args(self, *args, **kw): ...\n def localZone(self, ltm=None): ...\n def _calcTimezoneName(self, x, ms): ...\n def _parse(self, st, datefmt=getDefaultDateFormat()): ...\n def _validDate(self, y, m, d): ...\n def _validTime(self, h, m, s): ...\n def __getattr__(self, name): ...\n def timeTime(self): ...\n def toZone(self, z): ...\n def isFuture(self): ...\n def isPast(self): ...\n def isCurrentYear(self): ...\n def isCurrentMonth(self): ...\n def isCurrentDay(self): ...\n def isCurrentHour(self): ...\n def isCurrentMinute(self): ...\n def earliestTime(self): ...\n def latestTime(self): ...\n def greaterThan(self, t): ...\n def greaterThanEqualTo(self, t): ...\n def equalTo(self, t): ...\n def notEqualTo(self, t): ...\n def __eq__(self, t): ...\n def __ne__(self, t): ...\n def lessThan(self, t): ...\n def lessThanEqualTo(self, t): ...\n def isLeapYear(self): ...\n def dayOfYear(self): ...\n def parts(self): ...\n def tzoffset(self): ...\n def year(self): ...\n def month(self): ...\n def _fmon(self): ...\n def Month(self): ...\n def _amon(self): ...\n def aMonth(self): ...\n def Mon(self): ...\n def _pmon(self): ...\n def pMonth(self): ...\n def Mon_(self): ...\n def day(self): ...\n def _fday(self): ...\n def Day(self): ...\n def DayOfWeek(self): ...\n def _aday(self): ...\n def aDay(self): ...\n def _pday(self): ...\n def pDay(self): ...\n def Day_(self): ...\n def dow(self): ...\n def dow_1(self): ...\n def _pmhour(self): ...\n def h_12(self): ...\n def h_24(self): ...\n def _pm(self): ...\n def ampm(self): ...\n def hour(self): ...\n def minute(self): ...\n def second(self): ...\n def millis(self): ...\n def micros(self): ...\n def timezoneNaive(self): ...\n def strftime(self, format): ...\n def Date(self): ...\n def Time(self): ...\n def TimeMinutes(self): ...\n def AMPM(self): ...\n def AMPMMinutes(self): ...\n def PreciseTime(self): ...\n def PreciseAMPM(self): ...\n def yy(self): ...\n def mm(self): ...\n def dd(self): ...\n def rfc822(self): ...\n def fCommon(self): ...\n def fCommonZ(self): ...\n def aCommon(self): ...\n def aCommonZ(self): ...\n def pCommon(self): ...\n def pCommonZ(self): ...\n def ISO(self): ...\n def ISO8601(self): ...\n def HTML4(self): ...\n def asdatetime(self): ...\n def utcdatetime(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __repr__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __int__(self): ...\n def __long__(self): ...\n def __float__(self): ...\n def _t(self): ...\n def _parse_iso8601(self, s): ...\n def _parse_iso8601_preserving_tznaive(self, s): ...\n def __parse_iso8601(self, s): ...\n def JulianDay(self): ...\n def week(self): ...\n def encode(self, out): ...\n\n __roles__ = None\n __allow_access_to_unprotected_subobjects__ = 1\n __slots__ = ('_timezone_naive', '_tz', '_dayoffset', '_year', '_month', '_day', '_hour', '_minute', '_second', '_nearsec', '_d', '_micros', 'time')\n __gt__ = greaterThan\n __ge__ = greaterThanEqualTo\n __lt__ = lessThan\n __le__ = lessThanEqualTo\n __radd__ = __add__\n", "repository": "designspired/TaskManagerGAE", "test_name": "testEDTTimezone", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000074.py"} {"focal_file": "lib/oauth2client/_helpers.py", "focal_class": null, "focal_method": "_add_query_parameter", "tests": "import unittest\n\nclass Test_add_query_parameter(unittest.TestCase):\n def test__add_query_parameter(self):\n self.assertEqual(_helpers._add_query_parameter('/action', 'a', None), '/action')\n self.assertEqual(_helpers._add_query_parameter('/action', 'a', 'b'), '/action?a=b')\n self.assertEqual(_helpers._add_query_parameter('/action?a=b', 'a', 'c'), '/action?a=c')\n self.assertIn(_helpers._add_query_parameter('/action?a=b', 'c', 'd'), ['/action?a=b&c=d', '/action?c=d&a=b'])\n self.assertEqual(_helpers._add_query_parameter('/action', 'a', ' ='), '/action?a=+%3D')\n", "method_code": "def _add_query_parameter(url, name, value):\n \"\"\"Adds a query parameter to a url.\n\n Replaces the current value if it already exists in the URL.\n\n Args:\n url: string, url to add the query parameter to.\n name: string, query parameter name.\n value: string, query parameter value.\n\n Returns:\n Updated query parameter. Does not update the url if value is None.\n \"\"\"\n if value is None:\n return url\n else:\n return update_query_params(url, {name: value})", "context": "def _add_query_parameter(url, name, value): ...\ndef positional(max_positional_args): ...\ndef scopes_to_string(scopes): ...\ndef string_to_scopes(scopes): ...\ndef parse_unique_urlencoded(content): ...\ndef update_query_params(uri, params): ...\ndef _add_query_parameter(url, name, value): ...\ndef validate_file(filename): ...\ndef _parse_pem_key(raw_key_input): ...\ndef _json_encode(data): ...\ndef _to_bytes(value, encoding='ascii'): ...\ndef _from_bytes(value): ...\ndef _urlsafe_b64encode(raw_bytes): ...\ndef _urlsafe_b64decode(b64string): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__add_query_parameter", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000075.py"} {"focal_file": "lib/oauth2client/_helpers.py", "focal_class": null, "focal_method": "update_query_params", "tests": "import unittest\n\nclass Test_update_query_params(unittest.TestCase):\n def test_update_query_params_no_params(self):\n uri = 'http://www.google.com'\n updated = _helpers.update_query_params(uri, {'a': 'b'})\n self.assertEqual(updated, uri + '?a=b')\n\n def test_update_query_params_existing_params(self):\n uri = 'http://www.google.com?x=y'\n updated = _helpers.update_query_params(uri, {'a': 'b', 'c': 'd&'})\n hardcoded_update = uri + '&a=b&c=d%26'\n test_client.assertUrisEqual(self, updated, hardcoded_update)\n\n def test_update_query_params_replace_param(self):\n base_uri = 'http://www.google.com'\n uri = base_uri + '?x=a'\n updated = _helpers.update_query_params(uri, {'x': 'b', 'y': 'c'})\n hardcoded_update = base_uri + '?x=b&y=c'\n test_client.assertUrisEqual(self, updated, hardcoded_update)\n\n def test_update_query_params_repeated_params(self):\n uri = 'http://www.google.com?x=a&x=b'\n with self.assertRaises(ValueError):\n _helpers.update_query_params(uri, {'a': 'c'})\n", "method_code": "def update_query_params(uri, params):\n \"\"\"Updates a URI with new query parameters.\n\n If a given key from ``params`` is repeated in the ``uri``, then\n the URI will be considered invalid and an error will occur.\n\n If the URI is valid, then each value from ``params`` will\n replace the corresponding value in the query parameters (if\n it exists).\n\n Args:\n uri: string, A valid URI, with potential existing query parameters.\n params: dict, A dictionary of query parameters.\n\n Returns:\n The same URI but with the new query parameters added.\n \"\"\"\n parts = urllib.parse.urlparse(uri)\n query_params = parse_unique_urlencoded(parts.query)\n query_params.update(params)\n new_query = urllib.parse.urlencode(query_params)\n new_parts = parts._replace(query=new_query)\n return urllib.parse.urlunparse(new_parts)", "context": "def update_query_params(uri, params): ...\ndef positional(max_positional_args): ...\ndef scopes_to_string(scopes): ...\ndef string_to_scopes(scopes): ...\ndef parse_unique_urlencoded(content): ...\ndef update_query_params(uri, params): ...\ndef _add_query_parameter(url, name, value): ...\ndef validate_file(filename): ...\ndef _parse_pem_key(raw_key_input): ...\ndef _json_encode(data): ...\ndef _to_bytes(value, encoding='ascii'): ...\ndef _from_bytes(value): ...\ndef _urlsafe_b64encode(raw_bytes): ...\ndef _urlsafe_b64decode(b64string): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_update_query_params_no_params", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000076.py"} {"focal_file": "lib/oauth2client/_pkce.py", "focal_class": null, "focal_method": "code_verifier", "tests": "import unittest\n\nclass Test_code_verifier(unittest.TestCase):\n @mock.patch('oauth2client._pkce.os.urandom')\n def test_verifier(self, fake_urandom):\n canned_randomness = b'\\x98\\x10D7\\xf3\\xb7\\xaa\\xfc\\xdd\\xd3M\\xe2\\xa3,\\x06\\xa0\\xb0\\xa9\\xb4\\x8f\\xcb\\xd0\\xf5\\x86N2p\\x8c]!W\\x9a\\xed54\\x99\\x9d\\x8dv\\\\\\xa7/\\x81\\xf3J\\x98\\xc3\\x90\\xee\\xb0\\x8c\\xb7Zc#\\x05M0O\\x08\\xda\\t\\x1f\\x07'\n fake_urandom.return_value = canned_randomness\n expected = b'mBBEN_O3qvzd003ioywGoLCptI_L0PWGTjJwjF0hV5rtNTSZnY12XKcvgfNKmMOQ7rCMt1pjIwVNME8I2gkfBw=='\n result = _pkce.code_verifier()\n self.assertEqual(result, expected)\n", "method_code": "def code_verifier(n_bytes=64):\n \"\"\"\n Generates a 'code_verifier' as described in section 4.1 of RFC 7636.\n\n This is a 'high-entropy cryptographic random string' that will be\n impractical for an attacker to guess.\n\n Args:\n n_bytes: integer between 31 and 96, inclusive. default: 64\n number of bytes of entropy to include in verifier.\n\n Returns:\n Bytestring, representing urlsafe base64-encoded random data.\n \"\"\"\n verifier = base64.urlsafe_b64encode(os.urandom(n_bytes))\n if len(verifier) < 43:\n raise ValueError('Verifier too short. n_bytes must be > 30.')\n elif len(verifier) > 128:\n raise ValueError('Verifier too long. n_bytes must be < 97.')\n else:\n return verifier", "context": "def code_verifier(n_bytes=64): ...\ndef code_verifier(n_bytes=64): ...\ndef code_challenge(verifier): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000077.py"} {"focal_file": "lib/oauth2client/_pkce.py", "focal_class": null, "focal_method": "code_challenge", "tests": "import unittest\n\nclass Test_code_challenge(unittest.TestCase):\n def test_challenge(self):\n result = _pkce.code_challenge(b'SOME_VERIFIER')\n expected = b'6xJCQsjTtS3zjUwd8_ZqH0SyviGHnp5PsHXWKOCqDuI='\n self.assertEqual(result, expected)\n", "method_code": "def code_challenge(verifier):\n \"\"\"\n Creates a 'code_challenge' as described in section 4.2 of RFC 7636\n by taking the sha256 hash of the verifier and then urlsafe\n base64-encoding it.\n\n Args:\n verifier: bytestring, representing a code_verifier as generated by\n code_verifier().\n\n Returns:\n Bytestring, representing a urlsafe base64-encoded sha256 hash digest.\n \"\"\"\n return base64.urlsafe_b64encode(hashlib.sha256(verifier).digest())", "context": "def code_challenge(verifier): ...\ndef code_verifier(n_bytes=64): ...\ndef code_challenge(verifier): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_challenge", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000078.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.Credentials", "focal_method": "_to_json", "tests": "import unittest\n\nclass Test_oauth2client_client_Credentials_to_json(unittest.TestCase):\n def test__to_json_basic(self):\n credentials = client.Credentials()\n json_payload = credentials._to_json([])\n self.assertIsInstance(json_payload, str)\n payload = json.loads(json_payload)\n expected_payload = {'_class': client.Credentials.__name__, '_module': client.Credentials.__module__, 'token_expiry': None}\n self.assertEqual(payload, expected_payload)\n", "method_code": " def _to_json(self, strip, to_serialize=None):\n \"\"\"Utility function that creates JSON repr. of a Credentials object.\n \n Args:\n strip: array, An array of names of members to exclude from the\n JSON.\n to_serialize: dict, (Optional) The properties for this object\n that will be serialized. This allows callers to\n modify before serializing.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n curr_type = self.__class__\n if to_serialize is None:\n to_serialize = copy.copy(self.__dict__)\n else:\n to_serialize = copy.copy(to_serialize)\n for member in strip:\n if member in to_serialize:\n del to_serialize[member]\n to_serialize['token_expiry'] = _parse_expiry(to_serialize.get('token_expiry'))\n to_serialize['_class'] = curr_type.__name__\n to_serialize['_module'] = curr_type.__module__\n for key, val in to_serialize.items():\n if isinstance(val, bytes):\n to_serialize[key] = val.decode('utf-8')\n if isinstance(val, set):\n to_serialize[key] = list(val)\n return json.dumps(to_serialize)\n ", "context": "class Credentials(object):\n def _to_json(self, strip, to_serialize=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def to_json(self): ...\n def new_from_json(cls, json_data): ...\n def from_json(cls, unused_data): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['store'])\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__to_json_basic", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000079.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.Credentials", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_oauth2client_client_Credentials_to_json(unittest.TestCase):\n @mock.patch.object(client.Credentials, '_to_json', return_value=object())\n def test_to_json(self, to_json):\n credentials = client.Credentials()\n self.assertEqual(credentials.to_json(), to_json.return_value)\n to_json.assert_called_once_with(client.Credentials.NON_SERIALIZED_MEMBERS)\n", "method_code": " def to_json(self):\n \"\"\"Creating a JSON representation of an instance of Credentials.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n return self._to_json(self.NON_SERIALIZED_MEMBERS)\n ", "context": "class Credentials(object):\n def to_json(self): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip, to_serialize=None): ...\n def new_from_json(cls, json_data): ...\n def from_json(cls, unused_data): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['store'])\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000080.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n unused_data = {}\n credentials = client.Credentials.from_json(unused_data)\n self.assertIsInstance(credentials, client.Credentials)\n self.assertEqual(credentials.__dict__, {})\n\n def test_to_from_json(self):\n json = self.credentials.to_json()\n instance = client.OAuth2Credentials.from_json(json)\n self.assertEqual(client.OAuth2Credentials, type(instance))\n instance.token_expiry = None\n self.credentials.token_expiry = None\n self.assertEqual(instance.__dict__, self.credentials.__dict__)\n", "method_code": " def from_json(cls, unused_data):\n \"\"\"Instantiate a Credentials object from a JSON description of it.\n \n The JSON should have been produced by calling .to_json() on the object.\n \n Args:\n unused_data: dict, A deserialized JSON object.\n \n Returns:\n An instance of a Credentials subclass.\n \"\"\"\n return Credentials()\n ", "context": "class Credentials(object):\n @classmethod\n def from_json(cls, unused_data): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip, to_serialize=None): ...\n def to_json(self): ...\n def new_from_json(cls, json_data): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['store'])\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_from_json", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000081.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.Storage", "focal_method": "locked_get", "tests": "import unittest\n\nclass Test_oauth2client_client_Storage_locked_get(unittest.TestCase):\n def test_locked_get_abstract(self):\n storage = client.Storage()\n with self.assertRaises(NotImplementedError):\n storage.locked_get()\n", "method_code": " def locked_get(self):\n \"\"\"Retrieve credential.\n \n The Storage lock must be held when this is called.\n \n Returns:\n oauth2client.client.Credentials\n \"\"\"\n raise NotImplementedError\n ", "context": "class Storage(object):\n def locked_get(self): ...\n def __init__(self, lock=None): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def locked_put(self, credentials): ...\n def locked_delete(self): ...\n def get(self): ...\n def put(self, credentials): ...\n def delete(self): ...\n\n self._lock = lock\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_locked_get_abstract", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000082.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.Storage", "focal_method": "locked_put", "tests": "import unittest\n\nclass Test_oauth2client_client_Storage_locked_put(unittest.TestCase):\n def test_locked_put_abstract(self):\n storage = client.Storage()\n credentials = object()\n with self.assertRaises(NotImplementedError):\n storage.locked_put(credentials)\n", "method_code": " def locked_put(self, credentials):\n \"\"\"Write a credential.\n \n The Storage lock must be held when this is called.\n \n Args:\n credentials: Credentials, the credentials to store.\n \"\"\"\n raise NotImplementedError\n ", "context": "class Storage(object):\n def locked_put(self, credentials): ...\n def __init__(self, lock=None): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def locked_get(self): ...\n def locked_delete(self): ...\n def get(self): ...\n def put(self, credentials): ...\n def delete(self): ...\n\n self._lock = lock\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_locked_put_abstract", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000083.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.Storage", "focal_method": "locked_delete", "tests": "import unittest\n\nclass Test_oauth2client_client_Storage_locked_delete(unittest.TestCase):\n def test_locked_delete_abstract(self):\n storage = client.Storage()\n with self.assertRaises(NotImplementedError):\n storage.locked_delete()\n", "method_code": " def locked_delete(self):\n \"\"\"Delete a credential.\n \n The Storage lock must be held when this is called.\n \"\"\"\n raise NotImplementedError\n ", "context": "class Storage(object):\n def locked_delete(self): ...\n def __init__(self, lock=None): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def locked_get(self): ...\n def locked_put(self, credentials): ...\n def get(self): ...\n def put(self, credentials): ...\n def delete(self): ...\n\n self._lock = lock\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_locked_delete_abstract", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000084.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required(self):\n self.assertFalse(self.get_a_google_credentials_object().create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n \"\"\"Whether this Credentials object is scopeless.\n \n create_scoped(scopes) method needs to be called in order to create\n a Credentials object for API calls.\n \"\"\"\n return False\n ", "context": "class GoogleCredentials(OAuth2Credentials):\n def create_scoped_required(self): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def create_scoped(self, scopes): ...\n def from_json(cls, json_data): ...\n def serialization_data(self): ...\n def _implicit_credentials_from_gae(): ...\n def _implicit_credentials_from_gce(): ...\n def _implicit_credentials_from_files(): ...\n def _get_implicit_credentials(cls): ...\n def get_application_default(): ...\n def from_stream(credential_filename): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['_private_key']) | OAuth2Credentials.NON_SERIALIZED_MEMBERS\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_scoped_required", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000085.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "create_scoped", "tests": "import unittest\n\nclass Test_create_scoped(unittest.TestCase):\n def test_create_scoped(self):\n credentials = self.get_a_google_credentials_object()\n self.assertEqual(credentials, credentials.create_scoped(None))\n self.assertEqual(credentials, credentials.create_scoped(['dummy_scope']))\n", "method_code": " def create_scoped(self, scopes):\n \"\"\"Create a Credentials object for the given scopes.\n \n The Credentials type is preserved.\n \"\"\"\n return self\n ", "context": "class GoogleCredentials(OAuth2Credentials):\n def create_scoped(self, scopes): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def create_scoped_required(self): ...\n def from_json(cls, json_data): ...\n def serialization_data(self): ...\n def _implicit_credentials_from_gae(): ...\n def _implicit_credentials_from_gce(): ...\n def _implicit_credentials_from_files(): ...\n def _get_implicit_credentials(cls): ...\n def get_application_default(): ...\n def from_stream(credential_filename): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['_private_key']) | OAuth2Credentials.NON_SERIALIZED_MEMBERS\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_scoped", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000086.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "get_application_default", "tests": "import unittest\n\nclass Test_get_application_default(unittest.TestCase):\n @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_files', return_value=None)\n @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_gce')\n @mock.patch.object(client, '_in_gae_environment', return_value=True)\n @mock.patch.object(client, '_get_application_default_credential_GAE', return_value=object())\n def test_get_application_default_in_gae(self, gae_adc, in_gae, from_gce, from_files):\n credentials = client.GoogleCredentials.get_application_default()\n self.assertEqual(credentials, gae_adc.return_value)\n from_files.assert_called_once_with()\n in_gae.assert_called_once_with()\n from_gce.assert_not_called()\n\n @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_gae', return_value=None)\n @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_files', return_value=None)\n @mock.patch.object(client, '_in_gce_environment', return_value=True)\n @mock.patch.object(client, '_get_application_default_credential_GCE', return_value=object())\n def test_get_application_default_in_gce(self, gce_adc, in_gce, from_files, from_gae):\n credentials = client.GoogleCredentials.get_application_default()\n self.assertEqual(credentials, gce_adc.return_value)\n in_gce.assert_called_once_with()\n from_gae.assert_called_once_with()\n from_files.assert_called_once_with()\n", "method_code": " def get_application_default():\n \"\"\"Get the Application Default Credentials for the current environment.\n \n Raises:\n ApplicationDefaultCredentialsError: raised when the credentials\n fail to be retrieved.\n \"\"\"\n return GoogleCredentials._get_implicit_credentials()\n ", "context": "class GoogleCredentials(OAuth2Credentials):\n @staticmethod\n def get_application_default(): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def from_json(cls, json_data): ...\n def serialization_data(self): ...\n def _implicit_credentials_from_gae(): ...\n def _implicit_credentials_from_gce(): ...\n def _implicit_credentials_from_files(): ...\n def _get_implicit_credentials(cls): ...\n def from_stream(credential_filename): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['_private_key']) | OAuth2Credentials.NON_SERIALIZED_MEMBERS\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000087.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "_get_environment_variable_file", "tests": "import unittest\n\nclass Test_get_environment_variable_file(unittest.TestCase):\n def test_get_environment_variable_file(self):\n environment_variable_file = datafile(os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))\n os.environ[client.GOOGLE_APPLICATION_CREDENTIALS] = environment_variable_file\n self.assertEqual(environment_variable_file, client._get_environment_variable_file())\n\n def test_get_environment_variable_file_error(self):\n nonexistent_file = datafile('nonexistent')\n os.environ[client.GOOGLE_APPLICATION_CREDENTIALS] = nonexistent_file\n expected_err_msg = 'File {0} \\\\(pointed by {1} environment variable\\\\) does not exist!'.format(nonexistent_file, client.GOOGLE_APPLICATION_CREDENTIALS)\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._get_environment_variable_file()\n\n @mock.patch.dict(os.environ, {}, clear=True)\n def test_get_environment_variable_file_without_env_var(self):\n self.assertIsNone(client._get_environment_variable_file())\n", "method_code": "def _get_environment_variable_file():\n application_default_credential_filename = os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, None)\n if application_default_credential_filename:\n if os.path.isfile(application_default_credential_filename):\n return application_default_credential_filename\n else:\n raise ApplicationDefaultCredentialsError('File ' + application_default_credential_filename + ' (pointed by ' + GOOGLE_APPLICATION_CREDENTIALS + ' environment variable) does not exist!')", "context": "def _get_environment_variable_file(): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_get_environment_variable_file", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000088.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "_get_well_known_file", "tests": "import unittest\n\nclass Test_get_well_known_file(unittest.TestCase):\n @mock.patch('os.name', new='nt')\n @mock.patch.dict(os.environ, {'APPDATA': DATA_DIR}, clear=True)\n def test_get_well_known_file_on_windows(self):\n well_known_file = datafile(os.path.join(client._CLOUDSDK_CONFIG_DIRECTORY, client._WELL_KNOWN_CREDENTIALS_FILE))\n self.assertEqual(well_known_file, client._get_well_known_file())\n\n @mock.patch('os.name', new='nt')\n @mock.patch.dict(os.environ, {'SystemDrive': 'G:'}, clear=True)\n def test_get_well_known_file_on_windows_without_appdata(self):\n well_known_file = os.path.join('G:', '\\\\', client._CLOUDSDK_CONFIG_DIRECTORY, client._WELL_KNOWN_CREDENTIALS_FILE)\n self.assertEqual(well_known_file, client._get_well_known_file())\n\n @mock.patch.dict(os.environ, {client._CLOUDSDK_CONFIG_ENV_VAR: 'CUSTOM_DIR'}, clear=True)\n def test_get_well_known_file_with_custom_config_dir(self):\n CUSTOM_DIR = os.environ[client._CLOUDSDK_CONFIG_ENV_VAR]\n EXPECTED_FILE = os.path.join(CUSTOM_DIR, client._WELL_KNOWN_CREDENTIALS_FILE)\n well_known_file = client._get_well_known_file()\n self.assertEqual(well_known_file, EXPECTED_FILE)\n", "method_code": "def _get_well_known_file():\n \"\"\"Get the well known file produced by command 'gcloud auth login'.\"\"\"\n default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR)\n if default_config_dir is None:\n if os.name == 'nt':\n try:\n default_config_dir = os.path.join(os.environ['APPDATA'], _CLOUDSDK_CONFIG_DIRECTORY)\n except KeyError:\n drive = os.environ.get('SystemDrive', 'C:')\n default_config_dir = os.path.join(drive, '\\\\', _CLOUDSDK_CONFIG_DIRECTORY)\n else:\n default_config_dir = os.path.join(os.path.expanduser('~'), '.config', _CLOUDSDK_CONFIG_DIRECTORY)\n return os.path.join(default_config_dir, _WELL_KNOWN_CREDENTIALS_FILE)", "context": "def _get_well_known_file(): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000089.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "save_to_well_known_file", "tests": "import unittest\n\nclass Test_save_to_well_known_file(unittest.TestCase):\n def test_save_to_well_known_file_service_account(self):\n credential_file = datafile(os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))\n credentials = client._get_application_default_credential_from_file(credential_file)\n temp_credential_file = datafile(os.path.join('gcloud', 'temp_well_known_file_service_account.json'))\n client.save_to_well_known_file(credentials, temp_credential_file)\n with open(temp_credential_file) as f:\n d = json.load(f)\n self.assertEqual('service_account', d['type'])\n self.assertEqual('123', d['client_id'])\n self.assertEqual('dummy@google.com', d['client_email'])\n self.assertEqual('ABCDEF', d['private_key_id'])\n os.remove(temp_credential_file)\n\n def test_save_to_well_known_file_authorized_user(self):\n credentials_file = datafile(os.path.join('gcloud', 'application_default_credentials_authorized_user.json'))\n credentials = client._get_application_default_credential_from_file(credentials_file)\n temp_credential_file = datafile(os.path.join('gcloud', 'temp_well_known_file_authorized_user.json'))\n client.save_to_well_known_file(credentials, temp_credential_file)\n with open(temp_credential_file) as f:\n d = json.load(f)\n self.assertEqual('authorized_user', d['type'])\n self.assertEqual('123', d['client_id'])\n self.assertEqual('secret', d['client_secret'])\n self.assertEqual('alabalaportocala', d['refresh_token'])\n os.remove(temp_credential_file)\n", "method_code": "def save_to_well_known_file(credentials, well_known_file=None):\n \"\"\"Save the provided GoogleCredentials to the well known file.\n\n Args:\n credentials: the credentials to be saved to the well known file;\n it should be an instance of GoogleCredentials\n well_known_file: the name of the file where the credentials are to be\n saved; this parameter is supposed to be used for\n testing only\n \"\"\"\n if well_known_file is None:\n well_known_file = _get_well_known_file()\n config_dir = os.path.dirname(well_known_file)\n if not os.path.isdir(config_dir):\n raise OSError('Config directory does not exist: {0}'.format(config_dir))\n credentials_data = credentials.serialization_data\n _save_private_file(well_known_file, credentials_data)", "context": "def save_to_well_known_file(credentials, well_known_file=None): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_save_to_well_known_file_service_account", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000090.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "_get_application_default_credential_from_file", "tests": "import unittest\n\nclass Test_get_application_default_credential_from_file(unittest.TestCase):\n def test_get_application_default_credential_from_malformed_file_1(self):\n credentials_file = datafile(os.path.join('gcloud', 'application_default_credentials_malformed_1.json'))\n expected_err_msg = \"'type' field should be defined \\\\(and have one of the '{0}' or '{1}' values\\\\)\".format(client.AUTHORIZED_USER, client.SERVICE_ACCOUNT)\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._get_application_default_credential_from_file(credentials_file)\n\n def test_get_application_default_credential_from_malformed_file_2(self):\n credentials_file = datafile(os.path.join('gcloud', 'application_default_credentials_malformed_2.json'))\n expected_err_msg = 'The following field\\\\(s\\\\) must be defined: private_key_id'\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._get_application_default_credential_from_file(credentials_file)\n\n def test_get_application_default_credential_from_malformed_file_3(self):\n credentials_file = datafile(os.path.join('gcloud', 'application_default_credentials_malformed_3.json'))\n with self.assertRaises(ValueError):\n client._get_application_default_credential_from_file(credentials_file)\n", "method_code": "def _get_application_default_credential_from_file(filename):\n \"\"\"Build the Application Default Credentials from file.\"\"\"\n with open(filename) as file_obj:\n client_credentials = json.load(file_obj)\n credentials_type = client_credentials.get('type')\n if credentials_type == AUTHORIZED_USER:\n required_fields = set(['client_id', 'client_secret', 'refresh_token'])\n elif credentials_type == SERVICE_ACCOUNT:\n required_fields = set(['client_id', 'client_email', 'private_key_id', 'private_key'])\n else:\n raise ApplicationDefaultCredentialsError(\"'type' field should be defined (and have one of the '\" + AUTHORIZED_USER + \"' or '\" + SERVICE_ACCOUNT + \"' values)\")\n missing_fields = required_fields.difference(client_credentials.keys())\n if missing_fields:\n _raise_exception_for_missing_fields(missing_fields)\n if client_credentials['type'] == AUTHORIZED_USER:\n return GoogleCredentials(access_token=None, client_id=client_credentials['client_id'], client_secret=client_credentials['client_secret'], refresh_token=client_credentials['refresh_token'], token_expiry=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, user_agent='Python client library')\n else:\n from oauth2client import service_account\n return service_account._JWTAccessCredentials.from_json_keyfile_dict(client_credentials)", "context": "def _get_application_default_credential_from_file(filename): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_get_application_default_credential_from_malformed_file_1", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000091.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "_raise_exception_for_missing_fields", "tests": "import unittest\n\nclass Test_raise_exception_for_missing_fields(unittest.TestCase):\n def test_raise_exception_for_missing_fields(self):\n missing_fields = ['first', 'second', 'third']\n expected_err_msg = 'The following field\\\\(s\\\\) must be defined: ' + ', '.join(missing_fields)\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._raise_exception_for_missing_fields(missing_fields)\n", "method_code": "def _raise_exception_for_missing_fields(missing_fields):\n raise ApplicationDefaultCredentialsError('The following field(s) must be defined: ' + ', '.join(missing_fields))", "context": "def _raise_exception_for_missing_fields(missing_fields): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_raise_exception_for_missing_fields", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000092.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.ApplicationDefaultCredentialsError", "focal_method": "_raise_exception_for_reading_json", "tests": "import unittest\n\nclass Test_oauth2client_client_ApplicationDefaultCredentialsError_raise_exception_for_reading_json(unittest.TestCase):\n def test_raise_exception_for_reading_json(self):\n credential_file = 'any_file'\n extra_help = ' be good'\n error = client.ApplicationDefaultCredentialsError('stuff happens')\n expected_err_msg = 'An error was encountered while reading json file: ' + credential_file + extra_help + ': ' + str(error)\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._raise_exception_for_reading_json(credential_file, extra_help, error)\n", "method_code": "def _raise_exception_for_reading_json(credential_file, extra_help, error):\n raise ApplicationDefaultCredentialsError('An error was encountered while reading json file: ' + credential_file + extra_help + ': ' + str(error))", "context": "def _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_raise_exception_for_reading_json", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000093.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "_parse_expiry", "tests": "import unittest\n\nclass Test_parse_expiry(unittest.TestCase):\n def test_parse_expiry(self):\n dt = datetime.datetime(2016, 1, 1)\n parsed_expiry = client._parse_expiry(dt)\n self.assertEqual('2016-01-01T00:00:00Z', parsed_expiry)\n", "method_code": "def _parse_expiry(expiry):\n if expiry and isinstance(expiry, datetime.datetime):\n return expiry.strftime(EXPIRY_FORMAT)\n else:\n return None", "context": "def _parse_expiry(expiry): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_parse_expiry", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000094.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "authorize", "tests": "import unittest\n\nclass Test_authorize(unittest.TestCase):\n def test_recursive_authorize(self):\n token_response = {'access_token': '1/3w', 'expires_in': 3600}\n encoded_response = json.dumps(token_response).encode('utf-8')\n http = http_mock.HttpMock(data=encoded_response)\n http = self.credentials.authorize(http)\n http = self.credentials.authorize(http)\n transport.request(http, 'http://example.com')\n", "method_code": " def authorize(self, http):\n \"\"\"Take an httplib2.Http instance (or equivalent) and authorizes it.\n \n Authorizes it for the set of credentials, usually by replacing\n http.request() with a method that adds in the appropriate headers and\n then delegates to the original Http.request() method.\n \n Args:\n http: httplib2.Http, an http object to be used to make the refresh\n request.\n \"\"\"\n raise NotImplementedError\n ", "context": "class Credentials(object):\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip, to_serialize=None): ...\n def to_json(self): ...\n def new_from_json(cls, json_data): ...\n def from_json(cls, unused_data): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['store'])\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_recursive_authorize", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000095.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2Credentials", "focal_method": "_expires_in", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2Credentials_expires_in(unittest.TestCase):\n def test__expires_in_no_expiry(self):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n self.assertIsNone(credentials.token_expiry)\n self.assertIsNone(credentials._expires_in())\n\n @mock.patch('oauth2client.client._UTCNOW')\n def test__expires_in_expired(self, utcnow):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n credentials.token_expiry = datetime.datetime.utcnow()\n now = credentials.token_expiry + datetime.timedelta(seconds=1)\n self.assertLess(credentials.token_expiry, now)\n utcnow.return_value = now\n self.assertEqual(credentials._expires_in(), 0)\n utcnow.assert_called_once_with()\n\n @mock.patch('oauth2client.client._UTCNOW')\n def test__expires_in_not_expired(self, utcnow):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n credentials.token_expiry = datetime.datetime.utcnow()\n seconds = 1234\n now = credentials.token_expiry - datetime.timedelta(seconds=seconds)\n self.assertLess(now, credentials.token_expiry)\n utcnow.return_value = now\n self.assertEqual(credentials._expires_in(), seconds)\n utcnow.assert_called_once_with()\n", "method_code": " def _expires_in(self):\n \"\"\"Return the number of seconds until this token expires.\n \n If token_expiry is in the past, this method will return 0, meaning the\n token has already expired.\n \n If token_expiry is None, this method will return None. Note that\n returning 0 in such a case would not be fair: the token may still be\n valid; we just don't know anything about it.\n \"\"\"\n if self.token_expiry:\n now = _UTCNOW()\n if self.token_expiry > now:\n time_delta = self.token_expiry - now\n return time_delta.days * 86400 + time_delta.seconds\n else:\n return 0\n ", "context": "class OAuth2Credentials(Credentials):\n def _expires_in(self): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def has_scopes(self, scopes): ...\n def retrieve_scopes(self, http): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def get_access_token(self, http=None): ...\n def set_store(self, store): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__expires_in_no_expiry", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000096.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "get_access_token", "tests": "import unittest\n\nclass Test_get_access_token(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n def test_get_access_token(self, utcnow):\n seconds = 11\n NOW = datetime.datetime(1992, 12, 31, second=seconds)\n utcnow.return_value = NOW\n lifetime = 2\n EXPIRY_TIME = datetime.datetime(1992, 12, 31, second=seconds + lifetime)\n token1 = u'first_token'\n token_response_first = {'access_token': token1, 'expires_in': lifetime}\n token2 = u'second_token'\n token_response_second = {'access_token': token2, 'expires_in': lifetime}\n http = http_mock.HttpMockSequence([({'status': '200'}, json.dumps(token_response_first).encode('utf-8')), ({'status': '200'}, json.dumps(token_response_second).encode('utf-8'))])\n credentials = copy.deepcopy(self.credentials)\n credentials.access_token = None\n credentials.token_expiry = None\n self.assertEqual(credentials.access_token, None)\n self.assertFalse(credentials.access_token_expired)\n self.assertEqual(credentials.token_expiry, None)\n token = credentials.get_access_token(http=http)\n self.assertEqual(credentials.token_expiry, EXPIRY_TIME)\n self.assertEqual(token1, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertEqual(token_response_first, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * 2\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(credentials.access_token, token1)\n self.assertFalse(credentials.access_token_expired)\n token = credentials.get_access_token(http=http)\n self.assertEqual(token1, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertEqual(token_response_first, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * (2 + 3)\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(credentials.access_token, token1)\n credentials.token_expiry = NOW\n self.assertTrue(credentials.access_token_expired)\n token = credentials.get_access_token(http=http)\n self.assertEqual(token2, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertFalse(credentials.access_token_expired)\n self.assertEqual(token_response_second, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * (2 + 3 + 5)\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n", "method_code": " def get_access_token(self, http=None):\n \"\"\"Return the access token and its expiration information.\n \n If the token does not exist, get one.\n If the token expired, refresh it.\n \"\"\"\n if not self.access_token or self.access_token_expired:\n if not http:\n http = transport.get_http_object()\n self.refresh(http)\n return AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())\n ", "context": "class OAuth2Credentials(Credentials):\n def get_access_token(self, http=None): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def has_scopes(self, scopes): ...\n def retrieve_scopes(self, http): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def set_store(self, store): ...\n def _expires_in(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000097.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2Credentials", "focal_method": "get_access_token", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2Credentials_get_access_token(unittest.TestCase):\n @mock.patch.object(client.OAuth2Credentials, 'refresh')\n @mock.patch.object(client.OAuth2Credentials, '_expires_in', return_value=1835)\n def test_get_access_token_without_http(self, expires_in, refresh_mock):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n credentials.invalid = True\n credentials.access_token = 'ya29-s3kr3t'\n with mock.patch('oauth2client.transport.get_http_object', return_value=object()) as new_http:\n token_info = credentials.get_access_token()\n expires_in.assert_called_once_with()\n refresh_mock.assert_called_once_with(new_http.return_value)\n new_http.assert_called_once_with()\n self.assertIsInstance(token_info, client.AccessTokenInfo)\n self.assertEqual(token_info.access_token, credentials.access_token)\n self.assertEqual(token_info.expires_in, expires_in.return_value)\n\n @mock.patch.object(client.OAuth2Credentials, 'refresh')\n @mock.patch.object(client.OAuth2Credentials, '_expires_in', return_value=1835)\n def test_get_access_token_with_http(self, expires_in, refresh_mock):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n credentials.invalid = True\n credentials.access_token = 'ya29-s3kr3t'\n http_obj = object()\n token_info = credentials.get_access_token(http_obj)\n self.assertIsInstance(token_info, client.AccessTokenInfo)\n self.assertEqual(token_info.access_token, credentials.access_token)\n self.assertEqual(token_info.expires_in, expires_in.return_value)\n expires_in.assert_called_once_with()\n refresh_mock.assert_called_once_with(http_obj)\n", "method_code": " def get_access_token(self, http=None):\n \"\"\"Return the access token and its expiration information.\n \n If the token does not exist, get one.\n If the token expired, refresh it.\n \"\"\"\n if not self.access_token or self.access_token_expired:\n if not http:\n http = transport.get_http_object()\n self.refresh(http)\n return AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())\n ", "context": "class OAuth2Credentials(Credentials):\n def get_access_token(self, http=None): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def has_scopes(self, scopes): ...\n def retrieve_scopes(self, http): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def set_store(self, store): ...\n def _expires_in(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000098.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "has_scopes", "tests": "import unittest\n\nclass Test_has_scopes(unittest.TestCase):\n def test_has_scopes(self):\n self.assertTrue(self.credentials.has_scopes('foo'))\n self.assertTrue(self.credentials.has_scopes(['foo']))\n self.assertFalse(self.credentials.has_scopes('bar'))\n self.assertFalse(self.credentials.has_scopes(['bar']))\n self.credentials.scopes = set(['foo', 'bar'])\n self.assertTrue(self.credentials.has_scopes('foo'))\n self.assertTrue(self.credentials.has_scopes('bar'))\n self.assertFalse(self.credentials.has_scopes('baz'))\n self.assertTrue(self.credentials.has_scopes(['foo', 'bar']))\n self.assertFalse(self.credentials.has_scopes(['foo', 'baz']))\n self.credentials.scopes = set([])\n self.assertFalse(self.credentials.has_scopes('foo'))\n", "method_code": " def has_scopes(self, scopes):\n \"\"\"Verify that the credentials are authorized for the given scopes.\n \n Returns True if the credentials authorized scopes contain all of the\n scopes given.\n \n Args:\n scopes: list or string, the scopes to check.\n \n Notes:\n There are cases where the credentials are unaware of which scopes\n are authorized. Notably, credentials obtained and stored before\n this code was added will not have scopes, AccessTokenCredentials do\n not have scopes. In both cases, you can use refresh_scopes() to\n obtain the canonical set of scopes.\n \"\"\"\n scopes = _helpers.string_to_scopes(scopes)\n return set(scopes).issubset(self.scopes)\n ", "context": "class OAuth2Credentials(Credentials):\n def has_scopes(self, scopes): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def retrieve_scopes(self, http): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def get_access_token(self, http=None): ...\n def set_store(self, store): ...\n def _expires_in(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_has_scopes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000099.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "retrieve_scopes", "tests": "import unittest\n\nclass Test_retrieve_scopes(unittest.TestCase):\n def test_retrieve_scopes(self):\n info_response_first = {'scope': 'foo bar'}\n info_response_second = {'error_description': 'abcdef'}\n http = http_mock.HttpMockSequence([({'status': '200'}, json.dumps(info_response_first).encode('utf-8')), ({'status': '400'}, json.dumps(info_response_second).encode('utf-8')), ({'status': '500'}, b'')])\n self.credentials.retrieve_scopes(http)\n self.assertEqual(set(['foo', 'bar']), self.credentials.scopes)\n with self.assertRaises(client.Error):\n self.credentials.retrieve_scopes(http)\n with self.assertRaises(client.Error):\n self.credentials.retrieve_scopes(http)\n", "method_code": " def retrieve_scopes(self, http):\n \"\"\"Retrieves the canonical list of scopes for this access token.\n \n Gets the scopes from the OAuth2 provider.\n \n Args:\n http: httplib2.Http, an http object to be used to make the refresh\n request.\n \n Returns:\n A set of strings containing the canonical list of scopes.\n \"\"\"\n self._retrieve_scopes(http)\n return self.scopes\n ", "context": "class OAuth2Credentials(Credentials):\n def retrieve_scopes(self, http): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def has_scopes(self, scopes): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def get_access_token(self, http=None): ...\n def set_store(self, store): ...\n def _expires_in(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_retrieve_scopes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000100.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.AssertionCredentials", "focal_method": "_generate_assertion", "tests": "import unittest\n\nclass Test_oauth2client_client_AssertionCredentials_generate_assertion(unittest.TestCase):\n def test__generate_assertion_abstract(self):\n credentials = client.AssertionCredentials(None)\n with self.assertRaises(NotImplementedError):\n credentials._generate_assertion()\n", "method_code": " def _generate_assertion(self):\n \"\"\"Generate assertion string to be used in the access token request.\"\"\"\n raise NotImplementedError\n ", "context": "class AssertionCredentials(GoogleCredentials):\n def _generate_assertion(self): ...\n def __init__(self, assertion_type, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **unused_kwargs): ...\n def _generate_refresh_request_body(self): ...\n def _revoke(self, http): ...\n def sign_blob(self, blob): ...\n\n self.assertion_type = assertion_type\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__generate_assertion_abstract", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000101.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "step1_get_authorize_url", "tests": "import unittest\n\nclass Test_step1_get_authorize_url(unittest.TestCase):\n def test_construct_authorize_url(self):\n authorize_url = self.flow.step1_get_authorize_url(state='state+1')\n parsed = urllib.parse.urlparse(authorize_url)\n q = urllib.parse.parse_qs(parsed[4])\n self.assertEqual('client_id+1', q['client_id'][0])\n self.assertEqual('code', q['response_type'][0])\n self.assertEqual('foo', q['scope'][0])\n self.assertEqual(client.OOB_CALLBACK_URN, q['redirect_uri'][0])\n self.assertEqual('offline', q['access_type'][0])\n self.assertEqual('state+1', q['state'][0])\n", "method_code": " def step1_get_authorize_url(self, redirect_uri=None, state=None):\n \"\"\"Returns a URI to redirect to the provider.\n \n Args:\n redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'\n for a non-web-based application, or a URI that\n handles the callback from the authorization server.\n This parameter is deprecated, please move to passing\n the redirect_uri in via the constructor.\n state: string, Opaque state string which is passed through the\n OAuth2 flow and returned to the client as a query parameter\n in the callback.\n \n Returns:\n A URI as a string to redirect the user to begin the authorization\n flow.\n \"\"\"\n if redirect_uri is not None:\n logger.warning('The redirect_uri parameter for OAuth2WebServerFlow.step1_get_authorize_url is deprecated. Please move to passing the redirect_uri in via the constructor.')\n self.redirect_uri = redirect_uri\n if self.redirect_uri is None:\n raise ValueError('The value of redirect_uri must not be None.')\n query_params = {'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'scope': self.scope}\n if state is not None:\n query_params['state'] = state\n if self.login_hint is not None:\n query_params['login_hint'] = self.login_hint\n if self._pkce:\n if not self.code_verifier:\n self.code_verifier = _pkce.code_verifier()\n challenge = _pkce.code_challenge(self.code_verifier)\n query_params['code_challenge'] = challenge\n query_params['code_challenge_method'] = 'S256'\n query_params.update(self.params)\n return _helpers.update_query_params(self.auth_uri, query_params)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(1)\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_device_and_user_codes(self, http=None): ...\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_construct_authorize_url", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000102.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "_oauth2_web_server_flow_params", "tests": "import unittest\n\nclass Test_oauth2_web_server_flow_params(unittest.TestCase):\n def test__oauth2_web_server_flow_params(self):\n params = client._oauth2_web_server_flow_params({})\n self.assertEqual(params['access_type'], 'offline')\n self.assertEqual(params['response_type'], 'code')\n params = client._oauth2_web_server_flow_params({'approval_prompt': 'force'})\n self.assertEqual(params['prompt'], 'consent')\n self.assertNotIn('approval_prompt', params)\n params = client._oauth2_web_server_flow_params({'approval_prompt': 'other'})\n self.assertEqual(params['approval_prompt'], 'other')\n", "method_code": "def _oauth2_web_server_flow_params(kwargs):\n \"\"\"Configures redirect URI parameters for OAuth2WebServerFlow.\"\"\"\n params = {'access_type': 'offline', 'response_type': 'code'}\n params.update(kwargs)\n approval_prompt = params.get('approval_prompt')\n if approval_prompt is not None:\n logger.warning('The approval_prompt parameter for OAuth2WebServerFlow is deprecated. Please use the prompt parameter instead.')\n if approval_prompt == 'force':\n logger.warning('approval_prompt=\"force\" has been adjusted to prompt=\"consent\"')\n params['prompt'] = 'consent'\n del params['approval_prompt']\n return params", "context": "def _oauth2_web_server_flow_params(kwargs): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__oauth2_web_server_flow_params", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000103.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2WebServerFlow", "focal_method": "step1_get_authorize_url", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2WebServerFlow_step1_get_authorize_url(unittest.TestCase):\n @mock.patch('oauth2client.client.logger')\n def test_step1_get_authorize_url_redirect_override(self, logger):\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri=client.OOB_CALLBACK_URN)\n alt_redirect = 'foo:bar'\n self.assertEqual(flow.redirect_uri, client.OOB_CALLBACK_URN)\n result = flow.step1_get_authorize_url(redirect_uri=alt_redirect)\n self.assertEqual(flow.redirect_uri, alt_redirect)\n query_params = {'client_id': flow.client_id, 'redirect_uri': alt_redirect, 'scope': flow.scope, 'access_type': 'offline', 'response_type': 'code'}\n expected = _helpers.update_query_params(flow.auth_uri, query_params)\n assertUrisEqual(self, expected, result)\n self.assertEqual(logger.warning.call_count, 1)\n\n @mock.patch('oauth2client.client._pkce.code_challenge')\n @mock.patch('oauth2client.client._pkce.code_verifier')\n def test_step1_get_authorize_url_pkce(self, fake_verifier, fake_challenge):\n fake_verifier.return_value = self.good_verifier\n fake_challenge.return_value = self.good_challenger\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri='http://example.com', pkce=True)\n auth_url = urllib.parse.urlparse(flow.step1_get_authorize_url())\n self.assertEqual(flow.code_verifier, self.good_verifier)\n results = dict(urllib.parse.parse_qsl(auth_url.query))\n self.assertEqual(results['code_challenge'], self.good_challenger.decode())\n self.assertEqual(results['code_challenge_method'], 'S256')\n fake_verifier.assert_called()\n fake_challenge.assert_called_with(self.good_verifier)\n\n @mock.patch('oauth2client.client._pkce.code_challenge')\n @mock.patch('oauth2client.client._pkce.code_verifier')\n def test_step1_get_authorize_url_pkce_invalid_verifier(self, fake_verifier, fake_challenge):\n fake_verifier.return_value = self.good_verifier\n fake_challenge.return_value = self.good_challenger\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri='http://example.com', pkce=True, code_verifier=self.bad_verifier)\n auth_url = urllib.parse.urlparse(flow.step1_get_authorize_url())\n self.assertEqual(flow.code_verifier, self.bad_verifier)\n results = dict(urllib.parse.parse_qsl(auth_url.query))\n self.assertEqual(results['code_challenge'], self.good_challenger.decode())\n self.assertEqual(results['code_challenge_method'], 'S256')\n fake_verifier.assert_not_called()\n fake_challenge.assert_called_with(self.bad_verifier)\n\n def test_step1_get_authorize_url_without_redirect(self):\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri=None)\n with self.assertRaises(ValueError):\n flow.step1_get_authorize_url(redirect_uri=None)\n\n def test_step1_get_authorize_url_without_login_hint(self):\n login_hint = 'There are wascally wabbits nearby'\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri=client.OOB_CALLBACK_URN, login_hint=login_hint)\n result = flow.step1_get_authorize_url()\n query_params = {'client_id': flow.client_id, 'login_hint': login_hint, 'redirect_uri': client.OOB_CALLBACK_URN, 'scope': flow.scope, 'access_type': 'offline', 'response_type': 'code'}\n expected = _helpers.update_query_params(flow.auth_uri, query_params)\n assertUrisEqual(self, expected, result)\n", "method_code": " def step1_get_authorize_url(self, redirect_uri=None, state=None):\n \"\"\"Returns a URI to redirect to the provider.\n \n Args:\n redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'\n for a non-web-based application, or a URI that\n handles the callback from the authorization server.\n This parameter is deprecated, please move to passing\n the redirect_uri in via the constructor.\n state: string, Opaque state string which is passed through the\n OAuth2 flow and returned to the client as a query parameter\n in the callback.\n \n Returns:\n A URI as a string to redirect the user to begin the authorization\n flow.\n \"\"\"\n if redirect_uri is not None:\n logger.warning('The redirect_uri parameter for OAuth2WebServerFlow.step1_get_authorize_url is deprecated. Please move to passing the redirect_uri in via the constructor.')\n self.redirect_uri = redirect_uri\n if self.redirect_uri is None:\n raise ValueError('The value of redirect_uri must not be None.')\n query_params = {'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'scope': self.scope}\n if state is not None:\n query_params['state'] = state\n if self.login_hint is not None:\n query_params['login_hint'] = self.login_hint\n if self._pkce:\n if not self.code_verifier:\n self.code_verifier = _pkce.code_verifier()\n challenge = _pkce.code_challenge(self.code_verifier)\n query_params['code_challenge'] = challenge\n query_params['code_challenge_method'] = 'S256'\n query_params.update(self.params)\n return _helpers.update_query_params(self.auth_uri, query_params)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(1)\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_device_and_user_codes(self, http=None): ...\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000104.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2WebServerFlow", "focal_method": "step1_get_device_and_user_codes", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2WebServerFlow_step1_get_device_and_user_codes(unittest.TestCase):\n def test_step1_get_device_and_user_codes_wo_device_uri(self):\n flow = client.OAuth2WebServerFlow('CID', scope='foo', device_uri=None)\n with self.assertRaises(ValueError):\n flow.step1_get_device_and_user_codes()\n", "method_code": " def step1_get_device_and_user_codes(self, http=None):\n \"\"\"Returns a user code and the verification URL where to enter it\n \n Returns:\n A user code as a string for the user to authorize the application\n An URL as a string where the user has to enter the code\n \"\"\"\n if self.device_uri is None:\n raise ValueError('The value of device_uri must not be None.')\n body = urllib.parse.urlencode({'client_id': self.client_id, 'scope': self.scope})\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n if self.user_agent is not None:\n headers['user-agent'] = self.user_agent\n if http is None:\n http = transport.get_http_object()\n resp, content = transport.request(http, self.device_uri, method='POST', body=body, headers=headers)\n content = _helpers._from_bytes(content)\n if resp.status == http_client.OK:\n try:\n flow_info = json.loads(content)\n except ValueError as exc:\n raise OAuth2DeviceCodeError('Could not parse server response as JSON: \"{0}\", error: \"{1}\"'.format(content, exc))\n return DeviceFlowInfo.FromResponse(flow_info)\n else:\n error_msg = 'Invalid response {0}.'.format(resp.status)\n try:\n error_dict = json.loads(content)\n if 'error' in error_dict:\n error_msg += ' Error: {0}'.format(error_dict['error'])\n except ValueError:\n pass\n raise OAuth2DeviceCodeError(error_msg)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(1)\n def step1_get_device_and_user_codes(self, http=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_step1_get_device_and_user_codes_wo_device_uri", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000105.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2WebServerFlow", "focal_method": "step2_exchange", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2WebServerFlow_step2_exchange(unittest.TestCase):\n def test_step2_exchange_no_input(self):\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo')\n with self.assertRaises(ValueError):\n flow.step2_exchange()\n\n def test_exchange_with_pkce(self):\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, b'access_token=SlAV32hkKG')])\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri='http://example.com', pkce=True, code_verifier=self.good_verifier)\n flow.step2_exchange(code='some random code', http=http)\n self.assertEqual(len(http.requests), 1)\n test_request = http.requests[0]\n self.assertIn('code_verifier={0}'.format(self.good_verifier.decode()), test_request['body'])\n", "method_code": " def step2_exchange(self, code=None, http=None, device_flow_info=None):\n \"\"\"Exchanges a code for OAuth2Credentials.\n \n Args:\n code: string, a dict-like object, or None. For a non-device\n flow, this is either the response code as a string, or a\n dictionary of query parameters to the redirect_uri. For a\n device flow, this should be None.\n http: httplib2.Http, optional http instance to use when fetching\n credentials.\n device_flow_info: DeviceFlowInfo, return value from step1 in the\n case of a device flow.\n \n Returns:\n An OAuth2Credentials object that can be used to authorize requests.\n \n Raises:\n FlowExchangeError: if a problem occurred exchanging the code for a\n refresh_token.\n ValueError: if code and device_flow_info are both provided or both\n missing.\n \"\"\"\n if code is None and device_flow_info is None:\n raise ValueError('No code or device_flow_info provided.')\n if code is not None and device_flow_info is not None:\n raise ValueError('Cannot provide both code and device_flow_info.')\n if code is None:\n code = device_flow_info.device_code\n elif not isinstance(code, (six.string_types, six.binary_type)):\n if 'code' not in code:\n raise FlowExchangeError(code.get('error', 'No code was supplied in the query parameters.'))\n code = code['code']\n post_data = {'client_id': self.client_id, 'code': code, 'scope': self.scope}\n if self.client_secret is not None:\n post_data['client_secret'] = self.client_secret\n if self._pkce:\n post_data['code_verifier'] = self.code_verifier\n if device_flow_info is not None:\n post_data['grant_type'] = 'http://oauth.net/grant_type/device/1.0'\n else:\n post_data['grant_type'] = 'authorization_code'\n post_data['redirect_uri'] = self.redirect_uri\n body = urllib.parse.urlencode(post_data)\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n if self.authorization_header is not None:\n headers['Authorization'] = self.authorization_header\n if self.user_agent is not None:\n headers['user-agent'] = self.user_agent\n if http is None:\n http = transport.get_http_object()\n resp, content = transport.request(http, self.token_uri, method='POST', body=body, headers=headers)\n d = _parse_exchange_token_response(content)\n if resp.status == http_client.OK and 'access_token' in d:\n access_token = d['access_token']\n refresh_token = d.get('refresh_token', None)\n if not refresh_token:\n logger.info(\"Received token response with no refresh_token. Consider reauthenticating with prompt='consent'.\")\n token_expiry = None\n if 'expires_in' in d:\n delta = datetime.timedelta(seconds=int(d['expires_in']))\n token_expiry = delta + _UTCNOW()\n extracted_id_token = None\n if 'id_token' in d:\n extracted_id_token = _extract_id_token(d['id_token'])\n logger.info('Successfully retrieved access token')\n return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=extracted_id_token, token_response=d, scopes=self.scope, token_info_uri=self.token_info_uri)\n else:\n logger.info('Failed to retrieve access token: %s', content)\n if 'error' in d:\n error_msg = str(d['error']) + str(d.get('error_description', ''))\n else:\n error_msg = 'Invalid response: {0}.'.format(str(resp.status))\n raise FlowExchangeError(error_msg)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(2)\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def step1_get_device_and_user_codes(self, http=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_step2_exchange_no_input", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000106.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "step2_exchange", "tests": "import unittest\n\nclass Test_step2_exchange(unittest.TestCase):\n def test_exchange_failure(self):\n http = http_mock.HttpMock(headers={'status': http_client.BAD_REQUEST}, data=b'{\"error\":\"invalid_request\"}')\n with self.assertRaises(client.FlowExchangeError):\n self.flow.step2_exchange(code='some random code', http=http)\n\n def test_exchange_dictlike(self):\n\n class FakeDict(object):\n\n def __init__(self, d):\n self.d = d\n\n def __getitem__(self, name):\n return self.d[name]\n\n def __contains__(self, name):\n return name in self.d\n code = 'some random code'\n not_a_dict = FakeDict({'code': code})\n payload = b'{ \"access_token\":\"SlAV32hkKG\", \"expires_in\":3600, \"refresh_token\":\"8xLOxBtZp8\"}'\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, payload)])\n credentials = self.flow.step2_exchange(code=not_a_dict, http=http)\n self.assertEqual('SlAV32hkKG', credentials.access_token)\n self.assertNotEqual(None, credentials.token_expiry)\n self.assertEqual('8xLOxBtZp8', credentials.refresh_token)\n self.assertEqual('dummy_revoke_uri', credentials.revoke_uri)\n self.assertEqual(set(['foo']), credentials.scopes)\n self.assertEqual(len(http.requests), 1)\n request_code = urllib.parse.parse_qs(http.requests[0]['body'])['code'][0]\n self.assertEqual(code, request_code)\n\n def test_exchange_id_token(self):\n body = {'foo': 'bar'}\n body_json = json.dumps(body).encode('ascii')\n payload = base64.urlsafe_b64encode(body_json).strip(b'=')\n jwt = base64.urlsafe_b64encode(b'stuff') + b'.' + payload + b'.' + base64.urlsafe_b64encode(b'signature')\n payload = b'{ \"access_token\":\"SlAV32hkKG\", \"refresh_token\":\"8xLOxBtZp8\", \"id_token\": \"' + jwt + b'\"}'\n http = http_mock.HttpMock(data=payload)\n credentials = self.flow.step2_exchange(code='some random code', http=http)\n self.assertEqual(credentials.id_token, body)\n", "method_code": " def step2_exchange(self, code=None, http=None, device_flow_info=None):\n \"\"\"Exchanges a code for OAuth2Credentials.\n \n Args:\n code: string, a dict-like object, or None. For a non-device\n flow, this is either the response code as a string, or a\n dictionary of query parameters to the redirect_uri. For a\n device flow, this should be None.\n http: httplib2.Http, optional http instance to use when fetching\n credentials.\n device_flow_info: DeviceFlowInfo, return value from step1 in the\n case of a device flow.\n \n Returns:\n An OAuth2Credentials object that can be used to authorize requests.\n \n Raises:\n FlowExchangeError: if a problem occurred exchanging the code for a\n refresh_token.\n ValueError: if code and device_flow_info are both provided or both\n missing.\n \"\"\"\n if code is None and device_flow_info is None:\n raise ValueError('No code or device_flow_info provided.')\n if code is not None and device_flow_info is not None:\n raise ValueError('Cannot provide both code and device_flow_info.')\n if code is None:\n code = device_flow_info.device_code\n elif not isinstance(code, (six.string_types, six.binary_type)):\n if 'code' not in code:\n raise FlowExchangeError(code.get('error', 'No code was supplied in the query parameters.'))\n code = code['code']\n post_data = {'client_id': self.client_id, 'code': code, 'scope': self.scope}\n if self.client_secret is not None:\n post_data['client_secret'] = self.client_secret\n if self._pkce:\n post_data['code_verifier'] = self.code_verifier\n if device_flow_info is not None:\n post_data['grant_type'] = 'http://oauth.net/grant_type/device/1.0'\n else:\n post_data['grant_type'] = 'authorization_code'\n post_data['redirect_uri'] = self.redirect_uri\n body = urllib.parse.urlencode(post_data)\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n if self.authorization_header is not None:\n headers['Authorization'] = self.authorization_header\n if self.user_agent is not None:\n headers['user-agent'] = self.user_agent\n if http is None:\n http = transport.get_http_object()\n resp, content = transport.request(http, self.token_uri, method='POST', body=body, headers=headers)\n d = _parse_exchange_token_response(content)\n if resp.status == http_client.OK and 'access_token' in d:\n access_token = d['access_token']\n refresh_token = d.get('refresh_token', None)\n if not refresh_token:\n logger.info(\"Received token response with no refresh_token. Consider reauthenticating with prompt='consent'.\")\n token_expiry = None\n if 'expires_in' in d:\n delta = datetime.timedelta(seconds=int(d['expires_in']))\n token_expiry = delta + _UTCNOW()\n extracted_id_token = None\n if 'id_token' in d:\n extracted_id_token = _extract_id_token(d['id_token'])\n logger.info('Successfully retrieved access token')\n return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=extracted_id_token, token_response=d, scopes=self.scope, token_info_uri=self.token_info_uri)\n else:\n logger.info('Failed to retrieve access token: %s', content)\n if 'error' in d:\n error_msg = str(d['error']) + str(d.get('error_description', ''))\n else:\n error_msg = 'Invalid response: {0}.'.format(str(resp.status))\n raise FlowExchangeError(error_msg)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(2)\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def step1_get_device_and_user_codes(self, http=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_exchange_failure", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000107.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": null, "focal_method": "flow_from_clientsecrets", "tests": "import unittest\n\nclass Test_flow_from_clientsecrets(unittest.TestCase):\n def test_flow_from_clientsecrets_cached(self):\n cache_mock = http_mock.CacheMock()\n load_and_cache('client_secrets.json', 'some_secrets', cache_mock)\n flow = client.flow_from_clientsecrets('some_secrets', '', redirect_uri='oob', cache=cache_mock)\n self.assertEqual('foo_client_secret', flow.client_secret)\n\n @mock.patch('oauth2client.clientsecrets.loadfile', side_effect=clientsecrets.InvalidClientSecretsError)\n def test_flow_from_clientsecrets_invalid(self, loadfile_mock):\n filename = object()\n cache = object()\n with self.assertRaises(clientsecrets.InvalidClientSecretsError):\n client.flow_from_clientsecrets(filename, None, cache=cache, message=None)\n loadfile_mock.assert_called_once_with(filename, cache=cache)\n\n @mock.patch('oauth2client.clientsecrets.loadfile', side_effect=clientsecrets.InvalidClientSecretsError)\n @mock.patch('sys.exit')\n def test_flow_from_clientsecrets_invalid_w_msg(self, sys_exit, loadfile_mock):\n filename = object()\n cache = object()\n message = 'hi mom'\n client.flow_from_clientsecrets(filename, None, cache=cache, message=message)\n sys_exit.assert_called_once_with(message)\n loadfile_mock.assert_called_once_with(filename, cache=cache)\n\n @mock.patch('oauth2client.clientsecrets.loadfile', side_effect=clientsecrets.InvalidClientSecretsError('foobar'))\n @mock.patch('sys.exit')\n def test_flow_from_clientsecrets_invalid_w_msg_and_text(self, sys_exit, loadfile_mock):\n filename = object()\n cache = object()\n message = 'hi mom'\n expected = 'The client secrets were invalid: \\n{0}\\n{1}'.format('foobar', 'hi mom')\n client.flow_from_clientsecrets(filename, None, cache=cache, message=message)\n sys_exit.assert_called_once_with(expected)\n loadfile_mock.assert_called_once_with(filename, cache=cache)\n\n @mock.patch('oauth2client.clientsecrets.loadfile')\n def test_flow_from_clientsecrets_unknown_flow(self, loadfile_mock):\n client_type = 'UNKNOWN'\n loadfile_mock.return_value = (client_type, None)\n filename = object()\n cache = object()\n err_msg = 'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type)\n with self.assertRaisesRegexp(client.UnknownClientSecretsFlowError, err_msg):\n client.flow_from_clientsecrets(filename, None, cache=cache)\n loadfile_mock.assert_called_once_with(filename, cache=cache)\n", "method_code": "def flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None):\n \"\"\"Create a Flow from a clientsecrets file.\n\n Will create the right kind of Flow based on the contents of the\n clientsecrets file or will raise InvalidClientSecretsError for unknown\n types of Flows.\n\n Args:\n filename: string, File name of client secrets.\n scope: string or iterable of strings, scope(s) to request.\n redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for\n a non-web-based application, or a URI that handles the\n callback from the authorization server.\n message: string, A friendly string to display to the user if the\n clientsecrets file is missing or invalid. If message is\n provided then sys.exit will be called in the case of an error.\n If message in not provided then\n clientsecrets.InvalidClientSecretsError will be raised.\n cache: An optional cache service client that implements get() and set()\n methods. See clientsecrets.loadfile() for details.\n login_hint: string, Either an email address or domain. Passing this\n hint will either pre-fill the email box on the sign-in form\n or select the proper multi-login session, thereby\n simplifying the login flow.\n device_uri: string, URI for device authorization endpoint. For\n convenience defaults to Google's endpoints but any\n OAuth 2.0 provider can be used.\n\n Returns:\n A Flow object.\n\n Raises:\n UnknownClientSecretsFlowError: if the file describes an unknown kind of\n Flow.\n clientsecrets.InvalidClientSecretsError: if the clientsecrets file is\n invalid.\n \"\"\"\n try:\n client_type, client_info = clientsecrets.loadfile(filename, cache=cache)\n if client_type in (clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED):\n constructor_kwargs = {'redirect_uri': redirect_uri, 'auth_uri': client_info['auth_uri'], 'token_uri': client_info['token_uri'], 'login_hint': login_hint}\n revoke_uri = client_info.get('revoke_uri')\n optional = ('revoke_uri', 'device_uri', 'pkce', 'code_verifier')\n for param in optional:\n if locals()[param] is not None:\n constructor_kwargs[param] = locals()[param]\n return OAuth2WebServerFlow(client_info['client_id'], client_info['client_secret'], scope, **constructor_kwargs)\n except clientsecrets.InvalidClientSecretsError as e:\n if message is not None:\n if e.args:\n message = 'The client secrets were invalid: \\n{0}\\n{1}'.format(e, message)\n sys.exit(message)\n else:\n raise\n else:\n raise UnknownClientSecretsFlowError('This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type))", "context": "@_helpers.positional(2)\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_flow_from_clientsecrets_cached", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000108.py"} {"focal_file": "lib/oauth2client/client.py", "focal_class": "oauth2client.client.DeviceFlowInfo", "focal_method": "FromResponse", "tests": "import unittest\n\nclass Test_oauth2client_client_DeviceFlowInfo_FromResponse(unittest.TestCase):\n def test_FromResponse(self):\n response = {'device_code': self.DEVICE_CODE, 'user_code': self.USER_CODE, 'verification_url': self.VER_URL}\n result = client.DeviceFlowInfo.FromResponse(response)\n expected_result = client.DeviceFlowInfo(self.DEVICE_CODE, self.USER_CODE, None, self.VER_URL, None)\n self.assertEqual(result, expected_result)\n", "method_code": " def FromResponse(cls, response):\n \"\"\"Create a DeviceFlowInfo from a server response.\n \n The response should be a dict containing entries as described here:\n \n http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1\n \"\"\"\n kwargs = {'device_code': response['device_code'], 'user_code': response['user_code']}\n verification_url = response.get('verification_url', response.get('verification_uri'))\n if verification_url is None:\n raise OAuth2DeviceCodeError('No verification_url provided in server response')\n kwargs['verification_url'] = verification_url\n kwargs.update({'interval': response.get('interval'), 'user_code_expiry': None})\n if 'expires_in' in response:\n kwargs['user_code_expiry'] = _UTCNOW() + datetime.timedelta(seconds=int(response['expires_in']))\n return cls(**kwargs)\n ", "context": "class DeviceFlowInfo(collections.namedtuple('DeviceFlowInfo', ('device_code', 'user_code', 'interval', 'verification_url', 'user_code_expiry'))):\n @classmethod\n def FromResponse(cls, response): ...", "repository": "designspired/TaskManagerGAE", "test_name": "test_FromResponse", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000109.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": "oauth2client.service_account.ServiceAccountCredentials", "focal_method": "_to_json", "tests": "import unittest\n\nclass Test_oauth2client_service_account_ServiceAccountCredentials_to_json(unittest.TestCase):\n def test__to_json_override(self):\n signer = object()\n creds = service_account.ServiceAccountCredentials('name@email.com', signer)\n self.assertEqual(creds._signer, signer)\n to_serialize = {'unrelated': 'data'}\n serialized_str = creds._to_json([], to_serialize.copy())\n serialized_data = json.loads(serialized_str)\n expected_serialized = {'_class': 'ServiceAccountCredentials', '_module': 'oauth2client.service_account', 'token_expiry': None}\n expected_serialized.update(to_serialize)\n self.assertEqual(serialized_data, expected_serialized)\n", "method_code": " def _to_json(self, strip, to_serialize=None):\n \"\"\"Utility function that creates JSON repr. of a credentials object.\n \n Over-ride is needed since PKCS#12 keys will not in general be JSON\n serializable.\n \n Args:\n strip: array, An array of names of members to exclude from the\n JSON.\n to_serialize: dict, (Optional) The properties for this object\n that will be serialized. This allows callers to\n modify before serializing.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n if to_serialize is None:\n to_serialize = copy.copy(self.__dict__)\n pkcs12_val = to_serialize.get(_PKCS12_KEY)\n if pkcs12_val is not None:\n to_serialize[_PKCS12_KEY] = base64.b64encode(pkcs12_val)\n return super(ServiceAccountCredentials, self)._to_json(strip, to_serialize=to_serialize)\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def _to_json(self, strip, to_serialize=None): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__to_json_override", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000110.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": null, "focal_method": "sign_blob", "tests": "import unittest\n\nclass Test_sign_blob(unittest.TestCase):\n def test_sign_blob(self):\n private_key_id, signature = self.credentials.sign_blob('Google')\n self.assertEqual(self.private_key_id, private_key_id)\n pub_key = rsa.PublicKey.load_pkcs1_openssl_pem(datafile('publickey_openssl.pem'))\n self.assertTrue(rsa.pkcs1.verify(b'Google', signature, pub_key))\n with self.assertRaises(rsa.pkcs1.VerificationError):\n rsa.pkcs1.verify(b'Orest', signature, pub_key)\n with self.assertRaises(rsa.pkcs1.VerificationError):\n rsa.pkcs1.verify(b'Google', b'bad signature', pub_key)\n", "method_code": " def sign_blob(self, blob):\n \"\"\"Cryptographically sign a blob (of bytes).\n \n Implements abstract method\n :meth:`oauth2client.client.AssertionCredentials.sign_blob`.\n \n Args:\n blob: bytes, Message to be signed.\n \n Returns:\n tuple, A pair of the private key ID used to sign the blob and\n the signed contents.\n \"\"\"\n return (self._private_key_id, self._signer.sign(blob))\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def sign_blob(self, blob): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_sign_blob", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000111.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": null, "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required_without_scopes(self):\n self.assertTrue(self.credentials.create_scoped_required())\n\n def test_create_scoped_required(self):\n self.assertTrue(self.jwt.create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n return not self._scopes\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def create_scoped_required(self): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_scoped_required_without_scopes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000112.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": "oauth2client.service_account.ServiceAccountCredentials", "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_oauth2client_service_account_ServiceAccountCredentials_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required_with_scopes(self):\n signer = object()\n self.credentials = service_account.ServiceAccountCredentials(self.service_account_email, signer, scopes=self.scopes, private_key_id=self.private_key_id, client_id=self.client_id)\n self.assertFalse(self.credentials.create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n return not self._scopes\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def create_scoped_required(self): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_scoped_required_with_scopes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000113.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": null, "focal_method": "create_scoped", "tests": "import unittest\n\nclass Test_create_scoped(unittest.TestCase):\n def test_create_scoped(self):\n self.jwt._private_key_pkcs12 = ''\n self.jwt._private_key_password = ''\n new_credentials = self.jwt.create_scoped('dummy_scope')\n self.assertNotEqual(self.jwt, new_credentials)\n self.assertIsInstance(new_credentials, service_account.ServiceAccountCredentials)\n self.assertEqual('dummy_scope', new_credentials._scopes)\n", "method_code": " def create_scoped(self, scopes):\n result = self.__class__(self._service_account_email, self._signer, scopes=scopes, private_key_id=self._private_key_id, client_id=self.client_id, user_agent=self._user_agent, **self._kwargs)\n result.token_uri = self.token_uri\n result.revoke_uri = self.revoke_uri\n result._private_key_pkcs8_pem = self._private_key_pkcs8_pem\n result._private_key_pkcs12 = self._private_key_pkcs12\n result._private_key_password = self._private_key_password\n return result\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def create_scoped(self, scopes): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped_required(self): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_scoped", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000114.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": "oauth2client.service_account.ServiceAccountCredentials", "focal_method": "create_delegated", "tests": "import unittest\n\nclass Test_oauth2client_service_account_ServiceAccountCredentials_create_delegated(unittest.TestCase):\n def test_create_delegated(self):\n signer = object()\n sub = 'foo@email.com'\n creds = service_account.ServiceAccountCredentials('name@email.com', signer)\n self.assertNotIn('sub', creds._kwargs)\n delegated_creds = creds.create_delegated(sub)\n self.assertEqual(delegated_creds._kwargs['sub'], sub)\n self.assertNotIn('sub', creds._kwargs)\n\n def test_create_delegated_existing_sub(self):\n signer = object()\n sub1 = 'existing@email.com'\n sub2 = 'new@email.com'\n creds = service_account.ServiceAccountCredentials('name@email.com', signer, sub=sub1)\n self.assertEqual(creds._kwargs['sub'], sub1)\n delegated_creds = creds.create_delegated(sub2)\n self.assertEqual(delegated_creds._kwargs['sub'], sub2)\n self.assertEqual(creds._kwargs['sub'], sub1)\n", "method_code": " def create_delegated(self, sub):\n \"\"\"Create credentials that act as domain-wide delegation of authority.\n \n Use the ``sub`` parameter as the subject to delegate on behalf of\n that user.\n \n For example::\n \n >>> account_sub = 'foo@email.com'\n >>> delegate_creds = creds.create_delegated(account_sub)\n \n Args:\n sub: string, An email address that this service account will\n act on behalf of (via domain-wide delegation).\n \n Returns:\n ServiceAccountCredentials, a copy of the current service account\n updated to act on behalf of ``sub``.\n \"\"\"\n return self.create_with_claims({'sub': sub})\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def create_delegated(self, sub): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_delegated", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000115.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": "oauth2client.service_account.ServiceAccountCredentials", "focal_method": "get_access_token", "tests": "import unittest\n\nclass Test_oauth2client_service_account_ServiceAccountCredentials_get_access_token(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n def test_access_token(self, utcnow):\n seconds = 11\n NOW = datetime.datetime(1992, 12, 31, second=seconds)\n utcnow.return_value = NOW\n signer = mock.Mock()\n signed_value = b'signed-content'\n signer.sign = mock.Mock(name='sign', return_value=signed_value)\n credentials = service_account.ServiceAccountCredentials(self.service_account_email, signer, private_key_id=self.private_key_id, client_id=self.client_id)\n lifetime = 2\n EXPIRY_TIME = datetime.datetime(1992, 12, 31, second=seconds + lifetime)\n token1 = u'first_token'\n token_response_first = {'access_token': token1, 'expires_in': lifetime}\n token2 = u'second_token'\n token_response_second = {'access_token': token2, 'expires_in': lifetime}\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, json.dumps(token_response_first).encode('utf-8')), ({'status': http_client.OK}, json.dumps(token_response_second).encode('utf-8'))])\n self.assertIsNone(credentials.access_token)\n self.assertFalse(credentials.access_token_expired)\n self.assertIsNone(credentials.token_expiry)\n token = credentials.get_access_token(http=http)\n self.assertEqual(credentials.token_expiry, EXPIRY_TIME)\n self.assertEqual(token1, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertEqual(token_response_first, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * 2\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(len(signer.sign.mock_calls), 1)\n self.assertEqual(credentials.access_token, token1)\n self.assertFalse(credentials.access_token_expired)\n token = credentials.get_access_token(http=http)\n self.assertEqual(token1, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertEqual(token_response_first, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * (2 + 3)\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(len(signer.sign.mock_calls), 1 + 0)\n self.assertEqual(credentials.access_token, token1)\n credentials.token_expiry = NOW\n self.assertTrue(credentials.access_token_expired)\n token = credentials.get_access_token(http=http)\n self.assertEqual(token2, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertFalse(credentials.access_token_expired)\n self.assertEqual(token_response_second, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * (2 + 3 + 5)\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(len(signer.sign.mock_calls), 1 + 0 + 1)\n self.assertEqual(credentials.access_token, token2)\n", "method_code": " def get_access_token(self, http=None, additional_claims=None):\n \"\"\"Create a signed jwt.\n \n Args:\n http: unused\n additional_claims: dict, additional claims to add to\n the payload of the JWT.\n Returns:\n An AccessTokenInfo with the signed jwt\n \"\"\"\n if additional_claims is None:\n if self.access_token is None or self.access_token_expired:\n self.refresh(None)\n return client.AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())\n else:\n token, unused_expiry = self._create_token(additional_claims)\n return client.AccessTokenInfo(access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def get_access_token(self, http=None, additional_claims=None): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def authorize(self, http): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000116.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": null, "focal_method": "get_access_token", "tests": "import unittest\n\nclass Test_get_access_token(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n @mock.patch('time.time')\n def test_get_access_token_no_claims(self, time, utcnow):\n utcnow.return_value = T1_DATE\n time.return_value = T1\n token_info = self.jwt.get_access_token()\n certs = {'key': datafile('public_cert.pem')}\n payload = crypt.verify_signed_jwt_with_certs(token_info.access_token, certs, audience=self.url)\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], self.service_account_email)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(payload['aud'], self.url)\n self.assertEqual(token_info.expires_in, T1_EXPIRY - T1)\n utcnow.return_value = T2_DATE\n token_info = self.jwt.get_access_token()\n payload = crypt.verify_signed_jwt_with_certs(token_info.access_token, {'key': datafile('public_cert.pem')}, audience=self.url)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(token_info.expires_in, T1_EXPIRY - T2)\n utcnow.return_value = T3_DATE\n time.return_value = T3\n token_info = self.jwt.get_access_token()\n payload = crypt.verify_signed_jwt_with_certs(token_info.access_token, {'key': datafile('public_cert.pem')}, audience=self.url)\n expires_in = token_info.expires_in\n self.assertEqual(payload['iat'], T3)\n self.assertEqual(payload['exp'], T3_EXPIRY)\n self.assertEqual(expires_in, T3_EXPIRY - T3)\n\n @mock.patch('oauth2client.client._UTCNOW')\n @mock.patch('time.time')\n def test_get_access_token_additional_claims(self, time, utcnow):\n utcnow.return_value = T1_DATE\n time.return_value = T1\n audience = 'https://test2.url.com'\n subject = 'dummy2@google.com'\n claims = {'aud': audience, 'sub': subject}\n token_info = self.jwt.get_access_token(additional_claims=claims)\n certs = {'key': datafile('public_cert.pem')}\n payload = crypt.verify_signed_jwt_with_certs(token_info.access_token, certs, audience=audience)\n expires_in = token_info.expires_in\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], subject)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(payload['aud'], audience)\n self.assertEqual(expires_in, T1_EXPIRY - T1)\n", "method_code": " def get_access_token(self, http=None, additional_claims=None):\n \"\"\"Create a signed jwt.\n \n Args:\n http: unused\n additional_claims: dict, additional claims to add to\n the payload of the JWT.\n Returns:\n An AccessTokenInfo with the signed jwt\n \"\"\"\n if additional_claims is None:\n if self.access_token is None or self.access_token_expired:\n self.refresh(None)\n return client.AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())\n else:\n token, unused_expiry = self._create_token(additional_claims)\n return client.AccessTokenInfo(access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def get_access_token(self, http=None, additional_claims=None): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def authorize(self, http): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000117.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": null, "focal_method": "revoke", "tests": "import unittest\n\nclass Test_revoke(unittest.TestCase):\n def test_revoke(self):\n self.jwt.revoke(None)\n", "method_code": " def revoke(self, http):\n \"\"\"Cannot revoke JWTAccessCredentials tokens.\"\"\"\n pass\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def revoke(self, http): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def authorize(self, http): ...\n def get_access_token(self, http=None, additional_claims=None): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_revoke", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000118.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": null, "focal_method": "authorize", "tests": "import unittest\n\nclass Test_authorize(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n @mock.patch('time.time')\n def test_authorize_success(self, time, utcnow):\n utcnow.return_value = T1_DATE\n time.return_value = T1\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, b''), ({'status': http_client.OK}, b'')])\n self.jwt.authorize(http)\n transport.request(http, self.url)\n utcnow.return_value = T2_DATE\n transport.request(http, self.url)\n certs = {'key': datafile('public_cert.pem')}\n self.assertEqual(len(http.requests), 2)\n for info in http.requests:\n self.assertEqual(info['method'], 'GET')\n self.assertEqual(info['uri'], self.url)\n self.assertIsNone(info['body'])\n self.assertEqual(len(info['headers']), 1)\n bearer, token = info['headers'][b'Authorization'].split()\n self.assertEqual(bearer, b'Bearer')\n payload = crypt.verify_signed_jwt_with_certs(token, certs, audience=self.url)\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], self.service_account_email)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(payload['aud'], self.url)\n\n @mock.patch('oauth2client.client._UTCNOW')\n def test_authorize_401(self, utcnow):\n utcnow.return_value = T1_DATE\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, b''), ({'status': http_client.UNAUTHORIZED}, b''), ({'status': http_client.OK}, b'')])\n self.jwt.authorize(http)\n transport.request(http, self.url)\n token_1 = self.jwt.access_token\n utcnow.return_value = T2_DATE\n response, _ = transport.request(http, self.url)\n self.assertEquals(response.status, http_client.OK)\n token_2 = self.jwt.access_token\n self.assertNotEqual(token_1, token_2)\n certs = {'key': datafile('public_cert.pem')}\n self.assertEqual(len(http.requests), 3)\n issued_at_vals = (T1, T1, T2)\n exp_vals = (T1_EXPIRY, T1_EXPIRY, T2_EXPIRY)\n for info, issued_at, exp_val in zip(http.requests, issued_at_vals, exp_vals):\n self.assertEqual(info['uri'], self.url)\n self.assertEqual(info['method'], 'GET')\n self.assertIsNone(info['body'])\n self.assertEqual(len(info['headers']), 1)\n bearer, token = info['headers'][b'Authorization'].split()\n self.assertEqual(bearer, b'Bearer')\n with mock.patch('oauth2client.crypt._verify_time_range', return_value=True):\n payload = crypt.verify_signed_jwt_with_certs(token, certs, audience=self.url)\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], self.service_account_email)\n self.assertEqual(payload['iat'], issued_at)\n self.assertEqual(payload['exp'], exp_val)\n self.assertEqual(payload['aud'], self.url)\n", "method_code": " def authorize(self, http):\n \"\"\"Authorize an httplib2.Http instance with a JWT assertion.\n \n Unless specified, the 'aud' of the assertion will be the base\n uri of the request.\n \n Args:\n http: An instance of ``httplib2.Http`` or something that acts\n like it.\n Returns:\n A modified instance of http that was passed in.\n Example::\n h = httplib2.Http()\n h = credentials.authorize(h)\n \"\"\"\n transport.wrap_http_for_jwt_access(self, http)\n return http\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def authorize(self, http): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def get_access_token(self, http=None, additional_claims=None): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000119.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": "oauth2client.service_account._JWTAccessCredentials", "focal_method": "authorize", "tests": "import unittest\n\nclass Test_oauth2client_service_account_JWTAccessCredentials_authorize(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n @mock.patch('time.time')\n def test_authorize_no_aud(self, time, utcnow):\n utcnow.return_value = T1_DATE\n time.return_value = T1\n jwt = service_account._JWTAccessCredentials(self.service_account_email, self.signer, private_key_id=self.private_key_id, client_id=self.client_id)\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, b'')])\n jwt.authorize(http)\n transport.request(http, self.url)\n self.assertIsNone(jwt.access_token)\n self.assertEqual(len(http.requests), 1)\n info = http.requests[0]\n self.assertEqual(info['method'], 'GET')\n self.assertEqual(info['uri'], self.url)\n self.assertIsNone(info['body'])\n self.assertEqual(len(info['headers']), 1)\n bearer, token = info['headers'][b'Authorization'].split()\n self.assertEqual(bearer, b'Bearer')\n certs = {'key': datafile('public_cert.pem')}\n payload = crypt.verify_signed_jwt_with_certs(token, certs, audience=self.url)\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], self.service_account_email)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(payload['aud'], self.url)\n", "method_code": " def authorize(self, http):\n \"\"\"Authorize an httplib2.Http instance with a JWT assertion.\n \n Unless specified, the 'aud' of the assertion will be the base\n uri of the request.\n \n Args:\n http: An instance of ``httplib2.Http`` or something that acts\n like it.\n Returns:\n A modified instance of http that was passed in.\n Example::\n h = httplib2.Http()\n h = credentials.authorize(h)\n \"\"\"\n transport.wrap_http_for_jwt_access(self, http)\n return http\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def authorize(self, http): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def get_access_token(self, http=None, additional_claims=None): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000120.py"} {"focal_file": "lib/oauth2client/service_account.py", "focal_class": null, "focal_method": "refresh", "tests": "import unittest\n\nclass Test_refresh(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n def test_refresh(self, utcnow):\n utcnow.return_value = T1_DATE\n token_1 = self.jwt.access_token\n utcnow.return_value = T2_DATE\n self.jwt.refresh(None)\n token_2 = self.jwt.access_token\n self.assertEquals(self.jwt.token_expiry, T2_EXPIRY_DATE)\n self.assertNotEqual(token_1, token_2)\n", "method_code": " def refresh(self, http):\n \"\"\"Refreshes the access_token.\n \n The HTTP object is unused since no request needs to be made to\n get a new token, it can just be generated locally.\n \n Args:\n http: unused HTTP object\n \"\"\"\n self._refresh(None)\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def refresh(self, http): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def authorize(self, http): ...\n def get_access_token(self, http=None, additional_claims=None): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000121.py"} {"focal_file": "lib/oauth2client/tools.py", "focal_class": null, "focal_method": "message_if_missing", "tests": "import unittest\n\nclass Test_message_if_missing(unittest.TestCase):\n def test_message_if_missing(self):\n self.assertIn('somefile.txt', tools.message_if_missing('somefile.txt'))\n", "method_code": "def message_if_missing(filename):\n \"\"\"Helpful message to display if the CLIENT_SECRETS file is missing.\"\"\"\n return _CLIENT_SECRETS_MESSAGE.format(file_path=filename)", "context": "def message_if_missing(filename): ...\ndef _CreateArgumentParser(): ...\ndef run_flow(flow, storage, flags=None, http=None): ...\ndef message_if_missing(filename): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_message_if_missing", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000122.py"} {"focal_file": "lib/oauth2client/transport.py", "focal_class": "oauth2client.transport.MemoryCache", "focal_method": "delete", "tests": "import unittest\n\nclass Test_oauth2client_transport_MemoryCache_delete(unittest.TestCase):\n def test_get_set_delete(self):\n cache = transport.MemoryCache()\n self.assertIsNone(cache.get('foo'))\n self.assertIsNone(cache.delete('foo'))\n cache.set('foo', 'bar')\n self.assertEqual('bar', cache.get('foo'))\n cache.delete('foo')\n self.assertIsNone(cache.get('foo'))\n", "method_code": " def delete(self, key):\n self.cache.pop(key, None)\n ", "context": "class MemoryCache(object):\n def delete(self, key): ...\n def __init__(self): ...\n def get(self, key): ...\n def set(self, key, value): ...\n\n self.cache = {}\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_get_set_delete", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000123.py"} {"focal_file": "lib/oauth2client/contrib/devshell.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n with self.assertRaises(NotImplementedError):\n devshell.DevshellCredentials.from_json(None)\n", "method_code": " def from_json(cls, json_data):\n raise NotImplementedError('Cannot load Developer Shell credentials from JSON.')\n ", "context": "class DevshellCredentials(client.GoogleCredentials):\n @classmethod\n def from_json(cls, json_data): ...\n def __init__(self, user_agent=None): ...\n def _refresh(self, http): ...\n def user_email(self): ...\n def project_id(self): ...\n def serialization_data(self): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_from_json", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000124.py"} {"focal_file": "lib/oauth2client/contrib/flask_util.py", "focal_class": "oauth2client.contrib.flask_util.UserOAuth2", "focal_method": "_make_flow", "tests": "import unittest\n\nclass Test_oauth2client_contrib_flask_util_UserOAuth2_make_flow(unittest.TestCase):\n def test_create_flow(self):\n with self.app.test_request_context():\n flow = self.oauth2._make_flow()\n state = json.loads(flow.params['state'])\n self.assertIn('google_oauth2_csrf_token', flask.session)\n self.assertEqual(flask.session['google_oauth2_csrf_token'], state['csrf_token'])\n self.assertEqual(flow.client_id, self.oauth2.client_id)\n self.assertEqual(flow.client_secret, self.oauth2.client_secret)\n self.assertIn('http', flow.redirect_uri)\n self.assertIn('oauth2callback', flow.redirect_uri)\n flow = self.oauth2._make_flow(return_url='/return_url')\n state = json.loads(flow.params['state'])\n self.assertEqual(state['return_url'], '/return_url')\n flow = self.oauth2._make_flow(extra_arg='test')\n self.assertEqual(flow.params['extra_arg'], 'test')\n app = flask.Flask(__name__)\n app.config['SECRET_KEY'] = 'notasecert'\n oauth2 = flask_util.UserOAuth2(app, client_id='client_id', client_secret='secret', extra_arg='test')\n with app.test_request_context():\n flow = oauth2._make_flow()\n self.assertEqual(flow.params['extra_arg'], 'test')\n", "method_code": " def _make_flow(self, return_url=None, **kwargs):\n \"\"\"Creates a Web Server Flow\"\"\"\n csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest()\n session[_CSRF_KEY] = csrf_token\n state = json.dumps({'csrf_token': csrf_token, 'return_url': return_url})\n kw = self.flow_kwargs.copy()\n kw.update(kwargs)\n extra_scopes = kw.pop('scopes', [])\n scopes = set(self.scopes).union(set(extra_scopes))\n flow = client.OAuth2WebServerFlow(client_id=self.client_id, client_secret=self.client_secret, scope=scopes, state=state, redirect_uri=url_for('oauth2.callback', _external=True), **kw)\n flow_key = _FLOW_KEY.format(csrf_token)\n session[flow_key] = pickle.dumps(flow)\n return flow\n ", "context": "class UserOAuth2(object):\n def _make_flow(self, return_url=None, **kwargs): ...\n def __init__(self, app=None, *args, **kwargs): ...\n def init_app(self, app, scopes=None, client_secrets_file=None, client_id=None, client_secret=None, authorize_callback=None, storage=None, **kwargs): ...\n def _load_config(self, client_secrets_file, client_id, client_secret): ...\n def _load_client_secrets(self, filename): ...\n def _create_blueprint(self): ...\n def authorize_view(self): ...\n def callback_view(self): ...\n def credentials(self): ...\n def has_credentials(self): ...\n def email(self): ...\n def user_id(self): ...\n def authorize_url(self, return_url, **kwargs): ...\n def required(self, decorated_function=None, scopes=None, **decorator_kwargs): ...\n def http(self, *args, **kwargs): ...\n\n self.app = app\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_flow", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000125.py"} {"focal_file": "lib/oauth2client/contrib/flask_util.py", "focal_class": null, "focal_method": "has_credentials", "tests": "import unittest\n\nclass Test_has_credentials(unittest.TestCase):\n def test_no_credentials(self):\n with self.app.test_request_context():\n self.assertFalse(self.oauth2.has_credentials())\n self.assertTrue(self.oauth2.credentials is None)\n self.assertTrue(self.oauth2.user_id is None)\n self.assertTrue(self.oauth2.email is None)\n with self.assertRaises(ValueError):\n self.oauth2.http()\n self.assertFalse(self.oauth2.storage.get())\n self.oauth2.storage.delete()\n\n @mock.patch('oauth2client.client._UTCNOW')\n def test_with_expired_credentials(self, utcnow):\n utcnow.return_value = datetime.datetime(1990, 5, 29)\n credentials = self._generate_credentials()\n credentials.token_expiry = datetime.datetime(1990, 5, 28)\n with self.app.test_request_context():\n self.oauth2.storage.put(credentials)\n self.assertTrue(self.oauth2.has_credentials())\n credentials.refresh_token = None\n with self.app.test_request_context():\n self.oauth2.storage.put(credentials)\n self.assertFalse(self.oauth2.has_credentials())\n", "method_code": " def has_credentials(self):\n \"\"\"Returns True if there are valid credentials for the current user.\"\"\"\n if not self.credentials:\n return False\n elif self.credentials.access_token_expired and (not self.credentials.refresh_token):\n return False\n else:\n return True\n ", "context": "class UserOAuth2(object):\n def has_credentials(self): ...\n def __init__(self, app=None, *args, **kwargs): ...\n def init_app(self, app, scopes=None, client_secrets_file=None, client_id=None, client_secret=None, authorize_callback=None, storage=None, **kwargs): ...\n def _load_config(self, client_secrets_file, client_id, client_secret): ...\n def _load_client_secrets(self, filename): ...\n def _make_flow(self, return_url=None, **kwargs): ...\n def _create_blueprint(self): ...\n def authorize_view(self): ...\n def callback_view(self): ...\n def credentials(self): ...\n def email(self): ...\n def user_id(self): ...\n def authorize_url(self, return_url, **kwargs): ...\n def required(self, decorated_function=None, scopes=None, **decorator_kwargs): ...\n def http(self, *args, **kwargs): ...\n\n self.app = app\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_no_credentials", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000126.py"} {"focal_file": "lib/oauth2client/contrib/gce.py", "focal_class": "oauth2client.contrib.gce.AppAssertionCredentials", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_oauth2client_contrib_gce_AppAssertionCredentials_to_json(unittest.TestCase):\n def test_to_json(self):\n credentials = gce.AppAssertionCredentials()\n with self.assertRaises(NotImplementedError):\n credentials.to_json()\n", "method_code": " def to_json(self):\n raise NotImplementedError('Cannot serialize credentials for GCE service accounts.')\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def to_json(self): ...\n def __init__(self, email=None, *args, **kwargs): ...\n def from_json(cls, json_data): ...\n def retrieve_scopes(self, http): ...\n def _retrieve_info(self, http): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def sign_blob(self, blob): ...\n\n self.service_account_email = email\n self.scopes = None\n self.invalid = True\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_to_json", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000127.py"} {"focal_file": "lib/oauth2client/contrib/gce.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n with self.assertRaises(NotImplementedError):\n gce.AppAssertionCredentials.from_json({})\n", "method_code": " def from_json(cls, json_data):\n raise NotImplementedError('Cannot serialize credentials for GCE service accounts.')\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n @classmethod\n def from_json(cls, json_data): ...\n def __init__(self, email=None, *args, **kwargs): ...\n def to_json(self): ...\n def retrieve_scopes(self, http): ...\n def _retrieve_info(self, http): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def sign_blob(self, blob): ...\n\n self.service_account_email = email\n self.scopes = None\n self.invalid = True\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_from_json", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000128.py"} {"focal_file": "lib/oauth2client/contrib/gce.py", "focal_class": "oauth2client.contrib.gce.AppAssertionCredentials", "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_oauth2client_contrib_gce_AppAssertionCredentials_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required(self):\n credentials = gce.AppAssertionCredentials()\n self.assertFalse(credentials.create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n return False\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def create_scoped_required(self): ...\n def __init__(self, email=None, *args, **kwargs): ...\n def from_json(cls, json_data): ...\n def to_json(self): ...\n def retrieve_scopes(self, http): ...\n def _retrieve_info(self, http): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def sign_blob(self, blob): ...\n\n self.service_account_email = email\n self.scopes = None\n self.invalid = True\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_scoped_required", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000129.py"} {"focal_file": "lib/oauth2client/contrib/gce.py", "focal_class": "oauth2client.contrib.gce.AppAssertionCredentials", "focal_method": "retrieve_scopes", "tests": "import unittest\n\nclass Test_oauth2client_contrib_gce_AppAssertionCredentials_retrieve_scopes(unittest.TestCase):\n @mock.patch('oauth2client.contrib._metadata.get_service_account_info', return_value=SERVICE_ACCOUNT_INFO)\n def test_retrieve_scopes(self, metadata):\n http_mock = object()\n credentials = gce.AppAssertionCredentials()\n self.assertTrue(credentials.invalid)\n self.assertIsNone(credentials.scopes)\n scopes = credentials.retrieve_scopes(http_mock)\n self.assertEqual(scopes, SERVICE_ACCOUNT_INFO['scopes'])\n self.assertFalse(credentials.invalid)\n credentials.retrieve_scopes(http_mock)\n metadata.assert_called_once_with(http_mock, service_account='default')\n\n @mock.patch('oauth2client.contrib._metadata.get_service_account_info', side_effect=http_client.HTTPException('No Such Email'))\n def test_retrieve_scopes_bad_email(self, metadata):\n http_mock = object()\n credentials = gce.AppAssertionCredentials(email='b@example.com')\n with self.assertRaises(http_client.HTTPException):\n credentials.retrieve_scopes(http_mock)\n metadata.assert_called_once_with(http_mock, service_account='b@example.com')\n", "method_code": " def retrieve_scopes(self, http):\n \"\"\"Retrieves the canonical list of scopes for this access token.\n \n Overrides client.Credentials.retrieve_scopes. Fetches scopes info\n from the metadata server.\n \n Args:\n http: httplib2.Http, an http object to be used to make the refresh\n request.\n \n Returns:\n A set of strings containing the canonical list of scopes.\n \"\"\"\n self._retrieve_info(http)\n return self.scopes\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def retrieve_scopes(self, http): ...\n def __init__(self, email=None, *args, **kwargs): ...\n def from_json(cls, json_data): ...\n def to_json(self): ...\n def _retrieve_info(self, http): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def sign_blob(self, blob): ...\n\n self.service_account_email = email\n self.scopes = None\n self.invalid = True\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000130.py"} {"focal_file": "lib/oauth2client/contrib/keyring_storage.py", "focal_class": "oauth2client.contrib.keyring_storage.Storage", "focal_method": "locked_get", "tests": "import unittest\n\nclass Test_oauth2client_contrib_keyring_storage_Storage_locked_get(unittest.TestCase):\n def test_locked_get(self):\n service_name = 'my_unit_test'\n user_name = 'me'\n mock_content = (object(), 'mock_content')\n mock_return_creds = mock.Mock()\n mock_return_creds.set_store = set_store = mock.Mock(name='set_store')\n with mock.patch.object(keyring, 'get_password', return_value=mock_content, autospec=True) as get_password:\n class_name = 'oauth2client.client.Credentials'\n with mock.patch(class_name) as MockCreds:\n MockCreds.new_from_json = new_from_json = mock.Mock(name='new_from_json', return_value=mock_return_creds)\n store = keyring_storage.Storage(service_name, user_name)\n credentials = store.locked_get()\n new_from_json.assert_called_once_with(mock_content)\n get_password.assert_called_once_with(service_name, user_name)\n self.assertEqual(credentials, mock_return_creds)\n set_store.assert_called_once_with(store)\n", "method_code": " def locked_get(self):\n \"\"\"Retrieve Credential from file.\n \n Returns:\n oauth2client.client.Credentials\n \"\"\"\n credentials = None\n content = keyring.get_password(self._service_name, self._user_name)\n if content is not None:\n try:\n credentials = client.Credentials.new_from_json(content)\n credentials.set_store(self)\n except ValueError:\n pass\n return credentials\n ", "context": "class Storage(client.Storage):\n def locked_get(self): ...\n def __init__(self, service_name, user_name): ...\n def locked_put(self, credentials): ...\n def locked_delete(self): ...\n\n self._service_name = service_name\n self._user_name = user_name\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_locked_get", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000131.py"} {"focal_file": "lib/oauth2client/contrib/keyring_storage.py", "focal_class": "oauth2client.contrib.keyring_storage.Storage", "focal_method": "locked_put", "tests": "import unittest\n\nclass Test_oauth2client_contrib_keyring_storage_Storage_locked_put(unittest.TestCase):\n def test_locked_put(self):\n service_name = 'my_unit_test'\n user_name = 'me'\n store = keyring_storage.Storage(service_name, user_name)\n with mock.patch.object(keyring, 'set_password', return_value=None, autospec=True) as set_password:\n credentials = mock.Mock()\n to_json_ret = object()\n credentials.to_json = to_json = mock.Mock(name='to_json', return_value=to_json_ret)\n store.locked_put(credentials)\n to_json.assert_called_once_with()\n set_password.assert_called_once_with(service_name, user_name, to_json_ret)\n", "method_code": " def locked_put(self, credentials):\n \"\"\"Write Credentials to file.\n \n Args:\n credentials: Credentials, the credentials to store.\n \"\"\"\n keyring.set_password(self._service_name, self._user_name, credentials.to_json())\n ", "context": "class Storage(client.Storage):\n def locked_put(self, credentials): ...\n def __init__(self, service_name, user_name): ...\n def locked_get(self): ...\n def locked_delete(self): ...\n\n self._service_name = service_name\n self._user_name = user_name\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_locked_put", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000132.py"} {"focal_file": "lib/oauth2client/contrib/keyring_storage.py", "focal_class": "oauth2client.contrib.keyring_storage.Storage", "focal_method": "locked_delete", "tests": "import unittest\n\nclass Test_oauth2client_contrib_keyring_storage_Storage_locked_delete(unittest.TestCase):\n def test_locked_delete(self):\n service_name = 'my_unit_test'\n user_name = 'me'\n store = keyring_storage.Storage(service_name, user_name)\n with mock.patch.object(keyring, 'set_password', return_value=None, autospec=True) as set_password:\n store.locked_delete()\n set_password.assert_called_once_with(service_name, user_name, '')\n", "method_code": " def locked_delete(self):\n \"\"\"Delete Credentials file.\n \n Args:\n credentials: Credentials, the credentials to store.\n \"\"\"\n keyring.set_password(self._service_name, self._user_name, '')\n ", "context": "class Storage(client.Storage):\n def locked_delete(self): ...\n def __init__(self, service_name, user_name): ...\n def locked_get(self): ...\n def locked_put(self, credentials): ...\n\n self._service_name = service_name\n self._user_name = user_name\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_locked_delete", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000133.py"} {"focal_file": "lib/oauth2client/contrib/_metadata.py", "focal_class": null, "focal_method": "get_service_account_info", "tests": "import unittest\n\nclass Test_get_service_account_info(unittest.TestCase):\n def test_service_account_info(self):\n http = request_mock(http_client.OK, 'application/json', json.dumps(DATA))\n info = _metadata.get_service_account_info(http)\n self.assertEqual(info, DATA)\n self.assertEqual(http.requests, 1)\n self.assertEqual(http.uri, EXPECTED_URL + '/?recursive=True')\n self.assertEqual(http.method, 'GET')\n self.assertIsNone(http.body)\n self.assertEqual(http.headers, _metadata.METADATA_HEADERS)\n", "method_code": "def get_service_account_info(http, service_account='default'):\n \"\"\"Get information about a service account from the metadata server.\n\n Args:\n http: an object to be used to make HTTP requests.\n service_account: An email specifying the service account for which to\n look up information. Default will be information for the \"default\"\n service account of the current compute engine instance.\n\n Returns:\n A dictionary with information about the specified service account,\n for example:\n\n {\n 'email': '...',\n 'scopes': ['scope', ...],\n 'aliases': ['default', '...']\n }\n \"\"\"\n return get(http, 'instance/service-accounts/{0}/'.format(service_account), recursive=True)", "context": "def get_service_account_info(http, service_account='default'): ...\ndef get(http, path, root=METADATA_ROOT, recursive=None): ...\ndef get_service_account_info(http, service_account='default'): ...\ndef get_token(http, service_account='default'): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_service_account_info", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000134.py"} {"focal_file": "lib/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_create_file_if_needed", "tests": "import unittest\n\nclass Test_create_file_if_needed(unittest.TestCase):\n def test__create_file_if_needed(self):\n self.assertFalse(multiprocess_file_storage._create_file_if_needed(self.filename))\n os.unlink(self.filename)\n self.assertTrue(multiprocess_file_storage._create_file_if_needed(self.filename))\n self.assertTrue(os.path.exists(self.filename))\n", "method_code": "def _create_file_if_needed(filename):\n \"\"\"Creates the an empty file if it does not already exist.\n\n Returns:\n True if the file was created, False otherwise.\n \"\"\"\n if os.path.exists(filename):\n return False\n else:\n open(filename, 'a+b').close()\n logger.info('Credential file {0} created'.format(filename))\n return True", "context": "def _create_file_if_needed(filename): ...\ndef _create_file_if_needed(filename): ...\ndef _load_credentials_file(credentials_file): ...\ndef _write_credentials_file(credentials_file, credentials): ...\ndef _get_backend(filename): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__create_file_if_needed", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000135.py"} {"focal_file": "lib/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_get_backend", "tests": "import unittest\n\nclass Test_get_backend(unittest.TestCase):\n def test__get_backend(self):\n backend_one = multiprocess_file_storage._get_backend('file_a')\n backend_two = multiprocess_file_storage._get_backend('file_a')\n backend_three = multiprocess_file_storage._get_backend('file_b')\n self.assertIs(backend_one, backend_two)\n self.assertIsNot(backend_one, backend_three)\n", "method_code": "def _get_backend(filename):\n \"\"\"A helper method to get or create a backend with thread locking.\n\n This ensures that only one backend is used per-file per-process, so that\n thread and process locks are appropriately shared.\n\n Args:\n filename: The full path to the credential storage file.\n\n Returns:\n An instance of :class:`_MultiprocessStorageBackend`.\n \"\"\"\n filename = os.path.abspath(filename)\n with _backends_lock:\n if filename not in _backends:\n _backends[filename] = _MultiprocessStorageBackend(filename)\n return _backends[filename]", "context": "def _get_backend(filename): ...\ndef _create_file_if_needed(filename): ...\ndef _load_credentials_file(credentials_file): ...\ndef _write_credentials_file(credentials_file, credentials): ...\ndef _get_backend(filename): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__get_backend", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000136.py"} {"focal_file": "lib/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_write_credentials_file", "tests": "import unittest\n\nclass Test_write_credentials_file(unittest.TestCase):\n def test__read_write_credentials_file(self):\n credentials = _create_test_credentials()\n contents = six.StringIO()\n multiprocess_file_storage._write_credentials_file(contents, {'key': credentials})\n contents.seek(0)\n data = json.load(contents)\n self.assertEqual(data['file_version'], 2)\n self.assertTrue(data['credentials']['key'])\n contents.seek(0)\n results = multiprocess_file_storage._load_credentials_file(contents)\n self.assertEqual(results['key'].access_token, credentials.access_token)\n data['credentials']['invalid'] = '123'\n results = multiprocess_file_storage._load_credentials_file(six.StringIO(json.dumps(data)))\n self.assertNotIn('invalid', results)\n self.assertEqual(results['key'].access_token, credentials.access_token)\n", "method_code": "def _write_credentials_file(credentials_file, credentials):\n \"\"\"Writes credentials to a file.\n\n Refer to :func:`_load_credentials_file` for the format.\n\n Args:\n credentials_file: An open file handle, must be read/write.\n credentials: A dictionary mapping user-defined keys to an instance of\n :class:`oauth2client.client.Credentials`.\n \"\"\"\n data = {'file_version': 2, 'credentials': {}}\n for key, credential in iteritems(credentials):\n credential_json = credential.to_json()\n encoded_credential = _helpers._from_bytes(base64.b64encode(_helpers._to_bytes(credential_json)))\n data['credentials'][key] = encoded_credential\n credentials_file.seek(0)\n json.dump(data, credentials_file)\n credentials_file.truncate()", "context": "def _write_credentials_file(credentials_file, credentials): ...\ndef _create_file_if_needed(filename): ...\ndef _load_credentials_file(credentials_file): ...\ndef _write_credentials_file(credentials_file, credentials): ...\ndef _get_backend(filename): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__read_write_credentials_file", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000137.py"} {"focal_file": "lib/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_load_credentials", "tests": "import unittest\n\nclass Test_load_credentials(unittest.TestCase):\n def test__load_credentials_no_open_file(self):\n backend = multiprocess_file_storage._get_backend(self.filename)\n backend._credentials = mock.Mock()\n backend._credentials.update.side_effect = AssertionError()\n backend._load_credentials()\n", "method_code": " def _load_credentials(self):\n \"\"\"(Re-)loads the credentials from the file.\"\"\"\n if not self._file:\n return\n loaded_credentials = _load_credentials_file(self._file)\n self._credentials.update(loaded_credentials)\n logger.debug('Read credential file')\n ", "context": "class _MultiprocessStorageBackend(object):\n def _load_credentials(self): ...\n def __init__(self, filename): ...\n def _write_credentials(self): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def _refresh_predicate(self, credentials): ...\n def locked_get(self, key): ...\n def locked_put(self, key, credentials): ...\n def locked_delete(self, key): ...\n\n self._file = None\n self._filename = filename\n self._process_lock = fasteners.InterProcessLock('{0}.lock'.format(filename))\n self._thread_lock = threading.Lock()\n self._read_only = False\n self._credentials = {}\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__load_credentials_no_open_file", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000138.py"} {"focal_file": "lib/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "release_lock", "tests": "import unittest\n\nclass Test_release_lock(unittest.TestCase):\n def test_release_lock_with_no_file(self):\n backend = multiprocess_file_storage._get_backend(self.filename)\n backend._file = None\n backend._read_only = True\n backend._thread_lock.acquire()\n backend.release_lock()\n", "method_code": " def release_lock(self):\n if self._file is not None:\n self._file.close()\n self._file = None\n if not self._read_only:\n self._process_lock.release()\n self._thread_lock.release()\n ", "context": "class _MultiprocessStorageBackend(object):\n def release_lock(self): ...\n def __init__(self, filename): ...\n def _load_credentials(self): ...\n def _write_credentials(self): ...\n def acquire_lock(self): ...\n def _refresh_predicate(self, credentials): ...\n def locked_get(self, key): ...\n def locked_put(self, key, credentials): ...\n def locked_delete(self, key): ...\n\n self._file = None\n self._filename = filename\n self._process_lock = fasteners.InterProcessLock('{0}.lock'.format(filename))\n self._thread_lock = threading.Lock()\n self._read_only = False\n self._credentials = {}\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_release_lock_with_no_file", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000139.py"} {"focal_file": "lib/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_refresh_predicate", "tests": "import unittest\n\nclass Test_refresh_predicate(unittest.TestCase):\n def test__refresh_predicate(self):\n backend = multiprocess_file_storage._get_backend(self.filename)\n credentials = _create_test_credentials()\n self.assertFalse(backend._refresh_predicate(credentials))\n credentials.invalid = True\n self.assertTrue(backend._refresh_predicate(credentials))\n credentials = _create_test_credentials(expiration=datetime.datetime.utcnow() - datetime.timedelta(seconds=3600))\n self.assertTrue(backend._refresh_predicate(credentials))\n", "method_code": " def _refresh_predicate(self, credentials):\n if credentials is None:\n return True\n elif credentials.invalid:\n return True\n elif credentials.access_token_expired:\n return True\n else:\n return False\n ", "context": "class _MultiprocessStorageBackend(object):\n def _refresh_predicate(self, credentials): ...\n def __init__(self, filename): ...\n def _load_credentials(self): ...\n def _write_credentials(self): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def locked_get(self, key): ...\n def locked_put(self, key, credentials): ...\n def locked_delete(self, key): ...\n\n self._file = None\n self._filename = filename\n self._process_lock = fasteners.InterProcessLock('{0}.lock'.format(filename))\n self._thread_lock = threading.Lock()\n self._read_only = False\n self._credentials = {}\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__refresh_predicate", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000140.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.AppAssertionCredentials", "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_AppAssertionCredentials_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required_without_scopes(self):\n credentials = appengine.AppAssertionCredentials([])\n self.assertTrue(credentials.create_scoped_required())\n\n def test_create_scoped_required_with_scopes(self):\n credentials = appengine.AppAssertionCredentials(['dummy_scope'])\n self.assertFalse(credentials.create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n return not self.scope\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def create_scoped_required(self): ...\n def __init__(self, scope, **kwargs): ...\n def from_json(cls, json_data): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped(self, scopes): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n\n self.scope = _helpers.scopes_to_string(scope)\n self._kwargs = kwargs\n self.service_account_id = kwargs.get('service_account_id', None)\n self._service_account_email = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_scoped_required_without_scopes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000141.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.AppAssertionCredentials", "focal_method": "create_scoped", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_AppAssertionCredentials_create_scoped(unittest.TestCase):\n def test_create_scoped(self):\n credentials = appengine.AppAssertionCredentials([])\n new_credentials = credentials.create_scoped(['dummy_scope'])\n self.assertNotEqual(credentials, new_credentials)\n self.assertIsInstance(new_credentials, appengine.AppAssertionCredentials)\n self.assertEqual('dummy_scope', new_credentials.scope)\n", "method_code": " def create_scoped(self, scopes):\n return AppAssertionCredentials(scopes, **self._kwargs)\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def create_scoped(self, scopes): ...\n def __init__(self, scope, **kwargs): ...\n def from_json(cls, json_data): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n\n self.scope = _helpers.scopes_to_string(scope)\n self._kwargs = kwargs\n self.service_account_id = kwargs.get('service_account_id', None)\n self._service_account_email = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_create_scoped", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000142.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.AppAssertionCredentials", "focal_method": "sign_blob", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_AppAssertionCredentials_sign_blob(unittest.TestCase):\n def test_sign_blob(self):\n key_name = b'1234567890'\n sig_bytes = b'himom'\n app_identity_stub = self.AppIdentityStubImpl(key_name=key_name, sig_bytes=sig_bytes)\n apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()\n apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', app_identity_stub)\n credentials = appengine.AppAssertionCredentials([])\n to_sign = b'blob'\n self.assertEqual(app_identity_stub._sign_calls, [])\n result = credentials.sign_blob(to_sign)\n self.assertEqual(result, (key_name, sig_bytes))\n self.assertEqual(app_identity_stub._sign_calls, [to_sign])\n", "method_code": " def sign_blob(self, blob):\n \"\"\"Cryptographically sign a blob (of bytes).\n \n Implements abstract method\n :meth:`oauth2client.client.AssertionCredentials.sign_blob`.\n \n Args:\n blob: bytes, Message to be signed.\n \n Returns:\n tuple, A pair of the private key ID used to sign the blob and\n the signed contents.\n \"\"\"\n return app_identity.sign_blob(blob)\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def sign_blob(self, blob): ...\n def __init__(self, scope, **kwargs): ...\n def from_json(cls, json_data): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def service_account_email(self): ...\n\n self.scope = _helpers.scopes_to_string(scope)\n self._kwargs = kwargs\n self.service_account_id = kwargs.get('service_account_id', None)\n self._service_account_email = None\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_sign_blob", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000143.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.FlowProperty", "focal_method": "make_value_from_datastore", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_FlowProperty_make_value_from_datastore(unittest.TestCase):\n def test_make_value_from_datastore_none(self):\n self.assertIsNone(appengine.FlowProperty().make_value_from_datastore(None))\n", "method_code": " def make_value_from_datastore(self, value):\n if value is None:\n return None\n return pickle.loads(value)\n ", "context": "class FlowProperty(db.Property):\n def make_value_from_datastore(self, value): ...\n def get_value_for_datastore(self, model_instance): ...\n def validate(self, value): ...\n def empty(self, value): ...\n\n data_type = client.Flow\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_make_value_from_datastore_none", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000144.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.CredentialsProperty", "focal_method": "validate", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_CredentialsProperty_validate(unittest.TestCase):\n def test_validate(self):\n appengine.CredentialsProperty().validate(self.credentials)\n appengine.CredentialsProperty().validate(None)\n with self.assertRaises(db.BadValueError):\n appengine.CredentialsProperty().validate(42)\n", "method_code": " def validate(self, value):\n if value is not None and (not isinstance(value, client.Flow)):\n raise db.BadValueError('Property {0} must be convertible to a FlowThreeLegged instance ({1})'.format(self.name, value))\n return super(FlowProperty, self).validate(value)\n ", "context": "class FlowProperty(db.Property):\n def validate(self, value): ...\n def get_value_for_datastore(self, model_instance): ...\n def make_value_from_datastore(self, value): ...\n def empty(self, value): ...\n\n data_type = client.Flow\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_validate", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000145.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.CredentialsProperty", "focal_method": "make_value_from_datastore", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_CredentialsProperty_make_value_from_datastore(unittest.TestCase):\n def test_make_value_from_datastore(self):\n self.assertIsNone(appengine.CredentialsProperty().make_value_from_datastore(None))\n self.assertIsNone(appengine.CredentialsProperty().make_value_from_datastore(''))\n self.assertIsNone(appengine.CredentialsProperty().make_value_from_datastore('{'))\n decoded = appengine.CredentialsProperty().make_value_from_datastore(self.credentials.to_json())\n self.assertEqual(self.credentials.to_json(), decoded.to_json())\n", "method_code": " def make_value_from_datastore(self, value):\n if value is None:\n return None\n return pickle.loads(value)\n ", "context": "class FlowProperty(db.Property):\n def make_value_from_datastore(self, value): ...\n def get_value_for_datastore(self, model_instance): ...\n def validate(self, value): ...\n def empty(self, value): ...\n\n data_type = client.Flow\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_make_value_from_datastore", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000146.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.StorageByKeyName", "focal_method": "_is_ndb", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_StorageByKeyName_is_ndb(unittest.TestCase):\n def test__is_ndb(self):\n storage = appengine.StorageByKeyName(object(), 'foo', 'credentials')\n with self.assertRaises(TypeError):\n storage._is_ndb()\n storage._model = type(object)\n with self.assertRaises(TypeError):\n storage._is_ndb()\n storage._model = appengine.CredentialsModel\n self.assertFalse(storage._is_ndb())\n storage._model = appengine.CredentialsNDBModel\n self.assertTrue(storage._is_ndb())\n", "method_code": " def _is_ndb(self):\n \"\"\"Determine whether the model of the instance is an NDB model.\n \n Returns:\n Boolean indicating whether or not the model is an NDB or DB model.\n \"\"\"\n if isinstance(self._model, type):\n if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL):\n return True\n elif issubclass(self._model, db.Model):\n return False\n raise TypeError('Model class not an NDB or DB model: {0}.'.format(self._model))\n ", "context": "class StorageByKeyName(client.Storage):\n def _is_ndb(self): ...\n def __init__(self, model, key_name, property_name, cache=None, user=None): ...\n def _get_entity(self): ...\n def _delete_entity(self): ...\n def locked_get(self): ...\n def locked_put(self, credentials): ...\n def locked_delete(self): ...\n\n self._model = model\n self._key_name = key_name\n self._property_name = property_name\n self._cache = cache\n", "repository": "designspired/TaskManagerGAE", "test_name": "test__is_ndb", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000147.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.StorageByKeyName", "focal_method": "get", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_StorageByKeyName_get(unittest.TestCase):\n def test_get_and_put_mixed_ndb_storage_db_get(self):\n storage = appengine.StorageByKeyName(appengine.CredentialsNDBModel, 'foo', 'credentials')\n self.assertEqual(None, storage.get())\n self.credentials.set_store(storage)\n http = http_mock.HttpMock(data=BASIC_RESP)\n self.credentials._refresh(http)\n credmodel = appengine.CredentialsModel.get_by_key_name('foo')\n self.assertEqual(BASIC_TOKEN, credmodel.credentials.access_token)\n self.assertEqual(self.credentials.to_json(), credmodel.credentials.to_json())\n self._verify_basic_refresh(http)\n\n def test_get_and_put_mixed_db_storage_ndb_get(self):\n storage = appengine.StorageByKeyName(appengine.CredentialsModel, 'foo', 'credentials')\n self.assertEqual(None, storage.get())\n self.credentials.set_store(storage)\n http = http_mock.HttpMock(data=BASIC_RESP)\n self.credentials._refresh(http)\n credmodel = appengine.CredentialsNDBModel.get_by_id('foo')\n self.assertEqual(BASIC_TOKEN, credmodel.credentials.access_token)\n self.assertEqual(self.credentials.to_json(), credmodel.credentials.to_json())\n self._verify_basic_refresh(http)\n", "method_code": " def get(self):\n error = self.request.get('error')\n if error:\n errormsg = self.request.get('error_description', error)\n self.response.out.write('The authorization request failed: {0}'.format(_safe_html(errormsg)))\n else:\n user = users.get_current_user()\n decorator._create_flow(self)\n credentials = decorator.flow.step2_exchange(self.request.params)\n decorator._storage_class(decorator._credentials_class, None, decorator._credentials_property_name, user=user).put(credentials)\n redirect_uri = _parse_state_value(str(self.request.get('state')), user)\n if redirect_uri is None:\n self.response.out.write('The authorization request failed')\n return\n if decorator._token_response_param and credentials.token_response:\n resp_json = json.dumps(credentials.token_response)\n redirect_uri = _helpers._add_query_parameter(redirect_uri, decorator._token_response_param, resp_json)\n self.redirect(redirect_uri)\n ", "context": "class OAuth2Handler(webapp.RequestHandler):\n @login_required\n def get(self): ...", "repository": "designspired/TaskManagerGAE", "test_name": "test_get_and_put_mixed_ndb_storage_db_get", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000148.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": null, "focal_method": "callback_application", "tests": "import unittest\n\nclass Test_callback_application(unittest.TestCase):\n def test_callback_application(self):\n app = self.decorator.callback_application()\n self.assertEqual(app.router.match_routes[0].handler.__name__, 'OAuth2Handler')\n", "method_code": " def callback_application(self):\n \"\"\"WSGI application for handling the OAuth 2.0 redirect callback.\n \n If you need finer grained control use `callback_handler` which returns\n just the webapp.RequestHandler.\n \n Returns:\n A webapp.WSGIApplication that handles the redirect back from the\n server during the OAuth 2.0 dance.\n \"\"\"\n return webapp.WSGIApplication([(self.callback_path, self.callback_handler())])\n ", "context": "class OAuth2Decorator(object):\n def callback_application(self): ...\n def set_credentials(self, credentials): ...\n def get_credentials(self): ...\n def set_flow(self, flow): ...\n def get_flow(self): ...\n def __init__(self, client_id, client_secret, scope, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, user_agent=None, message=None, callback_path='/oauth2callback', token_response_param=None, _storage_class=StorageByKeyName, _credentials_class=CredentialsModel, _credentials_property_name='credentials', **kwargs): ...\n def _display_error_message(self, request_handler): ...\n def oauth_required(self, method): ...\n def _create_flow(self, request_handler): ...\n def oauth_aware(self, method): ...\n def has_credentials(self): ...\n def authorize_url(self): ...\n def http(self, *args, **kwargs): ...\n def callback_path(self): ...\n def callback_handler(self): ...\n\n self._tls = threading.local()\n self.flow = None\n self.credentials = None\n self._client_id = client_id\n self._client_secret = client_secret\n self._scope = _helpers.scopes_to_string(scope)\n self._auth_uri = auth_uri\n self._token_uri = token_uri\n self._revoke_uri = revoke_uri\n self._user_agent = user_agent\n self._kwargs = kwargs\n self._message = message\n self._in_error = False\n self._callback_path = callback_path\n self._token_response_param = token_response_param\n self._storage_class = _storage_class\n self._credentials_class = _credentials_class\n self._credentials_property_name = _credentials_property_name\n\n credentials = property(get_credentials, set_credentials)\n flow = property(get_flow, set_flow)\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_callback_application", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000149.py"} {"focal_file": "lib/oauth2client/contrib/appengine.py", "focal_class": null, "focal_method": "oauth2decorator_from_clientsecrets", "tests": "import unittest\n\nclass Test_oauth2decorator_from_clientsecrets(unittest.TestCase):\n def test_decorator_from_client_secrets_toplevel(self):\n decorator_patch = mock.patch('oauth2client.contrib.appengine.OAuth2DecoratorFromClientSecrets')\n with decorator_patch as decorator_mock:\n filename = datafile('client_secrets.json')\n appengine.oauth2decorator_from_clientsecrets(filename, scope='foo_scope')\n decorator_mock.assert_called_once_with(filename, 'foo_scope', cache=None, message=None)\n", "method_code": "def oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None):\n \"\"\"Creates an OAuth2Decorator populated from a clientsecrets file.\n\n Args:\n filename: string, File name of client secrets.\n scope: string or list of strings, scope(s) of the credentials being\n requested.\n message: string, A friendly string to display to the user if the\n clientsecrets file is missing or invalid. The message may\n contain HTML and will be presented on the web interface for\n any method that uses the decorator.\n cache: An optional cache service client that implements get() and set()\n methods. See clientsecrets.loadfile() for details.\n\n Returns: An OAuth2Decorator\n \"\"\"\n return OAuth2DecoratorFromClientSecrets(filename, scope, message=message, cache=cache)", "context": "@_helpers.positional(2)\ndef oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None): ...\ndef _safe_html(s): ...\ndef _generate_new_xsrf_secret_key(): ...\ndef xsrf_secret_key(): ...\ndef _build_state_value(request_handler, user): ...\ndef _parse_state_value(state, user): ...\ndef oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_decorator_from_client_secrets_toplevel", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000150.py"} {"focal_file": "lib/oauth2client/contrib/django_util/models.py", "focal_class": null, "focal_method": "from_db_value", "tests": "import unittest\n\nclass Test_from_db_value(unittest.TestCase):\n def test_from_db_value(self):\n value = self.field.from_db_value(self.pickle_str, None, None, None)\n self.assertIsInstance(value, client.Credentials)\n", "method_code": " def from_db_value(self, value, expression, connection, context):\n \"\"\"Overrides ``models.Field`` method. This converts the value\n returned from the database to an instance of this class.\n \"\"\"\n return self.to_python(value)\n ", "context": "class CredentialsField(models.Field):\n def from_db_value(self, value, expression, connection, context): ...\n def __init__(self, *args, **kwargs): ...\n def get_internal_type(self): ...\n def to_python(self, value): ...\n def get_prep_value(self, value): ...\n def value_to_string(self, obj): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_from_db_value", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000151.py"} {"focal_file": "lib/oauth2client/contrib/django_util/models.py", "focal_class": null, "focal_method": "value_to_string", "tests": "import unittest\n\nclass Test_value_to_string(unittest.TestCase):\n def test_field_value_to_string(self):\n self.fake_model.credentials = self.credentials\n value_str = self.fake_model_field.value_to_string(self.fake_model)\n self.assertEqual(value_str, self.pickle_str)\n\n def test_field_value_to_string_none(self):\n self.fake_model.credentials = None\n value_str = self.fake_model_field.value_to_string(self.fake_model)\n self.assertIsNone(value_str)\n", "method_code": " def value_to_string(self, obj):\n \"\"\"Convert the field value from the provided model to a string.\n \n Used during model serialization.\n \n Args:\n obj: db.Model, model object\n \n Returns:\n string, the serialized field value\n \"\"\"\n value = self._get_val_from_obj(obj)\n return self.get_prep_value(value)\n ", "context": "class CredentialsField(models.Field):\n def value_to_string(self, obj): ...\n def __init__(self, *args, **kwargs): ...\n def get_internal_type(self): ...\n def from_db_value(self, value, expression, connection, context): ...\n def to_python(self, value): ...\n def get_prep_value(self, value): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_field_value_to_string", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000152.py"} {"focal_file": "lib/oauth2client/contrib/django_util/storage.py", "focal_class": null, "focal_method": "locked_get", "tests": "import unittest\n\nclass Test_locked_get(unittest.TestCase):\n @mock.patch('django.db.models')\n def test_locked_get(self, djangoModel):\n fake_model_with_credentials = FakeCredentialsModelMock()\n entities = [fake_model_with_credentials]\n filter_mock = mock.Mock(return_value=entities)\n object_mock = mock.Mock()\n object_mock.filter = filter_mock\n FakeCredentialsModelMock.objects = object_mock\n storage = Storage(FakeCredentialsModelMock, self.key_name, self.key_value, self.property_name)\n credential = storage.locked_get()\n self.assertEqual(credential, fake_model_with_credentials.credentials)\n\n @mock.patch('django.db.models')\n def test_locked_get_no_entities(self, djangoModel):\n entities = []\n filter_mock = mock.Mock(return_value=entities)\n object_mock = mock.Mock()\n object_mock.filter = filter_mock\n FakeCredentialsModelMock.objects = object_mock\n storage = Storage(FakeCredentialsModelMock, self.key_name, self.key_value, self.property_name)\n credential = storage.locked_get()\n self.assertIsNone(credential)\n\n @mock.patch('django.db.models')\n def test_locked_get_no_set_store(self, djangoModel):\n fake_model_with_credentials = FakeCredentialsModelMockNoSet()\n entities = [fake_model_with_credentials]\n filter_mock = mock.Mock(return_value=entities)\n object_mock = mock.Mock()\n object_mock.filter = filter_mock\n FakeCredentialsModelMockNoSet.objects = object_mock\n storage = Storage(FakeCredentialsModelMockNoSet, self.key_name, self.key_value, self.property_name)\n credential = storage.locked_get()\n self.assertEqual(credential, fake_model_with_credentials.credentials)\n", "method_code": " def locked_get(self):\n \"\"\"Retrieve stored credential from the Django ORM.\n \n Returns:\n oauth2client.Credentials retrieved from the Django ORM, associated\n with the ``model``, ``key_value``->``key_name`` pair used to query\n for the model, and ``property_name`` identifying the\n ``CredentialsProperty`` field, all of which are defined in the\n constructor for this Storage object.\n \n \"\"\"\n query = {self.key_name: self.key_value}\n entities = self.model_class.objects.filter(**query)\n if len(entities) > 0:\n credential = getattr(entities[0], self.property_name)\n if getattr(credential, 'set_store', None) is not None:\n credential.set_store(self)\n return credential\n else:\n return None\n ", "context": "class DjangoORMStorage(client.Storage):\n def locked_get(self): ...\n def __init__(self, model_class, key_name, key_value, property_name): ...\n def locked_put(self, credentials): ...\n def locked_delete(self): ...\n\n self.model_class = model_class\n self.key_name = key_name\n self.key_value = key_value\n self.property_name = property_name\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000153.py"} {"focal_file": "lib/oauth2client/contrib/django_util/storage.py", "focal_class": null, "focal_method": "locked_put", "tests": "import unittest\n\nclass Test_locked_put(unittest.TestCase):\n @mock.patch('django.db.models')\n def test_locked_put(self, djangoModel):\n entity_mock = mock.Mock(credentials=None)\n objects = mock.Mock(get_or_create=mock.Mock(return_value=(entity_mock, None)))\n FakeCredentialsModelMock.objects = objects\n storage = Storage(FakeCredentialsModelMock, self.key_name, self.key_value, self.property_name)\n storage.locked_put(self.credentials)\n", "method_code": " def locked_put(self, credentials):\n \"\"\"Write a Credentials to the Django datastore.\n \n Args:\n credentials: Credentials, the credentials to store.\n \"\"\"\n entity, _ = self.model_class.objects.get_or_create(**{self.key_name: self.key_value})\n setattr(entity, self.property_name, credentials)\n entity.save()\n ", "context": "class DjangoORMStorage(client.Storage):\n def locked_put(self, credentials): ...\n def __init__(self, model_class, key_name, key_value, property_name): ...\n def locked_get(self): ...\n def locked_delete(self): ...\n\n self.model_class = model_class\n self.key_name = key_name\n self.key_value = key_value\n self.property_name = property_name\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000154.py"} {"focal_file": "lib/oauth2client/contrib/django_util/storage.py", "focal_class": null, "focal_method": "locked_delete", "tests": "import unittest\n\nclass Test_locked_delete(unittest.TestCase):\n @mock.patch('django.db.models')\n def test_locked_delete(self, djangoModel):\n\n class FakeEntities(object):\n\n def __init__(self):\n self.deleted = False\n\n def delete(self):\n self.deleted = True\n fake_entities = FakeEntities()\n entities = fake_entities\n filter_mock = mock.Mock(return_value=entities)\n object_mock = mock.Mock()\n object_mock.filter = filter_mock\n FakeCredentialsModelMock.objects = object_mock\n storage = Storage(FakeCredentialsModelMock, self.key_name, self.key_value, self.property_name)\n storage.locked_delete()\n self.assertTrue(fake_entities.deleted)\n", "method_code": " def locked_delete(self):\n \"\"\"Delete Credentials from the datastore.\"\"\"\n query = {self.key_name: self.key_value}\n self.model_class.objects.filter(**query).delete()\n ", "context": "class DjangoORMStorage(client.Storage):\n def locked_delete(self): ...\n def __init__(self, model_class, key_name, key_value, property_name): ...\n def locked_get(self): ...\n def locked_put(self, credentials): ...\n\n self.model_class = model_class\n self.key_name = key_name\n self.key_value = key_value\n self.property_name = property_name\n", "repository": "designspired/TaskManagerGAE", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000155.py"} {"focal_file": "lib/zope/interface/declarations.py", "focal_class": null, "focal_method": "flattened", "tests": "import unittest\n\nclass Test_flattened(unittest.TestCase):\n def test_flattened_empty(self):\n from zope.interface.interface import Interface\n decl = self._makeOne()\n self.assertEqual(list(decl.flattened()), [Interface])\n", "method_code": " def flattened(self):\n \"\"\"Return an iterator of all included and extended interfaces\n \"\"\"\n return iter(self.__iro__)\n ", "context": "class Declaration(Specification):\n def flattened(self): ...\n def __init__(self, *interfaces): ...\n def changed(self, originally_changed): ...\n def __contains__(self, interface): ...\n def __iter__(self): ...\n def __sub__(self, other): ...\n def __add__(self, other): ...\n\n __radd__ = __add__\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_flattened_empty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000156.py"} {"focal_file": "lib/zope/interface/declarations.py", "focal_class": "implementer", "focal_method": "__reduce__", "tests": "import unittest\n\nclass Test_implementer_reduce(unittest.TestCase):\n def test___reduce__(self):\n from zope.interface.declarations import implementer\n from zope.interface.interface import InterfaceClass\n IFoo = InterfaceClass('IFoo')\n IBar = InterfaceClass('IBar')\n\n @implementer(IFoo)\n class Foo(object):\n pass\n cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar)\n self.assertEqual(cp.__reduce__(), (self._getTargetClass(), (Foo, type(Foo), IBar)))\n", "method_code": " def __reduce__(self):\n return (implementedBy, (self.inherit,))\n ", "context": "class Implements(Declaration):\n def __reduce__(self): ...\n def named(cls, name, *interfaces): ...\n def __repr__(self): ...\n def __cmp(self, other): ...\n def __hash__(self): ...\n def __lt__(self, other): ...\n def __le__(self, other): ...\n def __gt__(self, other): ...\n def __ge__(self, other): ...\n\n inherit = None\n declared = ()\n __name__ = '?'\n", "repository": "designspired/TaskManagerGAE", "test_name": "test___reduce__", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000157.py"} {"focal_file": "lib/zope/interface/declarations.py", "focal_class": "implementer", "focal_method": "classImplements", "tests": "import unittest\n\nclass Test_implementer_classImplements(unittest.TestCase):\n def test_classImplements(self):\n\n @implementer(I3)\n class A(Odd):\n pass\n\n @implementer(I4)\n class B(Odd):\n pass\n\n class C(A, B):\n pass\n classImplements(C, I1, I2)\n self.assertEqual([i.getName() for i in implementedBy(C)], ['I1', 'I2', 'I3', 'I4'])\n classImplements(C, I5)\n self.assertEqual([i.getName() for i in implementedBy(C)], ['I1', 'I2', 'I5', 'I3', 'I4'])\n", "method_code": "def classImplements(cls, *interfaces):\n \"\"\"Declare additional interfaces implemented for instances of a class\n\n The arguments after the class are one or more interfaces or\n interface specifications (``IDeclaration`` objects).\n\n The interfaces given (including the interfaces in the specifications)\n are added to any interfaces previously declared.\n \"\"\"\n spec = implementedBy(cls)\n spec.declared += tuple(_normalizeargs(interfaces))\n bases = []\n seen = {}\n for b in spec.declared:\n if b not in seen:\n seen[b] = 1\n bases.append(b)\n if spec.inherit is not None:\n for c in spec.inherit.__bases__:\n b = implementedBy(c)\n if b not in seen:\n seen[b] = 1\n bases.append(b)\n spec.__bases__ = tuple(bases)", "context": "def classImplements(cls, *interfaces): ...\ndef _implements_name(ob): ...\ndef implementedByFallback(cls): ...\ndef classImplementsOnly(cls, *interfaces): ...\ndef classImplements(cls, *interfaces): ...\ndef _implements_advice(cls): ...\ndef _implements(name, interfaces, classImplements): ...\ndef implements(*interfaces): ...\ndef implementsOnly(*interfaces): ...\ndef Provides(*interfaces): ...\ndef directlyProvides(object, *interfaces): ...\ndef alsoProvides(object, *interfaces): ...\ndef noLongerProvides(object, interface): ...\ndef directlyProvidedBy(object): ...\ndef classProvides(*interfaces): ...\ndef _classProvides_advice(cls): ...\ndef moduleProvides(*interfaces): ...\ndef ObjectSpecification(direct, cls): ...\ndef getObjectSpecificationFallback(ob): ...\ndef providedByFallback(ob): ...\ndef _normalizeargs(sequence, output=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_classImplements", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000158.py"} {"focal_file": "lib/zope/interface/declarations.py", "focal_class": "implementer", "focal_method": "classImplementsOnly", "tests": "import unittest\n\nclass Test_implementer_classImplementsOnly(unittest.TestCase):\n def test_classImplementsOnly(self):\n\n @implementer(I3)\n class A(Odd):\n pass\n\n @implementer(I4)\n class B(Odd):\n pass\n\n class C(A, B):\n pass\n classImplementsOnly(C, I1, I2)\n self.assertEqual([i.__name__ for i in implementedBy(C)], ['I1', 'I2'])\n", "method_code": "def classImplementsOnly(cls, *interfaces):\n \"\"\"Declare the only interfaces implemented by instances of a class\n\n The arguments after the class are one or more interfaces or interface\n specifications (``IDeclaration`` objects).\n\n The interfaces given (including the interfaces in the specifications)\n replace any previous declarations.\n \"\"\"\n spec = implementedBy(cls)\n spec.declared = ()\n spec.inherit = None\n classImplements(cls, *interfaces)", "context": "def classImplementsOnly(cls, *interfaces): ...\ndef _implements_name(ob): ...\ndef implementedByFallback(cls): ...\ndef classImplementsOnly(cls, *interfaces): ...\ndef classImplements(cls, *interfaces): ...\ndef _implements_advice(cls): ...\ndef _implements(name, interfaces, classImplements): ...\ndef implements(*interfaces): ...\ndef implementsOnly(*interfaces): ...\ndef Provides(*interfaces): ...\ndef directlyProvides(object, *interfaces): ...\ndef alsoProvides(object, *interfaces): ...\ndef noLongerProvides(object, interface): ...\ndef directlyProvidedBy(object): ...\ndef classProvides(*interfaces): ...\ndef _classProvides_advice(cls): ...\ndef moduleProvides(*interfaces): ...\ndef ObjectSpecification(direct, cls): ...\ndef getObjectSpecificationFallback(ob): ...\ndef providedByFallback(ob): ...\ndef _normalizeargs(sequence, output=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_classImplementsOnly", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000159.py"} {"focal_file": "lib/zope/interface/declarations.py", "focal_class": null, "focal_method": "directlyProvides", "tests": "import unittest\n\nclass Test_directlyProvides(unittest.TestCase):\n def test_directlyProvides(self):\n\n class IA1(Interface):\n pass\n\n class IA2(Interface):\n pass\n\n class IB(Interface):\n pass\n\n class IC(Interface):\n pass\n\n class A(Odd):\n pass\n classImplements(A, IA1, IA2)\n\n class B(Odd):\n pass\n classImplements(B, IB)\n\n class C(A, B):\n pass\n classImplements(C, IC)\n ob = C()\n directlyProvides(ob, I1, I2)\n self.assertTrue(I1 in providedBy(ob))\n self.assertTrue(I2 in providedBy(ob))\n self.assertTrue(IA1 in providedBy(ob))\n self.assertTrue(IA2 in providedBy(ob))\n self.assertTrue(IB in providedBy(ob))\n self.assertTrue(IC in providedBy(ob))\n directlyProvides(ob, directlyProvidedBy(ob) - I2)\n self.assertTrue(I1 in providedBy(ob))\n self.assertFalse(I2 in providedBy(ob))\n self.assertFalse(I2 in providedBy(ob))\n directlyProvides(ob, directlyProvidedBy(ob), I2)\n self.assertTrue(I2 in providedBy(ob))\n", "method_code": "def directlyProvides(object, *interfaces):\n \"\"\"Declare interfaces declared directly for an object\n\n The arguments after the object are one or more interfaces or interface\n specifications (``IDeclaration`` objects).\n\n The interfaces given (including the interfaces in the specifications)\n replace interfaces previously declared for the object.\n \"\"\"\n cls = getattr(object, '__class__', None)\n if cls is not None and getattr(cls, '__class__', None) is cls:\n if not isinstance(object, DescriptorAwareMetaClasses):\n raise TypeError('Attempt to make an interface declaration on a non-descriptor-aware class')\n interfaces = _normalizeargs(interfaces)\n if cls is None:\n cls = type(object)\n issub = False\n for damc in DescriptorAwareMetaClasses:\n if issubclass(cls, damc):\n issub = True\n break\n if issub:\n object.__provides__ = ClassProvides(object, cls, *interfaces)\n else:\n object.__provides__ = Provides(cls, *interfaces)", "context": "def directlyProvides(object, *interfaces): ...\ndef _implements_name(ob): ...\ndef implementedByFallback(cls): ...\ndef classImplementsOnly(cls, *interfaces): ...\ndef classImplements(cls, *interfaces): ...\ndef _implements_advice(cls): ...\ndef _implements(name, interfaces, classImplements): ...\ndef implements(*interfaces): ...\ndef implementsOnly(*interfaces): ...\ndef Provides(*interfaces): ...\ndef directlyProvides(object, *interfaces): ...\ndef alsoProvides(object, *interfaces): ...\ndef noLongerProvides(object, interface): ...\ndef directlyProvidedBy(object): ...\ndef classProvides(*interfaces): ...\ndef _classProvides_advice(cls): ...\ndef moduleProvides(*interfaces): ...\ndef ObjectSpecification(direct, cls): ...\ndef getObjectSpecificationFallback(ob): ...\ndef providedByFallback(ob): ...\ndef _normalizeargs(sequence, output=None): ...\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_directlyProvides", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000160.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "registerUtility", "tests": "import unittest\n\nclass Test_registerUtility(unittest.TestCase):\n def test_registerUtility_w_component(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Registered\n from zope.interface.registry import UtilityRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name = u'name'\n _to_reg = object()\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerUtility(_to_reg, ifoo, _name, _info)\n self.assertTrue(comp.utilities._adapters[0][ifoo][_name] is _to_reg)\n self.assertEqual(comp._utility_registrations[ifoo, _name], (_to_reg, _info, None))\n self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,))\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Registered))\n self.assertTrue(isinstance(event.object, UtilityRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertTrue(event.object.name is _name)\n self.assertTrue(event.object.component is _to_reg)\n self.assertTrue(event.object.info is _info)\n self.assertTrue(event.object.factory is None)\n\n def test_registerUtility_w_factory(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Registered\n from zope.interface.registry import UtilityRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name = u'name'\n _to_reg = object()\n\n def _factory():\n return _to_reg\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerUtility(None, ifoo, _name, _info, factory=_factory)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Registered))\n self.assertTrue(isinstance(event.object, UtilityRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertTrue(event.object.name is _name)\n self.assertTrue(event.object.component is _to_reg)\n self.assertTrue(event.object.info is _info)\n self.assertTrue(event.object.factory is _factory)\n\n def test_registerUtility_wo_provided(self):\n from zope.interface.declarations import directlyProvides\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Registered\n from zope.interface.registry import UtilityRegistration\n\n class IFoo(InterfaceClass):\n pass\n\n class Foo(object):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name = u'name'\n _to_reg = Foo()\n directlyProvides(_to_reg, ifoo)\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerUtility(_to_reg, None, _name, _info)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Registered))\n self.assertTrue(isinstance(event.object, UtilityRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertTrue(event.object.name is _name)\n self.assertTrue(event.object.component is _to_reg)\n self.assertTrue(event.object.info is _info)\n self.assertTrue(event.object.factory is None)\n\n def test_registerUtility_w_different_info(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info1 = u'info1'\n _info2 = u'info2'\n _name = u'name'\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, _name, _info1)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerUtility(_to_reg, ifoo, _name, _info2)\n self.assertEqual(len(_events), 2)\n self.assertEqual(comp._utility_registrations[ifoo, _name], (_to_reg, _info2, None))\n self.assertEqual(comp.utilities._subscribers[0][ifoo][u''], (_to_reg,))\n\n def test_registerUtility_w_existing_subscr(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name1 = u'name1'\n _name2 = u'name2'\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, _name1, _info)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerUtility(_to_reg, ifoo, _name2, _info)\n self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,))\n\n def test_registerUtility_wo_event(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name = u'name'\n _to_reg = object()\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerUtility(_to_reg, ifoo, _name, _info, False)\n self.assertEqual(len(_events), 0)\n", "method_code": " def registerUtility(self, provided, name, component, info, factory):\n subscribed = self._is_utility_subscribed(provided, component)\n self._utility_registrations[provided, name] = (component, info, factory)\n self._utilities.register((), provided, name, component)\n if not subscribed:\n self._utilities.subscribe((), provided, component)\n self.__cache_utility(provided, component)\n ", "context": "class _UtilityRegistrations(object):\n def registerUtility(self, provided, name, component, info, factory): ...\n def for_components(cls, components): ...\n def clear_cache(cls): ...\n def __init__(self, utilities, utility_registrations): ...\n def __populate_cache(self): ...\n def __cache_utility(self, provided, component): ...\n def __uncache_utility(self, provided, component): ...\n def _is_utility_subscribed(self, provided, component): ...\n def unregisterUtility(self, provided, name, component): ...\n\n self._cache = defaultdict(lambda: defaultdict(int))\n self._utilities = utilities\n self._utility_registrations = utility_registrations\n\n _regs_for_components = {}\n _weakrefs_for_components = {}\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_registerUtility_w_component", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000161.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "unregisterUtility", "tests": "import unittest\n\nclass Test_unregisterUtility(unittest.TestCase):\n def test_unregisterUtility_w_component_miss(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _name = u'name'\n _to_reg = object()\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterUtility(_to_reg, ifoo, _name)\n self.assertFalse(unreg)\n self.assertFalse(_events)\n\n def test_unregisterUtility_w_component(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import UtilityRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _name = u'name'\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, _name)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterUtility(_to_reg, ifoo, _name)\n self.assertTrue(unreg)\n self.assertFalse(comp.utilities._adapters)\n self.assertFalse((ifoo, _name) in comp._utility_registrations)\n self.assertFalse(comp.utilities._subscribers)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, UtilityRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertTrue(event.object.name is _name)\n self.assertTrue(event.object.component is _to_reg)\n self.assertTrue(event.object.factory is None)\n\n def test_unregisterUtility_w_factory(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import UtilityRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name = u'name'\n _to_reg = object()\n\n def _factory():\n return _to_reg\n comp = self._makeOne()\n comp.registerUtility(None, ifoo, _name, _info, factory=_factory)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterUtility(None, ifoo, _name, factory=_factory)\n self.assertTrue(unreg)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, UtilityRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertTrue(event.object.name is _name)\n self.assertTrue(event.object.component is _to_reg)\n self.assertTrue(event.object.factory is _factory)\n\n def test_unregisterUtility_wo_explicit_provided(self):\n from zope.interface.declarations import directlyProvides\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import UtilityRegistration\n\n class IFoo(InterfaceClass):\n pass\n\n class Foo(object):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name = u'name'\n _to_reg = Foo()\n directlyProvides(_to_reg, ifoo)\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, _name, _info)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterUtility(_to_reg, None, _name)\n self.assertTrue(unreg)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, UtilityRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertTrue(event.object.name is _name)\n self.assertTrue(event.object.component is _to_reg)\n self.assertTrue(event.object.info is _info)\n self.assertTrue(event.object.factory is None)\n\n def test_unregisterUtility_w_existing_subscr(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name1 = u'name1'\n _name2 = u'name2'\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, _name1, _info)\n comp.registerUtility(_to_reg, ifoo, _name2, _info)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.unregisterUtility(_to_reg, ifoo, _name2)\n self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,))\n", "method_code": " def unregisterUtility(self, provided, name, component):\n del self._utility_registrations[provided, name]\n self._utilities.unregister((), provided, name)\n subscribed = self.__uncache_utility(provided, component)\n if not subscribed:\n self._utilities.unsubscribe((), provided, component)\n ", "context": "class _UtilityRegistrations(object):\n def unregisterUtility(self, provided, name, component): ...\n def for_components(cls, components): ...\n def clear_cache(cls): ...\n def __init__(self, utilities, utility_registrations): ...\n def __populate_cache(self): ...\n def __cache_utility(self, provided, component): ...\n def __uncache_utility(self, provided, component): ...\n def _is_utility_subscribed(self, provided, component): ...\n def registerUtility(self, provided, name, component, info, factory): ...\n\n self._cache = defaultdict(lambda: defaultdict(int))\n self._utilities = utilities\n self._utility_registrations = utility_registrations\n\n _regs_for_components = {}\n _weakrefs_for_components = {}\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_unregisterUtility_w_component_miss", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000162.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "clear_cache", "tests": "import unittest\n\nclass Test_clear_cache(unittest.TestCase):\n def test_unregisterUtility_w_existing_subscr_non_hashable_fresh_cache(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.registry import _UtilityRegistrations\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name1 = u'name1'\n _name2 = u'name2'\n _to_reg = dict()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, _name1, _info)\n comp.registerUtility(_to_reg, ifoo, _name2, _info)\n _UtilityRegistrations.clear_cache()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.unregisterUtility(_to_reg, ifoo, _name2)\n self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,))\n", "method_code": " def clear_cache(cls):\n cls._regs_for_components.clear()\n ", "context": "class _UtilityRegistrations(object):\n @classmethod\n def clear_cache(cls): ...\n def for_components(cls, components): ...\n def __init__(self, utilities, utility_registrations): ...\n def __populate_cache(self): ...\n def __cache_utility(self, provided, component): ...\n def __uncache_utility(self, provided, component): ...\n def _is_utility_subscribed(self, provided, component): ...\n def registerUtility(self, provided, name, component, info, factory): ...\n def unregisterUtility(self, provided, name, component): ...\n\n self._cache = defaultdict(lambda: defaultdict(int))\n self._utilities = utilities\n self._utility_registrations = utility_registrations\n\n _regs_for_components = {}\n _weakrefs_for_components = {}\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_unregisterUtility_w_existing_subscr_non_hashable_fresh_cache", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000163.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "registeredUtilities", "tests": "import unittest\n\nclass Test_registeredUtilities(unittest.TestCase):\n def test_registeredUtilities_empty(self):\n comp = self._makeOne()\n self.assertEqual(list(comp.registeredUtilities()), [])\n\n def test_registeredUtilities_notempty(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.registry import UtilityRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _info = u'info'\n _name1 = u'name1'\n _name2 = u'name2'\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, _name1, _info)\n comp.registerUtility(_to_reg, ifoo, _name2, _info)\n reg = sorted(comp.registeredUtilities(), key=lambda r: r.name)\n self.assertEqual(len(reg), 2)\n self.assertTrue(isinstance(reg[0], UtilityRegistration))\n self.assertTrue(reg[0].registry is comp)\n self.assertTrue(reg[0].provided is ifoo)\n self.assertTrue(reg[0].name is _name1)\n self.assertTrue(reg[0].component is _to_reg)\n self.assertTrue(reg[0].info is _info)\n self.assertTrue(reg[0].factory is None)\n self.assertTrue(isinstance(reg[1], UtilityRegistration))\n self.assertTrue(reg[1].registry is comp)\n self.assertTrue(reg[1].provided is ifoo)\n self.assertTrue(reg[1].name is _name2)\n self.assertTrue(reg[1].component is _to_reg)\n self.assertTrue(reg[1].info is _info)\n self.assertTrue(reg[1].factory is None)\n", "method_code": " def registeredUtilities(self):\n for (provided, name), data in iter(self._utility_registrations.items()):\n yield UtilityRegistration(self, provided, name, *data)\n ", "context": "class Components(object):\n def registeredUtilities(self): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_registeredUtilities_empty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000164.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "queryUtility", "tests": "import unittest\n\nclass Test_queryUtility(unittest.TestCase):\n def test_queryUtility_hit(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo)\n self.assertTrue(comp.queryUtility(ifoo) is _to_reg)\n", "method_code": " def queryUtility(self, provided, name=u'', default=None):\n return self.utilities.lookup((), provided, name, default)\n ", "context": "class Components(object):\n def queryUtility(self, provided, name=u'', default=None): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_queryUtility_hit", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000165.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "getUtility", "tests": "import unittest\n\nclass Test_getUtility(unittest.TestCase):\n def test_getUtility_hit(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo)\n self.assertTrue(comp.getUtility(ifoo) is _to_reg)\n", "method_code": " def getUtility(self, provided, name=u''):\n utility = self.utilities.lookup((), provided, name)\n if utility is None:\n raise ComponentLookupError(provided, name)\n return utility\n ", "context": "class Components(object):\n def getUtility(self, provided, name=u''): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_getUtility_hit", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000166.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "getUtilitiesFor", "tests": "import unittest\n\nclass Test_getUtilitiesFor(unittest.TestCase):\n def test_getUtilitiesFor_miss(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n comp = self._makeOne()\n self.assertEqual(list(comp.getUtilitiesFor(ifoo)), [])\n\n def test_getUtilitiesFor_hit(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _name1 = u'name1'\n _name2 = u'name2'\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, name=_name1)\n comp.registerUtility(_to_reg, ifoo, name=_name2)\n self.assertEqual(sorted(comp.getUtilitiesFor(ifoo)), [(_name1, _to_reg), (_name2, _to_reg)])\n", "method_code": " def getUtilitiesFor(self, interface):\n for name, utility in self.utilities.lookupAll((), interface):\n yield (name, utility)\n ", "context": "class Components(object):\n def getUtilitiesFor(self, interface): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_getUtilitiesFor_miss", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000167.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "getAllUtilitiesRegisteredFor", "tests": "import unittest\n\nclass Test_getAllUtilitiesRegisteredFor(unittest.TestCase):\n def test_getAllUtilitiesRegisteredFor_miss(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n comp = self._makeOne()\n self.assertEqual(list(comp.getAllUtilitiesRegisteredFor(ifoo)), [])\n\n def test_getAllUtilitiesRegisteredFor_hit(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n _name1 = u'name1'\n _name2 = u'name2'\n _to_reg = object()\n comp = self._makeOne()\n comp.registerUtility(_to_reg, ifoo, name=_name1)\n comp.registerUtility(_to_reg, ifoo, name=_name2)\n self.assertEqual(list(comp.getAllUtilitiesRegisteredFor(ifoo)), [_to_reg])\n", "method_code": " def getAllUtilitiesRegisteredFor(self, interface):\n return self.utilities.subscriptions((), interface)\n ", "context": "class Components(object):\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_getAllUtilitiesRegisteredFor_miss", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000168.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "registerAdapter", "tests": "import unittest\n\nclass Test_registerAdapter(unittest.TestCase):\n def test_registerAdapter_wo_event(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n _info = u'info'\n _name = u'name'\n _to_reg = object()\n\n def _factory(context):\n return _to_reg\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerAdapter(_factory, (ibar,), ifoo, _name, _info, event=False)\n self.assertEqual(len(_events), 0)\n", "method_code": " def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True):\n if provided is None:\n provided = _getAdapterProvided(factory)\n required = _getAdapterRequired(factory, required)\n if name == u'':\n name = _getName(factory)\n self._adapter_registrations[required, provided, name] = (factory, info)\n self.adapters.register(required, provided, name, factory)\n if event:\n notify(Registered(AdapterRegistration(self, required, provided, name, factory, info)))\n ", "context": "class Components(object):\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_registerAdapter_wo_event", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000169.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "unregisterAdapter", "tests": "import unittest\n\nclass Test_unregisterAdapter(unittest.TestCase):\n def test_unregisterAdapter_miss(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterAdapter(_Factory, (ibar,), ifoo)\n self.assertFalse(unreg)\n\n def test_unregisterAdapter_wo_explicit_provided(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import AdapterRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n @implementer(ifoo)\n class _Factory(object):\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n comp.registerAdapter(_Factory, (ibar,), ifoo)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterAdapter(_Factory, (ibar,))\n self.assertTrue(unreg)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, AdapterRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, '')\n self.assertEqual(event.object.info, '')\n self.assertTrue(event.object.factory is _Factory)\n\n def test_unregisterAdapter_wo_explicit_required(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import AdapterRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n __component_adapts__ = (ibar,)\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n comp.registerAdapter(_Factory, (ibar,), ifoo)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterAdapter(_Factory, provided=ifoo)\n self.assertTrue(unreg)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, AdapterRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, '')\n self.assertEqual(event.object.info, '')\n self.assertTrue(event.object.factory is _Factory)\n", "method_code": " def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''):\n if provided is None:\n if factory is None:\n raise TypeError('Must specify one of factory and provided')\n provided = _getAdapterProvided(factory)\n if required is None and factory is None:\n raise TypeError('Must specify one of factory and required')\n required = _getAdapterRequired(factory, required)\n old = self._adapter_registrations.get((required, provided, name))\n if old is None or (factory is not None and factory != old[0]):\n return False\n del self._adapter_registrations[required, provided, name]\n self.adapters.unregister(required, provided, name)\n notify(Unregistered(AdapterRegistration(self, required, provided, name, *old)))\n return True\n ", "context": "class Components(object):\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_unregisterAdapter_miss", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000170.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "registeredAdapters", "tests": "import unittest\n\nclass Test_registeredAdapters(unittest.TestCase):\n def test_registeredAdapters_empty(self):\n comp = self._makeOne()\n self.assertEqual(list(comp.registeredAdapters()), [])\n\n def test_registeredAdapters_notempty(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.registry import AdapterRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IFoo')\n _info = u'info'\n _name1 = u'name1'\n _name2 = u'name2'\n\n class _Factory(object):\n\n def __init__(self, context):\n pass\n comp = self._makeOne()\n comp.registerAdapter(_Factory, (ibar,), ifoo, _name1, _info)\n comp.registerAdapter(_Factory, (ibar,), ifoo, _name2, _info)\n reg = sorted(comp.registeredAdapters(), key=lambda r: r.name)\n self.assertEqual(len(reg), 2)\n self.assertTrue(isinstance(reg[0], AdapterRegistration))\n self.assertTrue(reg[0].registry is comp)\n self.assertTrue(reg[0].provided is ifoo)\n self.assertEqual(reg[0].required, (ibar,))\n self.assertTrue(reg[0].name is _name1)\n self.assertTrue(reg[0].info is _info)\n self.assertTrue(reg[0].factory is _Factory)\n self.assertTrue(isinstance(reg[1], AdapterRegistration))\n self.assertTrue(reg[1].registry is comp)\n self.assertTrue(reg[1].provided is ifoo)\n self.assertEqual(reg[1].required, (ibar,))\n self.assertTrue(reg[1].name is _name2)\n self.assertTrue(reg[1].info is _info)\n self.assertTrue(reg[1].factory is _Factory)\n", "method_code": " def registeredAdapters(self):\n for (required, provided, name), (component, info) in iter(self._adapter_registrations.items()):\n yield AdapterRegistration(self, required, provided, name, component, info)\n ", "context": "class Components(object):\n def registeredAdapters(self): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_registeredAdapters_empty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000171.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "queryAdapter", "tests": "import unittest\n\nclass Test_queryAdapter(unittest.TestCase):\n def test_queryAdapter_hit(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n\n def __init__(self, context):\n self.context = context\n\n @implementer(ibar)\n class _Context(object):\n pass\n _context = _Context()\n comp = self._makeOne()\n comp.registerAdapter(_Factory, (ibar,), ifoo)\n adapter = comp.queryAdapter(_context, ifoo)\n self.assertTrue(isinstance(adapter, _Factory))\n self.assertTrue(adapter.context is _context)\n", "method_code": " def queryAdapter(self, object, interface, name=u'', default=None):\n return self.adapters.queryAdapter(object, interface, name, default)\n ", "context": "class Components(object):\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_queryAdapter_hit", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000172.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "getAdapter", "tests": "import unittest\n\nclass Test_getAdapter(unittest.TestCase):\n def test_getAdapter_hit(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n\n def __init__(self, context):\n self.context = context\n\n @implementer(ibar)\n class _Context(object):\n pass\n _context = _Context()\n comp = self._makeOne()\n comp.registerAdapter(_Factory, (ibar,), ifoo)\n adapter = comp.getAdapter(_context, ifoo)\n self.assertTrue(isinstance(adapter, _Factory))\n self.assertTrue(adapter.context is _context)\n", "method_code": " def getAdapter(self, object, interface, name=u''):\n adapter = self.adapters.queryAdapter(object, interface, name)\n if adapter is None:\n raise ComponentLookupError(object, interface, name)\n return adapter\n ", "context": "class Components(object):\n def getAdapter(self, object, interface, name=u''): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_getAdapter_hit", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000173.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "queryMultiAdapter", "tests": "import unittest\n\nclass Test_queryMultiAdapter(unittest.TestCase):\n def test_queryMultiAdapter_miss(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n ibaz = IFoo('IBaz')\n\n @implementer(ibar)\n class _Context1(object):\n pass\n\n @implementer(ibaz)\n class _Context2(object):\n pass\n _context1 = _Context1()\n _context2 = _Context2()\n comp = self._makeOne()\n self.assertEqual(comp.queryMultiAdapter((_context1, _context2), ifoo), None)\n\n def test_queryMultiAdapter_miss_w_default(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n ibaz = IFoo('IBaz')\n\n @implementer(ibar)\n class _Context1(object):\n pass\n\n @implementer(ibaz)\n class _Context2(object):\n pass\n _context1 = _Context1()\n _context2 = _Context2()\n _default = object()\n comp = self._makeOne()\n self.assertTrue(comp.queryMultiAdapter((_context1, _context2), ifoo, default=_default) is _default)\n\n def test_queryMultiAdapter_hit(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n ibaz = IFoo('IBaz')\n\n @implementer(ibar)\n class _Context1(object):\n pass\n\n @implementer(ibaz)\n class _Context2(object):\n pass\n _context1 = _Context1()\n _context2 = _Context2()\n\n class _Factory(object):\n\n def __init__(self, context1, context2):\n self.context = (context1, context2)\n comp = self._makeOne()\n comp.registerAdapter(_Factory, (ibar, ibaz), ifoo)\n adapter = comp.queryMultiAdapter((_context1, _context2), ifoo)\n self.assertTrue(isinstance(adapter, _Factory))\n self.assertEqual(adapter.context, (_context1, _context2))\n", "method_code": " def queryMultiAdapter(self, objects, interface, name=u'', default=None):\n return self.adapters.queryMultiAdapter(objects, interface, name, default)\n ", "context": "class Components(object):\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_queryMultiAdapter_miss", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000174.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "getMultiAdapter", "tests": "import unittest\n\nclass Test_getMultiAdapter(unittest.TestCase):\n def test_getMultiAdapter_hit(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n ibaz = IFoo('IBaz')\n\n @implementer(ibar)\n class _Context1(object):\n pass\n\n @implementer(ibaz)\n class _Context2(object):\n pass\n _context1 = _Context1()\n _context2 = _Context2()\n\n class _Factory(object):\n\n def __init__(self, context1, context2):\n self.context = (context1, context2)\n comp = self._makeOne()\n comp.registerAdapter(_Factory, (ibar, ibaz), ifoo)\n adapter = comp.getMultiAdapter((_context1, _context2), ifoo)\n self.assertTrue(isinstance(adapter, _Factory))\n self.assertEqual(adapter.context, (_context1, _context2))\n", "method_code": " def getMultiAdapter(self, objects, interface, name=u''):\n adapter = self.adapters.queryMultiAdapter(objects, interface, name)\n if adapter is None:\n raise ComponentLookupError(objects, interface, name)\n return adapter\n ", "context": "class Components(object):\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_getMultiAdapter_hit", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000175.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "getAdapters", "tests": "import unittest\n\nclass Test_getAdapters(unittest.TestCase):\n def test_getAdapters_empty(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n ibaz = IFoo('IBaz')\n\n @implementer(ibar)\n class _Context1(object):\n pass\n\n @implementer(ibaz)\n class _Context2(object):\n pass\n _context1 = _Context1()\n _context2 = _Context2()\n comp = self._makeOne()\n self.assertEqual(list(comp.getAdapters((_context1, _context2), ifoo)), [])\n\n def test_getAdapters_non_empty(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n ibaz = IFoo('IBaz')\n\n @implementer(ibar)\n class _Context1(object):\n pass\n\n @implementer(ibaz)\n class _Context2(object):\n pass\n _context1 = _Context1()\n _context2 = _Context2()\n\n class _Factory1(object):\n\n def __init__(self, context1, context2):\n self.context = (context1, context2)\n\n class _Factory2(object):\n\n def __init__(self, context1, context2):\n self.context = (context1, context2)\n _name1 = u'name1'\n _name2 = u'name2'\n comp = self._makeOne()\n comp.registerAdapter(_Factory1, (ibar, ibaz), ifoo, name=_name1)\n comp.registerAdapter(_Factory2, (ibar, ibaz), ifoo, name=_name2)\n found = sorted(comp.getAdapters((_context1, _context2), ifoo))\n self.assertEqual(len(found), 2)\n self.assertEqual(found[0][0], _name1)\n self.assertTrue(isinstance(found[0][1], _Factory1))\n self.assertEqual(found[1][0], _name2)\n self.assertTrue(isinstance(found[1][1], _Factory2))\n", "method_code": " def getAdapters(self, objects, provided):\n for name, factory in self.adapters.lookupAll(list(map(providedBy, objects)), provided):\n adapter = factory(*objects)\n if adapter is not None:\n yield (name, adapter)\n ", "context": "class Components(object):\n def getAdapters(self, objects, provided): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_getAdapters_empty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000176.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "registerSubscriptionAdapter", "tests": "import unittest\n\nclass Test_registerSubscriptionAdapter(unittest.TestCase):\n def test_registerSubscriptionAdapter_w_explicit_provided_and_required(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Registered\n from zope.interface.registry import SubscriptionRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n _blank = u''\n _info = u'info'\n _to_reg = object()\n\n def _factory(context):\n return _to_reg\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerSubscriptionAdapter(_factory, (ibar,), ifoo, info=_info)\n reg = comp.adapters._subscribers[1][ibar][ifoo][_blank]\n self.assertEqual(len(reg), 1)\n self.assertTrue(reg[0] is _factory)\n self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _factory, _info)])\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Registered))\n self.assertTrue(isinstance(event.object, SubscriptionRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, _blank)\n self.assertTrue(event.object.info is _info)\n self.assertTrue(event.object.factory is _factory)\n\n def test_registerSubscriptionAdapter_wo_explicit_provided(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n from zope.interface.interfaces import Registered\n from zope.interface.registry import SubscriptionRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n _info = u'info'\n _blank = u''\n _to_reg = object()\n\n @implementer(ifoo)\n class _Factory(object):\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerSubscriptionAdapter(_Factory, (ibar,), info=_info)\n reg = comp.adapters._subscribers[1][ibar][ifoo][_blank]\n self.assertEqual(len(reg), 1)\n self.assertTrue(reg[0] is _Factory)\n self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _Factory, _info)])\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Registered))\n self.assertTrue(isinstance(event.object, SubscriptionRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, _blank)\n self.assertTrue(event.object.info is _info)\n self.assertTrue(event.object.factory is _Factory)\n\n def test_registerSubscriptionAdapter_wo_explicit_required(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Registered\n from zope.interface.registry import SubscriptionRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n _info = u'info'\n _blank = u''\n\n class _Factory(object):\n __component_adapts__ = (ibar,)\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerSubscriptionAdapter(_Factory, provided=ifoo, info=_info)\n reg = comp.adapters._subscribers[1][ibar][ifoo][_blank]\n self.assertEqual(len(reg), 1)\n self.assertTrue(reg[0] is _Factory)\n self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _Factory, _info)])\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Registered))\n self.assertTrue(isinstance(event.object, SubscriptionRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, _blank)\n self.assertTrue(event.object.info is _info)\n self.assertTrue(event.object.factory is _Factory)\n\n def test_registerSubscriptionAdapter_wo_event(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n _blank = u''\n _info = u'info'\n _to_reg = object()\n\n def _factory(context):\n return _to_reg\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n comp.registerSubscriptionAdapter(_factory, (ibar,), ifoo, info=_info, event=False)\n self.assertEqual(len(_events), 0)\n", "method_code": " def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True):\n if name:\n raise TypeError('Named subscribers are not yet supported')\n if provided is None:\n provided = _getAdapterProvided(factory)\n required = _getAdapterRequired(factory, required)\n self._subscription_registrations.append((required, provided, name, factory, info))\n self.adapters.subscribe(required, provided, factory)\n if event:\n notify(Registered(SubscriptionRegistration(self, required, provided, name, factory, info)))\n ", "context": "class Components(object):\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_registerSubscriptionAdapter_w_explicit_provided_and_required", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000177.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "registeredSubscriptionAdapters", "tests": "import unittest\n\nclass Test_registeredSubscriptionAdapters(unittest.TestCase):\n def test_registeredSubscriptionAdapters_empty(self):\n comp = self._makeOne()\n self.assertEqual(list(comp.registeredSubscriptionAdapters()), [])\n\n def test_registeredSubscriptionAdapters_notempty(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.registry import SubscriptionRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IFoo')\n _info = u'info'\n _blank = u''\n\n class _Factory(object):\n\n def __init__(self, context):\n pass\n comp = self._makeOne()\n comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo, info=_info)\n comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo, info=_info)\n reg = list(comp.registeredSubscriptionAdapters())\n self.assertEqual(len(reg), 2)\n self.assertTrue(isinstance(reg[0], SubscriptionRegistration))\n self.assertTrue(reg[0].registry is comp)\n self.assertTrue(reg[0].provided is ifoo)\n self.assertEqual(reg[0].required, (ibar,))\n self.assertEqual(reg[0].name, _blank)\n self.assertTrue(reg[0].info is _info)\n self.assertTrue(reg[0].factory is _Factory)\n self.assertTrue(isinstance(reg[1], SubscriptionRegistration))\n self.assertTrue(reg[1].registry is comp)\n self.assertTrue(reg[1].provided is ifoo)\n self.assertEqual(reg[1].required, (ibar,))\n self.assertEqual(reg[1].name, _blank)\n self.assertTrue(reg[1].info is _info)\n self.assertTrue(reg[1].factory is _Factory)\n", "method_code": " def registeredSubscriptionAdapters(self):\n for data in self._subscription_registrations:\n yield SubscriptionRegistration(self, *data)\n ", "context": "class Components(object):\n def registeredSubscriptionAdapters(self): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_registeredSubscriptionAdapters_empty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000178.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "unregisterSubscriptionAdapter", "tests": "import unittest\n\nclass Test_unregisterSubscriptionAdapter(unittest.TestCase):\n def test_unregisterSubscriptionAdapter_miss(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,), ifoo)\n self.assertFalse(unreg)\n self.assertFalse(_events)\n\n def test_unregisterSubscriptionAdapter_hit_wo_factory(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import SubscriptionRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterSubscriptionAdapter(None, (ibar,), ifoo)\n self.assertTrue(unreg)\n self.assertFalse(comp.adapters._subscribers)\n self.assertFalse(comp._subscription_registrations)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, SubscriptionRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, '')\n self.assertEqual(event.object.info, '')\n self.assertTrue(event.object.factory is None)\n\n def test_unregisterSubscriptionAdapter_hit_w_factory(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import SubscriptionRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,), ifoo)\n self.assertTrue(unreg)\n self.assertFalse(comp.adapters._subscribers)\n self.assertFalse(comp._subscription_registrations)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, SubscriptionRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, '')\n self.assertEqual(event.object.info, '')\n self.assertTrue(event.object.factory is _Factory)\n\n def test_unregisterSubscriptionAdapter_wo_explicit_provided(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import SubscriptionRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n @implementer(ifoo)\n class _Factory(object):\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,))\n self.assertTrue(unreg)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, SubscriptionRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, '')\n self.assertEqual(event.object.info, '')\n self.assertTrue(event.object.factory is _Factory)\n\n def test_unregisterSubscriptionAdapter_wo_explicit_required(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import SubscriptionRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n __component_adapts__ = (ibar,)\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterSubscriptionAdapter(_Factory, provided=ifoo)\n self.assertTrue(unreg)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, SubscriptionRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertTrue(event.object.provided is ifoo)\n self.assertEqual(event.object.required, (ibar,))\n self.assertEqual(event.object.name, '')\n self.assertEqual(event.object.info, '')\n self.assertTrue(event.object.factory is _Factory)\n", "method_code": " def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''):\n if name:\n raise TypeError('Named subscribers are not yet supported')\n if provided is None:\n if factory is None:\n raise TypeError('Must specify one of factory and provided')\n provided = _getAdapterProvided(factory)\n if required is None and factory is None:\n raise TypeError('Must specify one of factory and required')\n required = _getAdapterRequired(factory, required)\n if factory is None:\n new = [(r, p, n, f, i) for r, p, n, f, i in self._subscription_registrations if not (r == required and p == provided)]\n else:\n new = [(r, p, n, f, i) for r, p, n, f, i in self._subscription_registrations if not (r == required and p == provided and (f == factory))]\n if len(new) == len(self._subscription_registrations):\n return False\n self._subscription_registrations[:] = new\n self.adapters.unsubscribe(required, provided, factory)\n notify(Unregistered(SubscriptionRegistration(self, required, provided, name, factory, '')))\n return True\n ", "context": "class Components(object):\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_unregisterSubscriptionAdapter_miss", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000179.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "subscribers", "tests": "import unittest\n\nclass Test_subscribers(unittest.TestCase):\n def test_subscribers_empty(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n comp = self._makeOne()\n\n @implementer(ibar)\n class Bar(object):\n pass\n bar = Bar()\n self.assertEqual(list(comp.subscribers((bar,), ifoo)), [])\n\n def test_subscribers_non_empty(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.declarations import implementer\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n ibar = IFoo('IBar')\n\n class _Factory(object):\n __component_adapts__ = (ibar,)\n\n def __init__(self, context):\n self._context = context\n\n class _Derived(_Factory):\n pass\n comp = self._makeOne()\n comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo)\n comp.registerSubscriptionAdapter(_Derived, (ibar,), ifoo)\n\n @implementer(ibar)\n class Bar(object):\n pass\n bar = Bar()\n subscribers = comp.subscribers((bar,), ifoo)\n\n def _klassname(x):\n return x.__class__.__name__\n subscribers = sorted(subscribers, key=_klassname)\n self.assertEqual(len(subscribers), 2)\n self.assertTrue(isinstance(subscribers[0], _Derived))\n self.assertTrue(isinstance(subscribers[1], _Factory))\n", "method_code": " def subscribers(self, objects, provided):\n return self.adapters.subscribers(objects, provided)\n ", "context": "class Components(object):\n def subscribers(self, objects, provided): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_subscribers_empty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000180.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "registeredHandlers", "tests": "import unittest\n\nclass Test_registeredHandlers(unittest.TestCase):\n def test_registeredHandlers_empty(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n comp = self._makeOne()\n self.assertFalse(list(comp.registeredHandlers()))\n\n def test_registeredHandlers_non_empty(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.registry import HandlerRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n\n def _factory1(context):\n pass\n\n def _factory2(context):\n pass\n comp = self._makeOne()\n comp.registerHandler(_factory1, (ifoo,))\n comp.registerHandler(_factory2, (ifoo,))\n\n def _factory_name(x):\n return x.factory.__code__.co_name\n subscribers = sorted(comp.registeredHandlers(), key=_factory_name)\n self.assertEqual(len(subscribers), 2)\n self.assertTrue(isinstance(subscribers[0], HandlerRegistration))\n self.assertEqual(subscribers[0].required, (ifoo,))\n self.assertEqual(subscribers[0].name, '')\n self.assertEqual(subscribers[0].factory, _factory1)\n self.assertEqual(subscribers[0].info, '')\n self.assertTrue(isinstance(subscribers[1], HandlerRegistration))\n self.assertEqual(subscribers[1].required, (ifoo,))\n self.assertEqual(subscribers[1].name, '')\n self.assertEqual(subscribers[1].factory, _factory2)\n self.assertEqual(subscribers[1].info, '')\n", "method_code": " def registeredHandlers(self):\n for data in self._handler_registrations:\n yield HandlerRegistration(self, *data)\n ", "context": "class Components(object):\n def registeredHandlers(self): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_registeredHandlers_empty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000181.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "unregisterHandler", "tests": "import unittest\n\nclass Test_unregisterHandler(unittest.TestCase):\n def test_unregisterHandler_miss(self):\n from zope.interface.declarations import InterfaceClass\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n comp = self._makeOne()\n unreg = comp.unregisterHandler(required=(ifoo,))\n self.assertFalse(unreg)\n\n def test_unregisterHandler_wo_explicit_required(self):\n from zope.interface.declarations import InterfaceClass\n from zope.interface.interfaces import Unregistered\n from zope.interface.registry import HandlerRegistration\n\n class IFoo(InterfaceClass):\n pass\n ifoo = IFoo('IFoo')\n\n class _Factory(object):\n __component_adapts__ = (ifoo,)\n\n def __init__(self, context):\n self._context = context\n comp = self._makeOne()\n comp.registerHandler(_Factory)\n _monkey, _events = self._wrapEvents()\n with _monkey:\n unreg = comp.unregisterHandler(_Factory)\n self.assertTrue(unreg)\n self.assertEqual(len(_events), 1)\n args, kw = _events[0]\n event, = args\n self.assertEqual(kw, {})\n self.assertTrue(isinstance(event, Unregistered))\n self.assertTrue(isinstance(event.object, HandlerRegistration))\n self.assertTrue(event.object.registry is comp)\n self.assertEqual(event.object.required, (ifoo,))\n self.assertEqual(event.object.name, '')\n self.assertEqual(event.object.info, '')\n self.assertTrue(event.object.factory is _Factory)\n", "method_code": " def unregisterHandler(self, factory=None, required=None, name=u''):\n if name:\n raise TypeError('Named subscribers are not yet supported')\n if required is None and factory is None:\n raise TypeError('Must specify one of factory and required')\n required = _getAdapterRequired(factory, required)\n if factory is None:\n new = [(r, n, f, i) for r, n, f, i in self._handler_registrations if r != required]\n else:\n new = [(r, n, f, i) for r, n, f, i in self._handler_registrations if not (r == required and f == factory)]\n if len(new) == len(self._handler_registrations):\n return False\n self._handler_registrations[:] = new\n self.adapters.unsubscribe(required, None, factory)\n notify(Unregistered(HandlerRegistration(self, required, name, factory, '')))\n return True\n ", "context": "class Components(object):\n def unregisterHandler(self, factory=None, required=None, name=u''): ...\n def __init__(self, name='', bases=()): ...\n def __repr__(self): ...\n def _init_registries(self): ...\n def _init_registrations(self): ...\n def _getBases(self): ...\n def _setBases(self, bases): ...\n def registerUtility(self, component=None, provided=None, name=u'', info=u'', event=True, factory=None): ...\n def unregisterUtility(self, component=None, provided=None, name=u'', factory=None): ...\n def registeredUtilities(self): ...\n def queryUtility(self, provided, name=u'', default=None): ...\n def getUtility(self, provided, name=u''): ...\n def getUtilitiesFor(self, interface): ...\n def getAllUtilitiesRegisteredFor(self, interface): ...\n def registerAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def unregisterAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def registeredAdapters(self): ...\n def queryAdapter(self, object, interface, name=u'', default=None): ...\n def getAdapter(self, object, interface, name=u''): ...\n def queryMultiAdapter(self, objects, interface, name=u'', default=None): ...\n def getMultiAdapter(self, objects, interface, name=u''): ...\n def getAdapters(self, objects, provided): ...\n def registerSubscriptionAdapter(self, factory, required=None, provided=None, name=u'', info=u'', event=True): ...\n def registeredSubscriptionAdapters(self): ...\n def unregisterSubscriptionAdapter(self, factory=None, required=None, provided=None, name=u''): ...\n def subscribers(self, objects, provided): ...\n def registerHandler(self, factory, required=None, name=u'', info=u'', event=True): ...\n def registeredHandlers(self): ...\n def handle(self, *objects): ...\n\n self.__name__ = name\n self.__bases__ = tuple(bases)\n\n __bases__ = property(lambda self: self._getBases(), lambda self, bases: self._setBases(bases))\n", "repository": "designspired/TaskManagerGAE", "test_name": "test_unregisterHandler_miss", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000182.py"} {"focal_file": "lib/zope/interface/registry.py", "focal_class": null, "focal_method": "__hash__", "tests": "import unittest\n\nclass Test_hash(unittest.TestCase):\n def test___hash__(self):\n _component = object()\n ar, _registry, _name = self._makeOne(_component)\n self.assertEqual(ar.__hash__(), id(ar))\n", "method_code": " def __hash__(self):\n return id(self)\n ", "context": "class UtilityRegistration(object):\n def __hash__(self): ...\n def __init__(self, registry, provided, name, component, doc, factory=None): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __lt__(self, other): ...\n def __le__(self, other): ...\n def __gt__(self, other): ...\n def __ge__(self, other): ...\n\n self.registry, self.provided, self.name, self.component, self.info, self.factory = (registry, provided, name, component, doc, factory)\n", "repository": "designspired/TaskManagerGAE", "test_name": "test___hash__", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000183.py"} {"focal_file": "atoman/algebra/vectors.py", "focal_class": null, "focal_method": "magnitude", "tests": "import unittest\n\nclass Test_magnitude(unittest.TestCase):\n def test_magnitude(self):\n \"\"\"\n Vector magnitude\n\n \"\"\"\n vect = np.asarray([1.8, 5.4, 2.2, 0.0, 0.2], dtype=np.float64)\n mag = _vectors.magnitude(vect)\n self.assertAlmostEqual(mag, 6.1057350089895)\n\n def test_magnitudeCfNump(self):\n \"\"\"\n Vector magnitude cf. NumPy\n\n \"\"\"\n vect = np.random.rand(100)\n mag = _vectors.magnitude(vect)\n self.assertAlmostEqual(mag, np.linalg.norm(vect))\n", "method_code": "def magnitude(vect):\n \"\"\"\n Return magnitude of vect\n \n \"\"\"\n return c_vectors.magnitude(vect)", "context": "def magnitude(vect): ...\ndef magnitude(vect): ...\ndef normalise(vect): ...\ndef separationVector(pos1, pos2, cellDimsTmp, PBC): ...\ndef separation(pos1, pos2, cellDimsTmp, PBC): ...\n", "repository": "chrisdjscott/Atoman", "test_name": "test_magnitude", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000184.py"} {"focal_file": "atoman/algebra/vectors.py", "focal_class": null, "focal_method": "separationVector", "tests": "import unittest\n\nclass Test_separationVector(unittest.TestCase):\n def test_separationVector(self):\n \"\"\"\n Vector separation vector\n\n \"\"\"\n cellDims = np.asarray([100, 0, 0, 0, 100, 0, 0, 0, 100], dtype=np.float64)\n p1 = np.asarray([1.0, 1.0, 1.0], dtype=np.float64)\n p2 = np.asarray([11.0, 5.0, 0.0], dtype=np.float64)\n sepVec = np.empty(3, np.float64)\n status = _vectors.separationVector(sepVec, p1, p2, cellDims, np.ones(3, np.int32))\n self.assertEqual(status, 0)\n self.assertEqual(sepVec[0], 10)\n self.assertEqual(sepVec[1], 4)\n self.assertEqual(sepVec[2], -1)\n\n def test_separationVectorPBC(self):\n \"\"\"\n Vector separation vector PBC\n\n \"\"\"\n cellDims = np.asarray([100, 0, 0, 0, 100, 0, 0, 0, 100], dtype=np.float64)\n p1 = np.asarray([1.0, 1.0, 1.0], dtype=np.float64)\n p2 = np.asarray([99, 99, 99], dtype=np.float64)\n sepVec = np.empty(3, np.float64)\n status = _vectors.separationVector(sepVec, p1, p2, cellDims, np.ones(3, np.int32))\n self.assertEqual(status, 0)\n self.assertEqual(sepVec[0], -2)\n self.assertEqual(sepVec[1], -2)\n self.assertEqual(sepVec[2], -2)\n", "method_code": "def separationVector(pos1, pos2, cellDimsTmp, PBC):\n \"\"\"\n Return separation vector between position vectors pos1 and pos2.\n i.e. pos2 - pos1\n \n \"\"\"\n sepVec = np.empty(len(pos1), np.float64)\n cellDims = np.zeros(9, np.float64)\n cellDims[0] = cellDimsTmp[0]\n cellDims[4] = cellDimsTmp[1]\n cellDims[8] = cellDimsTmp[2]\n c_vectors.separationVector(sepVec, pos1, pos2, cellDims, PBC)\n return sepVec", "context": "def separationVector(pos1, pos2, cellDimsTmp, PBC): ...\ndef magnitude(vect): ...\ndef normalise(vect): ...\ndef separationVector(pos1, pos2, cellDimsTmp, PBC): ...\ndef separation(pos1, pos2, cellDimsTmp, PBC): ...\n", "repository": "chrisdjscott/Atoman", "test_name": "test_separationVector", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000185.py"} {"focal_file": "atoman/filtering/clusters.py", "focal_class": null, "focal_method": "makeClusterPos", "tests": "import unittest\n\nclass Test_makeClusterPos(unittest.TestCase):\n def test_atomCluster(self):\n \"\"\"\n AtomCluster\n\n \"\"\"\n cluster = clusters.AtomCluster(self.lattice)\n cluster.addAtom(0)\n cluster.addAtom(2)\n cluster.addAtom(5)\n cluster.addAtom(7)\n self.assertEqual(len(cluster), 4)\n self.assertEqual(cluster[0], 0)\n self.assertEqual(cluster[1], 2)\n self.assertEqual(cluster[2], 5)\n self.assertEqual(cluster[3], 7)\n self.assertTrue(0 in cluster)\n self.assertTrue(2 in cluster)\n self.assertTrue(5 in cluster)\n self.assertTrue(7 in cluster)\n pos = cluster.makeClusterPos()\n expectedPos = np.asarray([0, 0, 0, 3, 0, 0, 1.5, 3, 0, 1.5, 1.5, 3], dtype=np.float64)\n self.assertEqual(len(pos), len(expectedPos))\n for p1, p2 in zip(pos, expectedPos):\n self.assertEqual(p1, p2)\n cluster._facetArea = 44.3\n self.assertEqual(cluster.getFacetArea(), 44.3)\n cluster._facetArea = None\n cluster._volume = 11.6\n self.assertEqual(cluster.getVolume(), 11.6)\n cluster._volume = None\n\n def test_defectCluster(self):\n \"\"\"\n DefectCluster\n\n \"\"\"\n cluster = clusters.DefectCluster(self.inp, self.ref)\n cluster.addInterstitial(0)\n cluster.addSplitInterstitial(2, 4, 7)\n cluster.addVacancy(1)\n cluster.addVacancy(6)\n cluster.addAntisite(5, 3)\n cluster.addAntisite(3, 5)\n self.assertEqual(cluster.getNDefects(), 6)\n self.assertEqual(cluster.getNDefectsFull(), 8)\n self.assertEqual(cluster.getNVacancies(), 2)\n self.assertEqual(cluster.getNInterstitials(), 1)\n self.assertEqual(cluster.getNAntisites(), 2)\n self.assertEqual(cluster.getNSplitInterstitials(), 1)\n self.assertEqual(cluster.getVacancy(0), 1)\n self.assertEqual(cluster.getVacancy(1), 6)\n self.assertEqual(cluster.getInterstitial(0), 0)\n self.assertEqual(cluster.getAntisite(0)[0], 5)\n self.assertEqual(cluster.getAntisite(0)[1], 3)\n self.assertEqual(cluster.getAntisite(1)[0], 3)\n self.assertEqual(cluster.getAntisite(1)[1], 5)\n self.assertEqual(cluster.getSplitInterstitial(0)[0], 2)\n self.assertEqual(cluster.getSplitInterstitial(0)[1], 4)\n self.assertEqual(cluster.getSplitInterstitial(0)[2], 7)\n pos = cluster.makeClusterPos()\n expectedPos = np.asarray([3, 0, 0, 3, 0, 3, 0, 3, 3, 0, 0, 3, 0, 0, 0, 0, 3, 0, 3, 3, 0, 3, 3, 3], dtype=np.float64)\n self.assertEqual(len(pos), len(expectedPos))\n for p1, p2 in zip(pos, expectedPos):\n self.assertEqual(p1, p2)\n", "method_code": " def makeClusterPos(self):\n \"\"\"Returns an array of positions of atoms in the cluster.\"\"\"\n num = len(self._indexes)\n lattice = self._lattice\n clusterPos = np.empty(3 * num, np.float64)\n for i in range(num):\n index = self._indexes[i]\n i3 = 3 * i\n ind3 = 3 * index\n clusterPos[i3] = lattice.pos[ind3]\n clusterPos[i3 + 1] = lattice.pos[ind3 + 1]\n clusterPos[i3 + 2] = lattice.pos[ind3 + 2]\n return clusterPos\n ", "context": "class AtomCluster(object):\n def makeClusterPos(self): ...\n def __init__(self, lattice): ...\n def __len__(self): ...\n def __getitem__(self, i): ...\n def __contains__(self, item): ...\n def getSpeciesCount(self): ...\n def addAtom(self, index): ...\n def getLattice(self): ...\n def getVolume(self): ...\n def getFacetArea(self): ...\n def calculateVolume(self, voronoiCalculator, settings): ...\n def _calculateVolumeVoronoi(self, voronoiCalculator): ...\n def _calculateVolumeConvexHull(self, settings): ...\n\n self._indexes = []\n self._volume = None\n self._facetArea = None\n self._lattice = lattice\n", "repository": "chrisdjscott/Atoman", "test_name": "test_atomCluster", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000186.py"} {"focal_file": "atoman/filtering/clusters.py", "focal_class": null, "focal_method": "findConvexHullVolume", "tests": "import unittest\n\nclass Test_findConvexHullVolume(unittest.TestCase):\n def test_convexHullVolume(self):\n \"\"\"\n Convex hull volume\n\n \"\"\"\n N = 8\n pts = [0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 3, 0, 0, 3, 3, 3, 0, 3, 3, 3, 3]\n volume, facetArea = clusters.findConvexHullVolume(N, pts)\n self.assertAlmostEqual(volume, 27.0)\n", "method_code": "def findConvexHullVolume(N, pos, posIsPts=False):\n \"\"\"\n Find convex hull of given points\n \n \"\"\"\n if posIsPts:\n pts = pos\n else:\n pts = np.empty((N, 3), dtype=np.float64)\n for i in range(N):\n i3 = 3 * i\n pts[i][0] = pos[i3]\n pts[i][1] = pos[i3 + 1]\n pts[i][2] = pos[i3 + 2]\n if PYHULL_LOADED:\n volume, facetArea = convex_hull_volume_pyhull(pts)\n else:\n volume = convex_hull_volume_bis(pts)\n facetArea = None\n return (volume, facetArea)", "context": "def findConvexHullVolume(N, pos, posIsPts=False): ...\ndef findConvexHullFacets(num, pos): ...\ndef tetrahedron_volume(a, b, c, d): ...\ndef convex_hull_volume(pts): ...\ndef convex_hull_volume_bis(pts): ...\ndef convex_hull_volume_pyhull(pts): ...\ndef findConvexHullVolume(N, pos, posIsPts=False): ...\ndef applyPBCsToCluster(clusterPos, cellDims, appliedPBCs): ...\ndef checkFacetsPBCs(facetsIn, clusterPos, excludeRadius, PBC, cellDims): ...\n", "repository": "chrisdjscott/Atoman", "test_name": "test_convexHullVolume", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000187.py"} {"focal_file": "atoman/plotting/rdf.py", "focal_class": null, "focal_method": "calculateRDF", "tests": "import unittest\n\nclass Test_calculateRDF(unittest.TestCase):\n def test_calculateRDF(self):\n \"\"\"\n Calculate RDF\n\n \"\"\"\n calc = rdf.RDFCalculator()\n _preferences.setNumThreads(1)\n xvals, yvals = calc.calculateRDF(self.visAtoms, self.lattice, 2.0, 15.0, 0.1, -1, -1)\n self.assertTrue(np.allclose(xvals, self.allres[0]), msg='RDF xvals differ for ALL-ALL 1 proc')\n self.assertTrue(np.allclose(yvals, self.allres[1]), msg='RDF yvals differ for ALL-ALL 1 proc')\n _preferences.setNumThreads(4)\n xvals, yvals = calc.calculateRDF(self.visAtoms, self.lattice, 2.0, 15.0, 0.1, -1, -1)\n self.assertTrue(np.allclose(xvals, self.allres[0]), msg='RDF xvals differ for ALL-ALL 4 proc')\n self.assertTrue(np.allclose(yvals, self.allres[1]), msg='RDF yvals differ for ALL-ALL 4 proc')\n _preferences.setNumThreads(1)\n with self.assertRaises(RuntimeError):\n calc.calculateRDF(self.visAtoms, self.lattice, 2.0, 50.0, 0.1, -1, -1)\n", "method_code": " def calculateRDF(self, visibleAtoms, inputLattice, binMin, binMax, binWidth, speciesIndex1, speciesIndex2):\n \"\"\"\n Calculate the radial distribution function for the given selection of atoms.\n \n Parameters\n ----------\n visibleAtoms : numpy.ndarray\n Array containing the indices of atoms that are currently visible.\n inputLattice : Lattice\n Lattice object containing positions of atoms, etc.\n binMin : float\n The minimum separation to consider when constructing the histogram.\n binMin : float\n The maximum separation to consider when constructing the histogram.\n binWidth : float\n The separation between bins.\n speciesIndex1 : int\n The index of species of atom in the first selection.\n speciesIndex2 : int\n The index of species of atom in the second selection.\n numThreads : int, optional\n The number of threads to run on (default is to use all available).\n \n \"\"\"\n logger = logging.getLogger(__name__)\n logger.debug('Calculating RDF')\n warnDims = []\n if inputLattice.PBC[0] and binMax > inputLattice.cellDims[0] / 2.0:\n warnDims.append('x')\n if inputLattice.PBC[1] and binMax > inputLattice.cellDims[1] / 2.0:\n warnDims.append('y')\n if inputLattice.PBC[2] and binMax > inputLattice.cellDims[2] / 2.0:\n warnDims.append('z')\n if len(warnDims):\n msg = 'The maximum radius you have requested is greater than half the box length '\n msg += 'in the %s periodic direction(s)!' % ','.join(warnDims)\n raise RuntimeError('RDFCalculator: %s' % msg)\n numBins = int((binMax - binMin) / binWidth)\n logger.debug('Bin width is %f; number of bins is %d', binWidth, numBins)\n rdfArray = np.zeros(numBins, np.float64)\n _rdf.calculateRDF(visibleAtoms, inputLattice.specie, inputLattice.pos, speciesIndex1, speciesIndex2, inputLattice.cellDims, inputLattice.PBC, binMin, binMax, binWidth, numBins, rdfArray)\n xvals = np.arange(binMin + binWidth / 2.0, binMax, binWidth, dtype=np.float64)\n return (xvals, rdfArray)\n ", "context": "class RDFCalculator(object):\n def calculateRDF(self, visibleAtoms, inputLattice, binMin, binMax, binWidth, speciesIndex1, speciesIndex2): ...", "repository": "chrisdjscott/Atoman", "test_name": "test_calculateRDF", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000188.py"} {"focal_file": "atoman/rendering/renderers/bondRenderer.py", "focal_class": null, "focal_method": "calculateBonds", "tests": "import unittest\n\nclass Test_calculateBonds(unittest.TestCase):\n def test_bondCalculator(self):\n \"\"\"\n Bond calculator\n\n \"\"\"\n visibleAtoms = np.arange(self.lattice.NAtoms, dtype=np.int32)\n scalars = utils.NumpyVTKData(self.lattice.specie.astype(np.float64), name='colours')\n bondMinArray = np.zeros((3, 3), dtype=np.float64)\n bondMaxArray = np.zeros((3, 3), dtype=np.float64)\n bondMaxArray[0][2] = 2.1\n bondMaxArray[2][0] = 2.1\n bondMaxArray[1][2] = 2.1\n bondMaxArray[2][1] = 2.1\n drawList = ['Si-O_', 'B_-O_']\n bondCalc = bondRenderer.BondCalculator()\n result = bondCalc.calculateBonds(self.lattice, visibleAtoms, scalars, bondMinArray, bondMaxArray, drawList)\n bondCoords, bondVectors, bondScalars, bondSpecieCounter = result\n self.assertIsInstance(bondCoords, utils.NumpyVTKData)\n self.assertIsInstance(bondVectors, utils.NumpyVTKData)\n self.assertIsInstance(bondScalars, utils.NumpyVTKData)\n coords = bondCoords.getNumpy()\n vectors = bondCoords.getNumpy()\n scalars = bondCoords.getNumpy()\n self.assertEqual(coords.shape[0], 2964)\n self.assertEqual(coords.shape[1], 3)\n self.assertEqual(vectors.shape[0], 2964)\n self.assertEqual(vectors.shape[1], 3)\n self.assertEqual(scalars.shape[0], 2964)\n self.assertEqual(bondSpecieCounter[0][0], 0)\n self.assertEqual(bondSpecieCounter[1][1], 0)\n self.assertEqual(bondSpecieCounter[2][2], 0)\n self.assertEqual(bondSpecieCounter[0][1], 0)\n self.assertEqual(bondSpecieCounter[1][0], 0)\n self.assertEqual(bondSpecieCounter[0][2], 1118)\n self.assertEqual(bondSpecieCounter[2][0], 1118)\n self.assertEqual(bondSpecieCounter[1][2], 364)\n self.assertEqual(bondSpecieCounter[2][1], 364)\n", "method_code": " def calculateBonds(self, inputState, visibleAtoms, scalarsArray, bondMinArray, bondMaxArray, drawList, maxBondsPerAtom=50):\n \"\"\"Find bonds.\"\"\"\n self._logger.info('Calculating bonds')\n nvis = len(visibleAtoms)\n nspecs = len(inputState.specieList)\n size = int(nvis * maxBondsPerAtom / 2)\n bondArray = np.empty(size, np.int32)\n NBondsArray = np.zeros(nvis, np.int32)\n bondVectorArray = np.empty(3 * size, np.float64)\n bondSpecieCounter = np.zeros((nspecs, nspecs), dtype=np.int32)\n maxBond = bondMaxArray.max()\n status = bonds.calculateBonds(visibleAtoms, inputState.pos, inputState.specie, len(inputState.specieList), bondMinArray, bondMaxArray, maxBond, maxBondsPerAtom, inputState.cellDims, inputState.PBC, bondArray, NBondsArray, bondVectorArray, bondSpecieCounter)\n if status:\n if status == 1:\n msg = 'Max bonds per atom exceeded! This would suggest you bond range is too big!'\n else:\n msg = 'Error in bonds clib (%d)' % status\n raise RuntimeError(msg)\n NBondsTotal = np.sum(NBondsArray)\n self._logger.info('Total number of bonds: %d (x2 for actors)', NBondsTotal)\n bondArray.resize(NBondsTotal)\n bondVectorArray.resize(NBondsTotal * 3)\n res = _rendering.makeBondsArrays(visibleAtoms, scalarsArray.getNumpy(), inputState.pos, NBondsArray, bondArray, bondVectorArray)\n bondCoords, bondVectors, bondScalars = res\n bondCoords = utils.NumpyVTKData(bondCoords)\n bondVectors = utils.NumpyVTKData(bondVectors, name='vectors')\n bondScalars = utils.NumpyVTKData(bondScalars, name='colours')\n specieList = inputState.specieList\n for i in range(nspecs):\n syma = specieList[i]\n for j in range(i, nspecs):\n symb = specieList[j]\n pairStr = '%s-%s' % (syma, symb)\n pairStr2 = '%s-%s' % (symb, syma)\n if pairStr in drawList or pairStr2 in drawList:\n NBondsPair = bondSpecieCounter[i][j]\n if i != j:\n NBondsPair += bondSpecieCounter[j][i]\n bondSpecieCounter[i][j] = NBondsPair\n bondSpecieCounter[j][i] = NBondsPair\n self._logger.info('%d %s - %s bonds', NBondsPair, syma, symb)\n return (bondCoords, bondVectors, bondScalars, bondSpecieCounter)\n ", "context": "class BondCalculator(object):\n def calculateBonds(self, inputState, visibleAtoms, scalarsArray, bondMinArray, bondMaxArray, drawList, maxBondsPerAtom=50): ...\n def __init__(self): ...\n\n self._logger = logging.getLogger(__name__ + '.BondCalculator')\n", "repository": "chrisdjscott/Atoman", "test_name": "test_bondCalculator", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000189.py"} {"focal_file": "atoman/rendering/renderers/bondRenderer.py", "focal_class": null, "focal_method": "render", "tests": "import unittest\n\nclass Test_render(unittest.TestCase):\n def test_bondRenderer(self):\n \"\"\"\n Bond renderer\n\n \"\"\"\n colouringOptions = DummyColouringOpts()\n bondsOptions = DummyBondsOpts()\n bondRend = bondRenderer.BondRenderer()\n bondRend.render(self.bondCoords, self.bondVectors, self.bondScalars, self.nspecies, colouringOptions, bondsOptions, self.lut)\n self.assertIsInstance(bondRend.getActor(), utils.ActorObject)\n", "method_code": " def render(self, bondCoords, bondVectors, bondScalars, numSpecies, colouringOptions, bondsOptions, lut):\n \"\"\"\n Render the given bonds.\n \n \"\"\"\n self._logger.debug('Rendering bonds')\n renderBondsTime = time.time()\n bondThicknessVTK = bondsOptions.bondThicknessVTK\n bondNumSides = bondsOptions.bondNumSides\n bondPoints = vtk.vtkPoints()\n bondPoints.SetData(bondCoords.getVTK())\n bondPolyData = vtk.vtkPolyData()\n bondPolyData.SetPoints(bondPoints)\n bondPolyData.GetPointData().SetScalars(bondScalars.getVTK())\n bondPolyData.GetPointData().SetVectors(bondVectors.getVTK())\n lineSource = vtk.vtkLineSource()\n tubes = vtk.vtkTubeFilter()\n tubes.SetInputConnection(lineSource.GetOutputPort())\n tubes.SetRadius(bondThicknessVTK)\n tubes.SetNumberOfSides(bondNumSides)\n tubes.SetCapping(1)\n bondGlyphFilter = vtk.vtkProgrammableGlyphFilter()\n bondGlyphFilter.SetGlyphMethod(functools.partial(_bondGlyphMethod, bondGlyphFilter, lineSource))\n if vtk.vtkVersion.GetVTKMajorVersion() <= 5:\n bondGlyphFilter.SetSource(tubes.GetOutput())\n bondGlyphFilter.SetInput(bondPolyData)\n else:\n bondGlyphFilter.SetSourceConnection(tubes.GetOutputPort())\n bondGlyphFilter.SetInputData(bondPolyData)\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(bondGlyphFilter.GetOutputPort())\n mapper.SetLookupTable(lut)\n utils.setMapperScalarRange(mapper, colouringOptions, numSpecies)\n actor = vtk.vtkActor()\n actor.SetMapper(mapper)\n actor.GetProperty().SetOpacity(1)\n actor.GetProperty().SetLineWidth(bondThicknessVTK)\n renderBondsTime = time.time() - renderBondsTime\n self._logger.debug('Render bonds time: %f s', renderBondsTime)\n self._actor = utils.ActorObject(actor)\n self._data['Points'] = bondCoords\n self._data['Scalars'] = bondScalars\n self._data['Vectors'] = bondVectors\n self._data['LUT'] = lut\n self._data['Bond thickness'] = bondsOptions.bondThicknessPOV\n ", "context": "class BondRenderer(baseRenderer.BaseRenderer):\n def render(self, bondCoords, bondVectors, bondScalars, numSpecies, colouringOptions, bondsOptions, lut): ...\n def __init__(self): ...\n def writePovray(self, filename): ...\n\n self._logger = logging.getLogger(__name__ + '.BondRenderer')\n", "repository": "chrisdjscott/Atoman", "test_name": "test_bondRenderer", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000190.py"} {"focal_file": "atoman/rendering/renderers/bondRenderer.py", "focal_class": null, "focal_method": "calculateDisplacementVectors", "tests": "import unittest\n\nclass Test_calculateDisplacementVectors(unittest.TestCase):\n def test_calculateDisplacementVectors(self):\n \"\"\"\n Displacement vector calculator\n\n \"\"\"\n calc = bondRenderer.DisplacmentVectorCalculator()\n result = calc.calculateDisplacementVectors(self.inputState.pos, self.refState.pos, self.inputState.PBC, self.inputState.cellDims, self.visibleAtoms, self.scalars)\n bondCoords, bondVectors, bondScalars = result\n self.assertIsInstance(bondCoords, utils.NumpyVTKData)\n self.assertIsInstance(bondVectors, utils.NumpyVTKData)\n self.assertIsInstance(bondScalars, utils.NumpyVTKData)\n coords = bondCoords.getNumpy()\n vectors = bondVectors.getNumpy()\n scalars = bondScalars.getNumpy()\n self.assertEqual(len(coords.shape), 2)\n self.assertEqual(coords.shape[0], 2)\n self.assertEqual(coords.shape[1], 3)\n self.assertEqual(len(vectors.shape), 2)\n self.assertEqual(vectors.shape[0], 2)\n self.assertEqual(vectors.shape[1], 3)\n self.assertEqual(len(scalars.shape), 1)\n self.assertEqual(scalars.shape[0], 2)\n self.assertTrue(np.array_equal(coords[0], [2, 1, 3]))\n self.assertTrue(np.array_equal(coords[1], [4, 2, 4]))\n self.assertTrue(np.array_equal(vectors[0], [-2, -1, -3]))\n self.assertTrue(np.array_equal(vectors[1], [-3, 2, 1]))\n self.assertEqual(scalars[0], 0)\n self.assertEqual(scalars[1], 1)\n", "method_code": " def calculateDisplacementVectors(self, pos, refPos, pbc, cellDims, atomList, scalarsArray):\n \"\"\"Calculate displacement vectors for the set of atoms.\"\"\"\n self._logger.debug('Calculating displacement vectors')\n numAtoms = len(atomList)\n bondVectors = np.empty(3 * numAtoms, np.float64)\n drawBondVector = np.empty(numAtoms, np.int32)\n numBonds = bonds.calculateDisplacementVectors(atomList, pos, refPos, cellDims, pbc, bondVectors, drawBondVector)\n self._logger.debug('Number of displacement vectors to draw = %d (/ %d)', numBonds, numAtoms)\n res = _rendering.makeDisplacementVectorBondsArrays(numBonds, atomList, scalarsArray, pos, drawBondVector, bondVectors)\n bondCoords, bondVectors, bondScalars = res\n bondCoords = utils.NumpyVTKData(bondCoords)\n bondVectors = utils.NumpyVTKData(bondVectors, name='vectors')\n bondScalars = utils.NumpyVTKData(bondScalars, name='colours')\n return (bondCoords, bondVectors, bondScalars)\n ", "context": "class DisplacmentVectorCalculator(object):\n def calculateDisplacementVectors(self, pos, refPos, pbc, cellDims, atomList, scalarsArray): ...\n def __init__(self): ...\n\n self._logger = logging.getLogger(__name__ + '.DisplacmentVectorCalculator')\n", "repository": "chrisdjscott/Atoman", "test_name": "test_calculateDisplacementVectors", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000191.py"} {"focal_file": "atoman/system/lattice.py", "focal_class": null, "focal_method": "wrapAtoms", "tests": "import unittest\n\nclass Test_wrapAtoms(unittest.TestCase):\n def test_wrapAtoms(self):\n \"\"\"\n Lattice wrapAtoms\n\n \"\"\"\n self.lattice.pos[2] += self.lattice.cellDims[2]\n self.lattice.pos[3] -= self.lattice.cellDims[0]\n self.lattice.pos[4] += self.lattice.cellDims[1]\n self.lattice.wrapAtoms()\n for i in range(self.lattice.NAtoms):\n i3 = 3 * i\n for j in range(3):\n pos = self.lattice.pos[i3 + j]\n self.assertTrue(pos <= self.lattice.cellDims[0] and self.lattice.pos[3 * i + j] >= 0.0)\n", "method_code": " def wrapAtoms(self):\n \"\"\"\n Wrap atoms that have left the periodic cell.\n \n \"\"\"\n return _lattice.wrapAtoms(self.NAtoms, self.pos, self.cellDims, self.PBC)\n ", "context": "class Lattice(object):\n def wrapAtoms(self): ...\n def __init__(self): ...\n def atomSeparation(self, index1, index2, pbc): ...\n def reset(self, NAtoms): ...\n def calcTemperature(self, NMoving=None): ...\n def density(self): ...\n def volume(self): ...\n def addSpecie(self, sym, count=None): ...\n def addAtom(self, sym, pos, charge, atomID=None, scalarVals={}, vectorVals={}): ...\n def removeAtom(self, index): ...\n def removeSpecie(self, index): ...\n def calcForce(self, forceConfig): ...\n def atomPos(self, index): ...\n def atomSym(self, index): ...\n def getSpecieIndex(self, sym): ...\n def setDims(self, dimsarray): ...\n def refreshElementProperties(self): ...\n def toLKMC(self, storeEnergies=False): ...\n def writeLattice(self, filename, visibleAtoms=None): ...\n def clone(self, lattice): ...\n\n self.NAtoms = 0\n self.cellDims = np.array([100, 100, 100], np.float64)\n self.specieList = []\n self.specieCount = np.empty(0, np.int32)\n self.specieMass = np.empty(0, np.float64)\n self.specieCovalentRadius = np.empty(0, np.float64)\n self.specieRGB = np.empty((0, 3), np.float64)\n self.specieAtomicNumber = np.empty(0, np.int32)\n self.minPos = np.zeros(3, np.float64)\n self.maxPos = np.zeros(3, np.float64)\n self.atomID = np.empty(0, np.int32)\n self.specie = np.empty(0, np.int32)\n self.pos = np.empty(0, np.float64)\n self.charge = np.empty(0, np.float64)\n self.scalarsDict = {}\n self.scalarsFiles = {}\n self.vectorsDict = {}\n self.vectorsFiles = {}\n self.attributes = {}\n self.PBC = np.ones(3, np.int32)\n", "repository": "chrisdjscott/Atoman", "test_name": "test_wrapAtoms", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000192.py"} {"focal_file": "atoman/system/lattice.py", "focal_class": null, "focal_method": "atomSeparation", "tests": "import unittest\n\nclass Test_atomSeparation(unittest.TestCase):\n def test_atomSeparation(self):\n \"\"\"\n Lattice atomSeparation\n\n \"\"\"\n sep = self.lattice.atomSeparation(0, self.lattice.NAtoms - 1, np.ones(3, np.int32))\n self.assertAlmostEqual(sep, 4.9945095855)\n with self.assertRaises(IndexError):\n self.lattice.atomSeparation(0, self.lattice.NAtoms, np.ones(3, np.int32))\n with self.assertRaises(IndexError):\n self.lattice.atomSeparation(self.lattice.NAtoms, 0, np.ones(3, np.int32))\n", "method_code": " def atomSeparation(self, index1, index2, pbc):\n \"\"\"\n Calculate the separation between two atoms.\n \n Parameters\n ----------\n index1, index2 : integer\n Indexes of the atoms you want to calculate the separation\n between.\n \n \n Returns\n -------\n atomSeparation : float\n The separation between the two atoms. This function will\n return 'None' if the indexes are out of range.\n \n Raises\n ------\n IndexError\n If the specified indexes are too large.\n \n \"\"\"\n if index1 < self.NAtoms and index2 < self.NAtoms:\n atomSeparation = vectors.separation(self.atomPos(index1), self.atomPos(index2), self.cellDims, pbc)\n else:\n raise IndexError('Atom index(es) out of range: (%d or %d) >= %d' % (index1, index2, self.NAtoms))\n return atomSeparation\n ", "context": "class Lattice(object):\n def atomSeparation(self, index1, index2, pbc): ...\n def __init__(self): ...\n def wrapAtoms(self): ...\n def reset(self, NAtoms): ...\n def calcTemperature(self, NMoving=None): ...\n def density(self): ...\n def volume(self): ...\n def addSpecie(self, sym, count=None): ...\n def addAtom(self, sym, pos, charge, atomID=None, scalarVals={}, vectorVals={}): ...\n def removeAtom(self, index): ...\n def removeSpecie(self, index): ...\n def calcForce(self, forceConfig): ...\n def atomPos(self, index): ...\n def atomSym(self, index): ...\n def getSpecieIndex(self, sym): ...\n def setDims(self, dimsarray): ...\n def refreshElementProperties(self): ...\n def toLKMC(self, storeEnergies=False): ...\n def writeLattice(self, filename, visibleAtoms=None): ...\n def clone(self, lattice): ...\n\n self.NAtoms = 0\n self.cellDims = np.array([100, 100, 100], np.float64)\n self.specieList = []\n self.specieCount = np.empty(0, np.int32)\n self.specieMass = np.empty(0, np.float64)\n self.specieCovalentRadius = np.empty(0, np.float64)\n self.specieRGB = np.empty((0, 3), np.float64)\n self.specieAtomicNumber = np.empty(0, np.int32)\n self.minPos = np.zeros(3, np.float64)\n self.maxPos = np.zeros(3, np.float64)\n self.atomID = np.empty(0, np.int32)\n self.specie = np.empty(0, np.int32)\n self.pos = np.empty(0, np.float64)\n self.charge = np.empty(0, np.float64)\n self.scalarsDict = {}\n self.scalarsFiles = {}\n self.vectorsDict = {}\n self.vectorsFiles = {}\n self.attributes = {}\n self.PBC = np.ones(3, np.int32)\n", "repository": "chrisdjscott/Atoman", "test_name": "test_atomSeparation", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000193.py"} {"focal_file": "atoman/system/lattice.py", "focal_class": null, "focal_method": "calcTemperature", "tests": "import unittest\n\nclass Test_calcTemperature(unittest.TestCase):\n def test_calcTemperature(self):\n \"\"\"\n Lattice calcTemperature\n\n \"\"\"\n self.assertIsNone(self.lattice.calcTemperature())\n ke = np.asarray([0.1, 0.3, 0.2], dtype=np.float64)\n self.lattic3.scalarsDict['KE'] = ke\n self.assertAlmostEqual(self.lattic3.calcTemperature(), 1547.2692376742177)\n", "method_code": " def calcTemperature(self, NMoving=None):\n \"\"\"\n Calculate temperature in K\n \n \"\"\"\n logger = logging.getLogger(__name__)\n logger.debug('Calculating temperature of Lattice')\n if 'Kinetic energy' in self.scalarsDict:\n logger.debug(\"Got 'Kinetic energy' array from scalarsDict\")\n ke = self.scalarsDict['Kinetic energy']\n elif 'KE' in self.scalarsDict:\n logger.debug(\"Got 'KE' array from scalarsDict\")\n ke = self.scalarsDict['KE']\n else:\n logger.debug('No kinetic energy information stored on Lattice')\n return None\n if NMoving is None:\n NMoving = self.NAtoms\n keSum = np.sum(ke)\n if keSum == 0:\n temperature = 0.0\n else:\n boltzmann = 8.6173324e-05\n temperature = 2.0 * keSum / (3.0 * boltzmann * NMoving)\n return temperature\n ", "context": "class Lattice(object):\n def calcTemperature(self, NMoving=None): ...\n def __init__(self): ...\n def wrapAtoms(self): ...\n def atomSeparation(self, index1, index2, pbc): ...\n def reset(self, NAtoms): ...\n def density(self): ...\n def volume(self): ...\n def addSpecie(self, sym, count=None): ...\n def addAtom(self, sym, pos, charge, atomID=None, scalarVals={}, vectorVals={}): ...\n def removeAtom(self, index): ...\n def removeSpecie(self, index): ...\n def calcForce(self, forceConfig): ...\n def atomPos(self, index): ...\n def atomSym(self, index): ...\n def getSpecieIndex(self, sym): ...\n def setDims(self, dimsarray): ...\n def refreshElementProperties(self): ...\n def toLKMC(self, storeEnergies=False): ...\n def writeLattice(self, filename, visibleAtoms=None): ...\n def clone(self, lattice): ...\n\n self.NAtoms = 0\n self.cellDims = np.array([100, 100, 100], np.float64)\n self.specieList = []\n self.specieCount = np.empty(0, np.int32)\n self.specieMass = np.empty(0, np.float64)\n self.specieCovalentRadius = np.empty(0, np.float64)\n self.specieRGB = np.empty((0, 3), np.float64)\n self.specieAtomicNumber = np.empty(0, np.int32)\n self.minPos = np.zeros(3, np.float64)\n self.maxPos = np.zeros(3, np.float64)\n self.atomID = np.empty(0, np.int32)\n self.specie = np.empty(0, np.int32)\n self.pos = np.empty(0, np.float64)\n self.charge = np.empty(0, np.float64)\n self.scalarsDict = {}\n self.scalarsFiles = {}\n self.vectorsDict = {}\n self.vectorsFiles = {}\n self.attributes = {}\n self.PBC = np.ones(3, np.int32)\n", "repository": "chrisdjscott/Atoman", "test_name": "test_calcTemperature", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000194.py"} {"focal_file": "atoman/system/lattice.py", "focal_class": null, "focal_method": "density", "tests": "import unittest\n\nclass Test_density(unittest.TestCase):\n def test_density(self):\n \"\"\"\n Lattice density\n\n \"\"\"\n dens = self.lattice.density()\n self.assertAlmostEqual(dens, 0.0589818414)\n", "method_code": " def density(self):\n \"\"\"\n Return density of lattice\n \n \"\"\"\n vol = self.volume()\n if vol == 0:\n return\n return self.NAtoms / vol\n ", "context": "class Lattice(object):\n def density(self): ...\n def __init__(self): ...\n def wrapAtoms(self): ...\n def atomSeparation(self, index1, index2, pbc): ...\n def reset(self, NAtoms): ...\n def calcTemperature(self, NMoving=None): ...\n def volume(self): ...\n def addSpecie(self, sym, count=None): ...\n def addAtom(self, sym, pos, charge, atomID=None, scalarVals={}, vectorVals={}): ...\n def removeAtom(self, index): ...\n def removeSpecie(self, index): ...\n def calcForce(self, forceConfig): ...\n def atomPos(self, index): ...\n def atomSym(self, index): ...\n def getSpecieIndex(self, sym): ...\n def setDims(self, dimsarray): ...\n def refreshElementProperties(self): ...\n def toLKMC(self, storeEnergies=False): ...\n def writeLattice(self, filename, visibleAtoms=None): ...\n def clone(self, lattice): ...\n\n self.NAtoms = 0\n self.cellDims = np.array([100, 100, 100], np.float64)\n self.specieList = []\n self.specieCount = np.empty(0, np.int32)\n self.specieMass = np.empty(0, np.float64)\n self.specieCovalentRadius = np.empty(0, np.float64)\n self.specieRGB = np.empty((0, 3), np.float64)\n self.specieAtomicNumber = np.empty(0, np.int32)\n self.minPos = np.zeros(3, np.float64)\n self.maxPos = np.zeros(3, np.float64)\n self.atomID = np.empty(0, np.int32)\n self.specie = np.empty(0, np.int32)\n self.pos = np.empty(0, np.float64)\n self.charge = np.empty(0, np.float64)\n self.scalarsDict = {}\n self.scalarsFiles = {}\n self.vectorsDict = {}\n self.vectorsFiles = {}\n self.attributes = {}\n self.PBC = np.ones(3, np.int32)\n", "repository": "chrisdjscott/Atoman", "test_name": "test_density", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000195.py"} {"focal_file": "atoman/system/lattice.py", "focal_class": null, "focal_method": "volume", "tests": "import unittest\n\nclass Test_volume(unittest.TestCase):\n def test_volume(self):\n \"\"\"\n Lattice volume\n\n \"\"\"\n lattice = self.lattice\n v1 = lattice.volume()\n v2 = lattice.cellDims[0] * lattice.cellDims[1] * lattice.cellDims[2]\n self.assertEqual(v1, v2)\n", "method_code": " def volume(self):\n \"\"\"\n Return volume of lattice\n \n \"\"\"\n return self.cellDims[0] * self.cellDims[1] * self.cellDims[2]\n ", "context": "class Lattice(object):\n def volume(self): ...\n def __init__(self): ...\n def wrapAtoms(self): ...\n def atomSeparation(self, index1, index2, pbc): ...\n def reset(self, NAtoms): ...\n def calcTemperature(self, NMoving=None): ...\n def density(self): ...\n def addSpecie(self, sym, count=None): ...\n def addAtom(self, sym, pos, charge, atomID=None, scalarVals={}, vectorVals={}): ...\n def removeAtom(self, index): ...\n def removeSpecie(self, index): ...\n def calcForce(self, forceConfig): ...\n def atomPos(self, index): ...\n def atomSym(self, index): ...\n def getSpecieIndex(self, sym): ...\n def setDims(self, dimsarray): ...\n def refreshElementProperties(self): ...\n def toLKMC(self, storeEnergies=False): ...\n def writeLattice(self, filename, visibleAtoms=None): ...\n def clone(self, lattice): ...\n\n self.NAtoms = 0\n self.cellDims = np.array([100, 100, 100], np.float64)\n self.specieList = []\n self.specieCount = np.empty(0, np.int32)\n self.specieMass = np.empty(0, np.float64)\n self.specieCovalentRadius = np.empty(0, np.float64)\n self.specieRGB = np.empty((0, 3), np.float64)\n self.specieAtomicNumber = np.empty(0, np.int32)\n self.minPos = np.zeros(3, np.float64)\n self.maxPos = np.zeros(3, np.float64)\n self.atomID = np.empty(0, np.int32)\n self.specie = np.empty(0, np.int32)\n self.pos = np.empty(0, np.float64)\n self.charge = np.empty(0, np.float64)\n self.scalarsDict = {}\n self.scalarsFiles = {}\n self.vectorsDict = {}\n self.vectorsFiles = {}\n self.attributes = {}\n self.PBC = np.ones(3, np.int32)\n", "repository": "chrisdjscott/Atoman", "test_name": "test_volume", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000196.py"} {"focal_file": "atoman/system/lattice.py", "focal_class": null, "focal_method": "atomPos", "tests": "import unittest\n\nclass Test_atomPos(unittest.TestCase):\n def test_atomPos(self):\n \"\"\"\n Lattice atomPos\n\n \"\"\"\n pos = self.lattice.atomPos(11)\n self.assertEqual(pos[0], 2.039)\n self.assertEqual(pos[1], 2.039)\n self.assertEqual(pos[2], 8.156)\n", "method_code": " def atomPos(self, index):\n \"\"\"\n Return pointer to atom position within pos array: [xpos, ypos, zpos].\n \n \"\"\"\n atomPos = None\n if index < self.NAtoms:\n atomPos = self.pos[3 * index:3 * index + 3]\n return atomPos\n ", "context": "class Lattice(object):\n def atomPos(self, index): ...\n def __init__(self): ...\n def wrapAtoms(self): ...\n def atomSeparation(self, index1, index2, pbc): ...\n def reset(self, NAtoms): ...\n def calcTemperature(self, NMoving=None): ...\n def density(self): ...\n def volume(self): ...\n def addSpecie(self, sym, count=None): ...\n def addAtom(self, sym, pos, charge, atomID=None, scalarVals={}, vectorVals={}): ...\n def removeAtom(self, index): ...\n def removeSpecie(self, index): ...\n def calcForce(self, forceConfig): ...\n def atomSym(self, index): ...\n def getSpecieIndex(self, sym): ...\n def setDims(self, dimsarray): ...\n def refreshElementProperties(self): ...\n def toLKMC(self, storeEnergies=False): ...\n def writeLattice(self, filename, visibleAtoms=None): ...\n def clone(self, lattice): ...\n\n self.NAtoms = 0\n self.cellDims = np.array([100, 100, 100], np.float64)\n self.specieList = []\n self.specieCount = np.empty(0, np.int32)\n self.specieMass = np.empty(0, np.float64)\n self.specieCovalentRadius = np.empty(0, np.float64)\n self.specieRGB = np.empty((0, 3), np.float64)\n self.specieAtomicNumber = np.empty(0, np.int32)\n self.minPos = np.zeros(3, np.float64)\n self.maxPos = np.zeros(3, np.float64)\n self.atomID = np.empty(0, np.int32)\n self.specie = np.empty(0, np.int32)\n self.pos = np.empty(0, np.float64)\n self.charge = np.empty(0, np.float64)\n self.scalarsDict = {}\n self.scalarsFiles = {}\n self.vectorsDict = {}\n self.vectorsFiles = {}\n self.attributes = {}\n self.PBC = np.ones(3, np.int32)\n", "repository": "chrisdjscott/Atoman", "test_name": "test_atomPos", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000197.py"} {"focal_file": "atoman/system/lattice.py", "focal_class": null, "focal_method": "writeLattice", "tests": "import unittest\n\nclass Test_writeLattice(unittest.TestCase):\n def test_writeLattice(self):\n \"\"\"\n Lattice writeLattice\n\n \"\"\"\n with tempfile.NamedTemporaryFile() as tmpf:\n fn = tmpf.name\n self.lattice.writeLattice(fn)\n line = tmpf.readline()\n natom = int(line)\n self.assertEqual(natom, self.lattice.NAtoms)\n line = tmpf.readline()\n dims = line.split()\n self.assertEqual(float(dims[0]), self.lattice.cellDims[0])\n self.assertEqual(float(dims[1]), self.lattice.cellDims[1])\n self.assertEqual(float(dims[2]), self.lattice.cellDims[2])\n for i, line in enumerate(tmpf):\n array = line.split()\n self.assertEqual(array[0].decode('utf-8'), 'Au')\n for j in range(3):\n self.assertEqual(float(array[j + 1]), self.lattice.pos[3 * i + j])\n self.assertEqual(float(array[4]), self.lattice.charge[i])\n self.assertEqual(i + 1, self.lattice.NAtoms)\n with tempfile.NamedTemporaryFile() as tmpf:\n visatoms = np.asarray([1, 3, 5], dtype=np.int32)\n fn = tmpf.name\n self.lattice.writeLattice(fn, visibleAtoms=visatoms)\n line = tmpf.readline()\n natom = int(line)\n self.assertEqual(natom, len(visatoms))\n line = tmpf.readline()\n dims = line.split()\n self.assertEqual(float(dims[0]), self.lattice.cellDims[0])\n self.assertEqual(float(dims[1]), self.lattice.cellDims[1])\n self.assertEqual(float(dims[2]), self.lattice.cellDims[2])\n for i, line in enumerate(tmpf):\n index = visatoms[i]\n array = line.split()\n self.assertEqual(array[0].decode('utf-8'), 'Au')\n for j in range(3):\n self.assertEqual(float(array[j + 1]), self.lattice.pos[3 * index + j])\n self.assertEqual(float(array[4]), self.lattice.charge[index])\n self.assertEqual(i + 1, len(visatoms))\n", "method_code": " def writeLattice(self, filename, visibleAtoms=None):\n \"\"\"\n Write the Lattice to the given file. If visibleAtoms is passed only write those atoms.\n \n \"\"\"\n if visibleAtoms is None:\n writeFullLattice = 1\n visibleAtoms = np.empty(0, np.int32)\n else:\n writeFullLattice = 0\n _output.writeLattice(filename, visibleAtoms, self.cellDims, self.specieList, self.specie, self.pos, self.charge, writeFullLattice)\n ", "context": "class Lattice(object):\n def writeLattice(self, filename, visibleAtoms=None): ...\n def __init__(self): ...\n def wrapAtoms(self): ...\n def atomSeparation(self, index1, index2, pbc): ...\n def reset(self, NAtoms): ...\n def calcTemperature(self, NMoving=None): ...\n def density(self): ...\n def volume(self): ...\n def addSpecie(self, sym, count=None): ...\n def addAtom(self, sym, pos, charge, atomID=None, scalarVals={}, vectorVals={}): ...\n def removeAtom(self, index): ...\n def removeSpecie(self, index): ...\n def calcForce(self, forceConfig): ...\n def atomPos(self, index): ...\n def atomSym(self, index): ...\n def getSpecieIndex(self, sym): ...\n def setDims(self, dimsarray): ...\n def refreshElementProperties(self): ...\n def toLKMC(self, storeEnergies=False): ...\n def clone(self, lattice): ...\n\n self.NAtoms = 0\n self.cellDims = np.array([100, 100, 100], np.float64)\n self.specieList = []\n self.specieCount = np.empty(0, np.int32)\n self.specieMass = np.empty(0, np.float64)\n self.specieCovalentRadius = np.empty(0, np.float64)\n self.specieRGB = np.empty((0, 3), np.float64)\n self.specieAtomicNumber = np.empty(0, np.int32)\n self.minPos = np.zeros(3, np.float64)\n self.maxPos = np.zeros(3, np.float64)\n self.atomID = np.empty(0, np.int32)\n self.specie = np.empty(0, np.int32)\n self.pos = np.empty(0, np.float64)\n self.charge = np.empty(0, np.float64)\n self.scalarsDict = {}\n self.scalarsFiles = {}\n self.vectorsDict = {}\n self.vectorsFiles = {}\n self.attributes = {}\n self.PBC = np.ones(3, np.int32)\n", "repository": "chrisdjscott/Atoman", "test_name": "test_writeLattice", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000198.py"} {"focal_file": "atoman/system/lattice.py", "focal_class": null, "focal_method": "getSpecieIndex", "tests": "import unittest\n\nclass Test_getSpecieIndex(unittest.TestCase):\n def test_getSpecieIndex(self):\n \"\"\"\n Lattice getSpecieIndex\n\n \"\"\"\n index = self.lattic2.getSpecieIndex('Si')\n self.assertEqual('Si', self.lattic2.specieList[index])\n index = self.lattic2.getSpecieIndex('B_')\n self.assertEqual('B_', self.lattic2.specieList[index])\n index = self.lattic2.getSpecieIndex('O_')\n self.assertEqual('O_', self.lattic2.specieList[index])\n with self.assertRaises(ValueError):\n self.lattic2.getSpecieIndex('Zn')\n", "method_code": " def getSpecieIndex(self, sym):\n \"\"\"\n Return index of specie in specie list.\n \n \"\"\"\n if sym not in self.specieList:\n raise ValueError(\"Species '%s' is not in the species list\" % sym)\n index = None\n for i in range(len(self.specieList)):\n if self.specieList[i] == sym:\n index = i\n break\n return index\n ", "context": "class Lattice(object):\n def getSpecieIndex(self, sym): ...\n def __init__(self): ...\n def wrapAtoms(self): ...\n def atomSeparation(self, index1, index2, pbc): ...\n def reset(self, NAtoms): ...\n def calcTemperature(self, NMoving=None): ...\n def density(self): ...\n def volume(self): ...\n def addSpecie(self, sym, count=None): ...\n def addAtom(self, sym, pos, charge, atomID=None, scalarVals={}, vectorVals={}): ...\n def removeAtom(self, index): ...\n def removeSpecie(self, index): ...\n def calcForce(self, forceConfig): ...\n def atomPos(self, index): ...\n def atomSym(self, index): ...\n def setDims(self, dimsarray): ...\n def refreshElementProperties(self): ...\n def toLKMC(self, storeEnergies=False): ...\n def writeLattice(self, filename, visibleAtoms=None): ...\n def clone(self, lattice): ...\n\n self.NAtoms = 0\n self.cellDims = np.array([100, 100, 100], np.float64)\n self.specieList = []\n self.specieCount = np.empty(0, np.int32)\n self.specieMass = np.empty(0, np.float64)\n self.specieCovalentRadius = np.empty(0, np.float64)\n self.specieRGB = np.empty((0, 3), np.float64)\n self.specieAtomicNumber = np.empty(0, np.int32)\n self.minPos = np.zeros(3, np.float64)\n self.maxPos = np.zeros(3, np.float64)\n self.atomID = np.empty(0, np.int32)\n self.specie = np.empty(0, np.int32)\n self.pos = np.empty(0, np.float64)\n self.charge = np.empty(0, np.float64)\n self.scalarsDict = {}\n self.scalarsFiles = {}\n self.vectorsDict = {}\n self.vectorsFiles = {}\n self.attributes = {}\n self.PBC = np.ones(3, np.int32)\n", "repository": "chrisdjscott/Atoman", "test_name": "test_getSpecieIndex", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000199.py"} {"focal_file": "rpy/version.py", "focal_class": null, "focal_method": "get_version", "tests": "import unittest\n\nclass Test_get_version(unittest.TestCase):\n def test_get_version(self):\n \"\"\"\n Ensures the get_version function returns a dot separated expression of\n the VERSION.\n \"\"\"\n expected = '.'.join([str(i) for i in VERSION])\n actual = get_version()\n self.assertEqual(expected, actual)\n", "method_code": "def get_version():\n \"\"\"\n Returns a string version of VERSION\n \"\"\"\n return '.'.join([str(i) for i in VERSION])", "context": "def get_version(): ...\ndef get_version(): ...\n", "repository": "EthrosDemon/RaspberryPy", "test_name": "test_get_version", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000200.py"} {"focal_file": "gluon/storage.py", "focal_class": null, "focal_method": "getlist", "tests": "import unittest\n\nclass Test_getlist(unittest.TestCase):\n def test_getlist(self):\n a = Storage()\n a.x = 'abc'\n a.y = ['abc', 'def']\n self.assertEqual(a.getlist('x'), ['abc'])\n self.assertEqual(a.getlist('y'), ['abc', 'def'])\n self.assertEqual(a.getlist('z'), [])\n", "method_code": " def getlist(self, key):\n \"\"\"\n Returns a Storage value as a list.\n \n If the value is a list it will be returned as-is.\n If object is None, an empty list will be returned.\n Otherwise, `[value]` will be returned.\n \n Example output for a query string of `?x=abc&y=abc&y=def`::\n \n >>> request = Storage()\n >>> request.vars = Storage()\n >>> request.vars.x = 'abc'\n >>> request.vars.y = ['abc', 'def']\n >>> request.vars.getlist('x')\n ['abc']\n >>> request.vars.getlist('y')\n ['abc', 'def']\n >>> request.vars.getlist('z')\n []\n \n \"\"\"\n value = self.get(key, [])\n if value is None or isinstance(value, (list, tuple)):\n return value\n else:\n return [value]\n ", "context": "class Storage(dict):\n def getlist(self, key): ...\n def getfirst(self, key, default=None): ...\n def getlast(self, key, default=None): ...\n\n __slots__ = ()\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n __getitem__ = dict.get\n __getattr__ = dict.get\n __repr__ = lambda self: '' % dict.__repr__(self)\n __getstate__ = lambda self: None\n __copy__ = lambda self: Storage(self)\n", "repository": "varshit97/placement-website", "test_name": "test_getlist", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000201.py"} {"focal_file": "gluon/storage.py", "focal_class": null, "focal_method": "getfirst", "tests": "import unittest\n\nclass Test_getfirst(unittest.TestCase):\n def test_getfirst(self):\n a = Storage()\n a.x = 'abc'\n a.y = ['abc', 'def']\n self.assertEqual(a.getfirst('x'), 'abc')\n self.assertEqual(a.getfirst('y'), 'abc')\n self.assertEqual(a.getfirst('z'), None)\n", "method_code": " def getfirst(self, key, default=None):\n \"\"\"\n Returns the first value of a list or the value itself when given a\n `request.vars` style key.\n \n If the value is a list, its first item will be returned;\n otherwise, the value will be returned as-is.\n \n Example output for a query string of `?x=abc&y=abc&y=def`::\n \n >>> request = Storage()\n >>> request.vars = Storage()\n >>> request.vars.x = 'abc'\n >>> request.vars.y = ['abc', 'def']\n >>> request.vars.getfirst('x')\n 'abc'\n >>> request.vars.getfirst('y')\n 'abc'\n >>> request.vars.getfirst('z')\n \n \"\"\"\n values = self.getlist(key)\n return values[0] if values else default\n ", "context": "class Storage(dict):\n def getfirst(self, key, default=None): ...\n def getlist(self, key): ...\n def getlast(self, key, default=None): ...\n\n __slots__ = ()\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n __getitem__ = dict.get\n __getattr__ = dict.get\n __repr__ = lambda self: '' % dict.__repr__(self)\n __getstate__ = lambda self: None\n __copy__ = lambda self: Storage(self)\n", "repository": "varshit97/placement-website", "test_name": "test_getfirst", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000202.py"} {"focal_file": "gluon/storage.py", "focal_class": null, "focal_method": "getlast", "tests": "import unittest\n\nclass Test_getlast(unittest.TestCase):\n def test_getlast(self):\n a = Storage()\n a.x = 'abc'\n a.y = ['abc', 'def']\n self.assertEqual(a.getlast('x'), 'abc')\n self.assertEqual(a.getlast('y'), 'def')\n self.assertEqual(a.getlast('z'), None)\n", "method_code": " def getlast(self, key, default=None):\n \"\"\"\n Returns the last value of a list or value itself when given a\n `request.vars` style key.\n \n If the value is a list, the last item will be returned;\n otherwise, the value will be returned as-is.\n \n Simulated output with a query string of `?x=abc&y=abc&y=def`::\n \n >>> request = Storage()\n >>> request.vars = Storage()\n >>> request.vars.x = 'abc'\n >>> request.vars.y = ['abc', 'def']\n >>> request.vars.getlast('x')\n 'abc'\n >>> request.vars.getlast('y')\n 'def'\n >>> request.vars.getlast('z')\n \n \"\"\"\n values = self.getlist(key)\n return values[-1] if values else default\n ", "context": "class Storage(dict):\n def getlast(self, key, default=None): ...\n def getlist(self, key): ...\n def getfirst(self, key, default=None): ...\n\n __slots__ = ()\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n __getitem__ = dict.get\n __getattr__ = dict.get\n __repr__ = lambda self: '' % dict.__repr__(self)\n __getstate__ = lambda self: None\n __copy__ = lambda self: Storage(self)\n", "repository": "varshit97/placement-website", "test_name": "test_getlast", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000203.py"} {"focal_file": "ultraboost/paskoba/lib/araw.py", "focal_class": "Araw", "focal_method": "get_current_date_with_tz", "tests": "import unittest\n\nclass Test_Araw_get_current_date_with_tz(unittest.TestCase):\n def test_get_current_date_with_tz_return_type(self):\n \"\"\"\n Tests if the return type is datetime.datetime\n :return:\n \"\"\"\n a = Araw()\n self.assertTrue(isinstance(a.get_current_date_with_tz('Asia/Manila'), datetime.datetime))\n", "method_code": " def get_current_date_with_tz(time_zone='Asia/Manila'):\n \"\"\"\n Gets the current date with the specified time zone\n :param time_zone: Location to get the local time of\n :return datetime.datetime: Current date and time\n \"\"\"\n tz = pytz.timezone(time_zone)\n return datetime.now(tz)\n ", "context": "class Araw(object):\n @staticmethod\n def get_current_date_with_tz(time_zone='Asia/Manila'): ...\n def get_simple_date(self, time_zone='Asia/Manila'): ...\n def is_today_christmas(): ...\n", "repository": "migzpogi/unchained", "test_name": "test_get_current_date_with_tz_return_type", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000204.py"} {"focal_file": "ultraboost/paskoba/lib/araw.py", "focal_class": "Araw", "focal_method": "get_simple_date", "tests": "import unittest\n\nclass Test_Araw_get_simple_date(unittest.TestCase):\n def test_get_simple_date_return_type(self):\n \"\"\"\n Tests if the return type is string\n :return:\n \"\"\"\n a = Araw()\n self.assertTrue(isinstance(a.get_simple_date(), str))\n", "method_code": " def get_simple_date(self, time_zone='Asia/Manila'):\n \"\"\"\n Gets the current date in Asia/Manila and converts it to string\n :param time_zone: Location to get the local time of\n :return str: month-day-year hour:minute\n \"\"\"\n manila = self.get_current_date_with_tz(time_zone)\n return f'{manila.month}-{manila.day}-{manila.year} {manila.hour}:{manila.minute}'\n ", "context": "class Araw(object):\n def get_simple_date(self, time_zone='Asia/Manila'): ...\n def get_current_date_with_tz(time_zone='Asia/Manila'): ...\n def is_today_christmas(): ...\n", "repository": "migzpogi/unchained", "test_name": "test_get_simple_date_return_type", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000205.py"} {"focal_file": "ultraboost/paskoba/lib/araw.py", "focal_class": "Araw", "focal_method": "is_today_christmas", "tests": "import unittest\n\nclass Test_Araw_is_today_christmas(unittest.TestCase):\n def test_is_today_christmas(self):\n \"\"\"\n Tests is_today_christmas\n :return:\n \"\"\"\n a = Araw()\n expected = (False, 99.73)\n actual = a.is_today_christmas()\n self.assertEqual(expected, actual)\n", "method_code": " def is_today_christmas():\n \"\"\"\n Checks if it is Christmas day\n :return tuple: this always returns False with its accuracy (False, x%)\n \"\"\"\n accuracy = round(364 / 365 * 100, 2)\n return (False, accuracy)\n ", "context": "class Araw(object):\n @staticmethod\n def is_today_christmas(): ...\n def get_current_date_with_tz(time_zone='Asia/Manila'): ...\n def get_simple_date(self, time_zone='Asia/Manila'): ...\n", "repository": "migzpogi/unchained", "test_name": "test_is_today_christmas", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000206.py"} {"focal_file": "ultraboost/ilan/lib/ilan.py", "focal_class": "Ilan", "focal_method": "is_string_number_valid", "tests": "import unittest\n\nclass Test_Ilan_is_string_number_valid(unittest.TestCase):\n def test_is_string_number_valid_integer(self):\n \"\"\"\n Integer in string format is provided\n :return:\n \"\"\"\n self.assertTrue(Ilan().is_string_number_valid('100'))\n\n def test_is_string_number_valid_float(self):\n \"\"\"\n Float in string format is provided\n :return:\n \"\"\"\n self.assertTrue(Ilan().is_string_number_valid('100.50'))\n\n def test_is_string_number_int_type(self):\n \"\"\"\n Integer in integer format is provided\n :return:\n \"\"\"\n self.assertFalse(Ilan().is_string_number_valid(100))\n\n def test_is_string_number_float_type(self):\n \"\"\"\n Float in float format is provided\n :return:\n \"\"\"\n self.assertFalse(Ilan().is_string_number_valid(100.5))\n\n def test_is_string_number_commas(self):\n \"\"\"\n Input with commas\n :return:\n \"\"\"\n expected = 1000\n actual = Ilan().is_string_number_valid('1,000')\n self.assertEqual(expected, actual)\n\n def test_is_string_number_multiple_points(self):\n \"\"\"\n Input with multiple decimal points\n :return:\n \"\"\"\n self.assertFalse(Ilan().is_string_number_valid('1.000.000'))\n\n def test_is_string_number_with_non_numeric(self):\n \"\"\"\n Input with letters and special characters\n :return:\n \"\"\"\n self.assertFalse(Ilan().is_string_number_valid('1000a!'))\n\n def test_is_string_number_with_negative(self):\n \"\"\"\n Input with negative sign\n :return:\n \"\"\"\n expected = -1000\n actual = Ilan().is_string_number_valid('-1000')\n self.assertEqual(expected, actual)\n", "method_code": " def is_string_number_valid(number: str):\n \"\"\"\n Checks if the given number is valid\n :param str number: input given by the user\n :return:\n \"\"\"\n try:\n stripped_number = Ilan().__remove_commas(number)\n return float(stripped_number)\n except AttributeError:\n print('Please make sure you provided int')\n return False\n except ValueError:\n print('Please check correct format. No letters, multiple decimal points, special characters')\n return False\n ", "context": "class Ilan():\n @staticmethod\n def is_string_number_valid(number: str): ...\n def get_qty(total_amount, price): ...\n def __remove_commas(number): ...\n", "repository": "migzpogi/unchained", "test_name": "test_is_string_number_valid_integer", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000207.py"} {"focal_file": "scriptcraft/gamemap.py", "focal_class": "GameMap", "focal_method": "place_object", "tests": "import unittest\n\nclass Test_GameMap_place_object(unittest.TestCase):\n def test_placing_object_on_field(self):\n game_map = GameMap((16, 16), [])\n field = game_map[9, 6]\n obj = object()\n field.place_object(obj)\n self.assertEqual(field.accessible, False)\n self.assertEqual(field.empty, False)\n self.assertEqual(field.maybe_object, obj)\n self.assertEqual(field, game_map[9, 6])\n", "method_code": " def place_object(self, obj):\n self._maybe_object = obj\n self._game_map[self._position] = self\n ", "context": "class Field(object):\n def place_object(self, obj): ...\n def __init__(self, position, valid_position, ground_type, maybe_object, game_map): ...\n def __eq__(self, other): ...\n def __repr__(self): ...\n def position(self): ...\n def valid_position(self): ...\n def ground_type(self): ...\n def maybe_object(self): ...\n def empty(self): ...\n def accessible(self): ...\n def change_ground(self, new_ground): ...\n\n self._position = position\n self._valid_position = valid_position\n self._ground_type = ground_type\n self._maybe_object = maybe_object\n self._game_map = game_map\n\n __slots__ = ('_maybe_object', '_valid_position', '_position', '_ground_type', '_game_map')\n", "repository": "chrismedrela/scriptcraft", "test_name": "test_placing_object_on_field", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000208.py"} {"focal_file": "scriptcraft/gamemap.py", "focal_class": null, "focal_method": "find_accessible_neighbour_of", "tests": "import unittest\n\nclass Test_find_accessible_neighbour_of(unittest.TestCase):\n def test_finding_accessible_neighbour_when_it_doesnt_exist(self):\n game_map = self._create_game_map(occupied_positions=[(0, 1), (1, 0)])\n answer = game_map.find_accessible_neighbour_of((0, 0))\n self.assertEqual(answer, None)\n\n def test_finding_accessible_neighbour_when_it_exists(self):\n game_map = self._create_game_map(occupied_positions=[(0, 1)])\n answer = game_map.find_accessible_neighbour_of((0, 0))\n self.assertEqual(answer.position, (1, 0))\n", "method_code": " def find_accessible_neighbour_of(self, position):\n for neighbour in self._get_four_neighbours_of(position):\n if neighbour.accessible:\n return neighbour\n return None\n ", "context": "class GameMap(object):\n def find_accessible_neighbour_of(self, position): ...\n def __init__(self, size=None, start_positions=None, raw_instance=False): ...\n def __getitem__(self, position): ...\n def __setitem__(self, position, field): ...\n def __deepcopy__(self, memo): ...\n def __repr__(self): ...\n def size(self): ...\n def try_reserve_free_start_position(self): ...\n def find_direction(self, source, destination): ...\n def _get_four_neighbours_of(self, pos): ...\n def _is_valid_position(self, position): ...\n\n self._free_start_positions = set(start_positions)\n self._size = size\n self._ground_types = dict((((x, y), GameMap.DEFAULT_GROUND_TYPE) for x in xrange(size[0]) for y in xrange(size[1])))\n self._objs = {}\n\n DEFAULT_GROUND_TYPE = 1\n INVALID_GROUND_TYPE = None\n MIN_GROUND_TYPE = 1\n MAX_GROUND_TYPE = 127\n", "repository": "chrismedrela/scriptcraft", "test_name": "test_finding_accessible_neighbour_when_it_doesnt_exist", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000209.py"} {"focal_file": "scriptcraft/gamemap.py", "focal_class": null, "focal_method": "try_reserve_free_start_position", "tests": "import unittest\n\nclass Test_try_reserve_free_start_position(unittest.TestCase):\n def test_reserving_start_position_when_its_occupied(self):\n game_map = self._create_game_map(start_positions=[(8, 8)], occupied_positions=[(8, 8)])\n self.assertEqual(game_map.try_reserve_free_start_position(), None)\n\n def test_reserving_start_position_when_its_not_occupied(self):\n game_map = self._create_game_map(start_positions=[(8, 8)], occupied_positions=[(7, 7)])\n self.assertEqual(game_map.try_reserve_free_start_position(), (8, 8))\n\n def test_reserving_start_position_when_its_on_edge(self):\n game_map = self._create_game_map(start_positions=[(0, 8)])\n self.assertEqual(game_map.try_reserve_free_start_position(), None)\n", "method_code": " def try_reserve_free_start_position(self):\n for position in self._free_start_positions:\n all_neighbours_are_accessible = all((neighbour.accessible for neighbour in self._get_four_neighbours_of(position)))\n if self[position].accessible and all_neighbours_are_accessible:\n self._free_start_positions.remove(position)\n return position\n return None\n ", "context": "class GameMap(object):\n def try_reserve_free_start_position(self): ...\n def __init__(self, size=None, start_positions=None, raw_instance=False): ...\n def __getitem__(self, position): ...\n def __setitem__(self, position, field): ...\n def __deepcopy__(self, memo): ...\n def __repr__(self): ...\n def size(self): ...\n def find_accessible_neighbour_of(self, position): ...\n def find_direction(self, source, destination): ...\n def _get_four_neighbours_of(self, pos): ...\n def _is_valid_position(self, position): ...\n\n self._free_start_positions = set(start_positions)\n self._size = size\n self._ground_types = dict((((x, y), GameMap.DEFAULT_GROUND_TYPE) for x in xrange(size[0]) for y in xrange(size[1])))\n self._objs = {}\n\n DEFAULT_GROUND_TYPE = 1\n INVALID_GROUND_TYPE = None\n MIN_GROUND_TYPE = 1\n MAX_GROUND_TYPE = 127\n", "repository": "chrismedrela/scriptcraft", "test_name": "test_reserving_start_position_when_its_occupied", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000210.py"} {"focal_file": "src/ciphers/caesar.py", "focal_class": null, "focal_method": "caesar", "tests": "import unittest\n\nclass Test_caesar(unittest.TestCase):\n def test_caesar(self):\n self.assertEqual(caesar('Hello World', 11), 'Spwwz Hzcwo')\n self.assertEqual(caesar('Caesar Cipher is a monoalphabetic substitution cipher', 17), 'Trvjri Tzgyvi zj r dfefrcgyrsvkzt jlsjkzklkzfe tzgyvi')\n", "method_code": "def caesar(text, shift):\n \"\"\"This function preforms a caesar shift on the input text and returns the output. Any characters which are not letters are left unchanged.\"\"\"\n return text.translate(CAESAR[shift % 26])", "context": "def caesar(text, shift): ...\ndef _caesar_chr(chr_code, shift): ...\ndef caesar(text, shift): ...\n", "repository": "ictrobot/alevel-coursework", "test_name": "test_caesar", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000211.py"} {"focal_file": "openerp/osv/query.py", "focal_class": "Query", "focal_method": "add_join", "tests": "import unittest\n\nclass Test_Query_add_join(unittest.TestCase):\n def test_query_chained_explicit_joins(self):\n query = Query()\n query.tables.extend(['\"product_product\"', '\"product_template\"'])\n query.where_clause.append('product_product.template_id = product_template.id')\n query.add_join(('product_template', 'product_category', 'categ_id', 'id', 'categ_id'), implicit=False, outer=False)\n query.add_join(('product_template__categ_id', 'res_user', 'user_id', 'id', 'user_id'), implicit=False, outer=True)\n self.assertEquals(query.get_sql()[0].strip(), '\"product_product\",\"product_template\" JOIN \"product_category\" as \"product_template__categ_id\" ON (\"product_template\".\"categ_id\" = \"product_template__categ_id\".\"id\") LEFT JOIN \"res_user\" as \"product_template__categ_id__user_id\" ON (\"product_template__categ_id\".\"user_id\" = \"product_template__categ_id__user_id\".\"id\")'.strip())\n self.assertEquals(query.get_sql()[1].strip(), 'product_product.template_id = product_template.id'.strip())\n", "method_code": " def add_join(self, connection, implicit=True, outer=False):\n \"\"\" Join a destination table to the current table.\n \n :param implicit: False if the join is an explicit join. This allows\n to fall back on the previous implementation of ``join`` before\n OpenERP 7.0. It therefore adds the JOIN specified in ``connection``\n If True, the join is done implicitely, by adding the table alias\n in the from clause and the join condition in the where clause\n of the query. Implicit joins do not handle outer parameter.\n :param connection: a tuple ``(lhs, table, lhs_col, col, link)``.\n The join corresponds to the SQL equivalent of::\n \n (lhs.lhs_col = table.col)\n \n Note that all connection elements are strings. Please refer to expression.py for more details about joins.\n \n :param outer: True if a LEFT OUTER JOIN should be used, if possible\n (no promotion to OUTER JOIN is supported in case the JOIN\n was already present in the query, as for the moment\n implicit INNER JOINs are only connected from NON-NULL\n columns so it would not be correct (e.g. for\n ``_inherits`` or when a domain criterion explicitly\n adds filtering)\n \"\"\"\n from openerp.osv.expression import generate_table_alias\n lhs, table, lhs_col, col, link = connection\n alias, alias_statement = generate_table_alias(lhs, [(table, link)])\n if implicit:\n if alias_statement not in self.tables:\n self.tables.append(alias_statement)\n condition = '(\"%s\".\"%s\" = \"%s\".\"%s\")' % (lhs, lhs_col, alias, col)\n self.where_clause.append(condition)\n else:\n pass\n return (alias, alias_statement)\n else:\n aliases = self._get_table_aliases()\n assert lhs in aliases, 'Left-hand-side table %s must already be part of the query tables %s!' % (lhs, str(self.tables))\n if alias_statement in self.tables:\n pass\n else:\n self.tables.append(alias_statement)\n self.joins.setdefault(lhs, []).append((alias, lhs_col, col, outer and 'LEFT JOIN' or 'JOIN'))\n return (alias, alias_statement)\n ", "context": "class Query(object):\n def add_join(self, connection, implicit=True, outer=False): ...\n def __init__(self, tables=None, where_clause=None, where_clause_params=None, joins=None): ...\n def _get_table_aliases(self): ...\n def _get_alias_mapping(self): ...\n def get_sql(self): ...\n def __str__(self): ...\n\n self.tables = tables or []\n self.where_clause = where_clause or []\n self.where_clause_params = where_clause_params or []\n self.joins = joins or {}\n", "repository": "nrjac/odoo-8.0", "test_name": "test_query_chained_explicit_joins", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000212.py"} {"focal_file": "scrapenv/lib/python3.6/site-packages/bs4/element.py", "focal_class": null, "focal_method": "decode", "tests": "import unittest\n\nclass Test_decode(unittest.TestCase):\n def test_real_shift_jis_document(self):\n shift_jis_html = b'
\\x82\\xb1\\x82\\xea\\x82\\xcdShift-JIS\\x82\\xc5\\x83R\\x81[\\x83f\\x83B\\x83\\x93\\x83O\\x82\\xb3\\x82\\xea\\x82\\xbd\\x93\\xfa\\x96{\\x8c\\xea\\x82\\xcc\\x83t\\x83@\\x83C\\x83\\x8b\\x82\\xc5\\x82\\xb7\\x81B
'\n unicode_html = shift_jis_html.decode('shift-jis')\n soup = self.soup(unicode_html)\n self.assertEqual(soup.encode('utf-8'), unicode_html.encode('utf-8'))\n self.assertEqual(soup.encode('euc_jp'), unicode_html.encode('euc_jp'))\n\n def test_real_hebrew_document(self):\n hebrew_document = b'Hebrew (ISO 8859-8) in Visual Directionality

Hebrew (ISO 8859-8) in Visual Directionality

\\xed\\xe5\\xec\\xf9'\n soup = self.soup(hebrew_document, from_encoding='iso8859-8')\n assert soup.original_encoding in ('iso8859-8', 'iso-8859-8')\n self.assertEqual(soup.encode('utf-8'), hebrew_document.decode('iso8859-8').encode('utf-8'))\n", "method_code": " def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):\n \"\"\"Returns a Unicode representation of this tag and its contents.\n \n :param eventual_encoding: The tag is destined to be\n encoded into this encoding. This method is _not_\n responsible for performing that encoding. This information\n is passed in so that it can be substituted in if the\n document contains a tag that mentions the document's\n encoding.\n \"\"\"\n if not isinstance(formatter, Formatter) and (not isinstance(formatter, Callable)):\n formatter = self._formatter_for_name(formatter)\n attrs = []\n if self.attrs:\n for key, val in sorted(self.attrs.items()):\n if val is None:\n decoded = key\n else:\n if isinstance(val, list) or isinstance(val, tuple):\n val = ' '.join(val)\n elif not isinstance(val, str):\n val = str(val)\n elif isinstance(val, AttributeValueWithCharsetSubstitution) and eventual_encoding is not None:\n val = val.encode(eventual_encoding)\n text = self.format_string(val, formatter)\n decoded = str(key) + '=' + EntitySubstitution.quoted_attribute_value(text)\n attrs.append(decoded)\n close = ''\n closeTag = ''\n prefix = ''\n if self.prefix:\n prefix = self.prefix + ':'\n if self.is_empty_element:\n close = ''\n if isinstance(formatter, Formatter):\n close = formatter.void_element_close_prefix or close\n else:\n closeTag = '' % (prefix, self.name)\n pretty_print = self._should_pretty_print(indent_level)\n space = ''\n indent_space = ''\n if indent_level is not None:\n indent_space = ' ' * (indent_level - 1)\n if pretty_print:\n space = indent_space\n indent_contents = indent_level + 1\n else:\n indent_contents = None\n contents = self.decode_contents(indent_contents, eventual_encoding, formatter)\n if self.hidden:\n s = contents\n else:\n s = []\n attribute_string = ''\n if attrs:\n attribute_string = ' ' + ' '.join(attrs)\n if indent_level is not None:\n s.append(indent_space)\n s.append('<%s%s%s%s>' % (prefix, self.name, attribute_string, close))\n if pretty_print:\n s.append('\\n')\n s.append(contents)\n if pretty_print and contents and (contents[-1] != '\\n'):\n s.append('\\n')\n if pretty_print and closeTag:\n s.append(space)\n s.append(closeTag)\n if indent_level is not None and closeTag and self.next_sibling:\n s.append('\\n')\n s = ''.join(s)\n return s\n ", "context": "class Tag(PageElement):\n def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None, is_xml=None): ...\n def __copy__(self): ...\n def is_empty_element(self): ...\n def string(self): ...\n def string(self, string): ...\n def _all_strings(self, strip=False, types=(NavigableString, CData)): ...\n def stripped_strings(self): ...\n def get_text(self, separator='', strip=False, types=(NavigableString, CData)): ...\n def decompose(self): ...\n def clear(self, decompose=False): ...\n def index(self, element): ...\n def get(self, key, default=None): ...\n def get_attribute_list(self, key, default=None): ...\n def has_attr(self, key): ...\n def __hash__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __contains__(self, x): ...\n def __bool__(self): ...\n def __setitem__(self, key, value): ...\n def __delitem__(self, key): ...\n def __call__(self, *args, **kwargs): ...\n def __getattr__(self, tag): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __repr__(self, encoding='unicode-escape'): ...\n def __unicode__(self): ...\n def __str__(self): ...\n def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, indent_level=None, formatter='minimal', errors='xmlcharrefreplace'): ...\n def _should_pretty_print(self, indent_level): ...\n def prettify(self, encoding=None, formatter='minimal'): ...\n def decode_contents(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def encode_contents(self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): ...\n def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): ...\n def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): ...\n def children(self): ...\n def descendants(self): ...\n def select_one(self, selector, namespaces=None, **kwargs): ...\n def select(self, selector, namespaces=None, limit=None, **kwargs): ...\n def childGenerator(self): ...\n def recursiveChildGenerator(self): ...\n def has_key(self, key): ...\n\n self.name = name\n self.namespace = namespace\n self.prefix = prefix\n self.preserve_whitespace_tags = preserve_whitespace_tags\n self.attrs = attrs\n self.contents = []\n self.hidden = False\n\n parserClass = _alias('parser_class')\n isSelfClosing = is_empty_element\n strings = property(_all_strings)\n getText = get_text\n text = property(get_text)\n findChild = find\n findAll = find_all\n findChildren = find_all\n", "repository": "dennohpeter/Cisco-Course-Updater", "test_name": "test_real_shift_jis_document", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000213.py"} {"focal_file": "compatibility_lib/compatibility_lib/deprecated_dep_finder.py", "focal_class": "compatibility_lib.deprecated_dep_finder.DeprecatedDepFinder", "focal_method": "_get_development_status_from_pypi", "tests": "import unittest\n\nclass Test_compatibility_lib_deprecated_dep_finder_DeprecatedDepFinder_get_development_status_from_pypi(unittest.TestCase):\n def test__get_development_status_from_pypi_error(self):\n PKG_INFO = {'test': {'test_key_error': []}}\n mock_call_pypi_json_api = mock.Mock(autospec=True)\n mock_call_pypi_json_api.return_value = PKG_INFO\n patch_utils = mock.patch('compatibility_lib.deprecated_dep_finder.utils.call_pypi_json_api', mock_call_pypi_json_api)\n with patch_utils:\n finder = deprecated_dep_finder.DeprecatedDepFinder(checker=self.mock_checker, store=self.fake_store)\n development_status = finder._get_development_status_from_pypi('package1')\n self.assertIsNone(development_status)\n\n def test__get_development_status_from_pypi(self):\n mock_call_pypi_json_api = mock.Mock(autospec=True)\n mock_call_pypi_json_api.return_value = self.PKG_INFO\n patch_utils = mock.patch('compatibility_lib.deprecated_dep_finder.utils.call_pypi_json_api', mock_call_pypi_json_api)\n with patch_utils:\n finder = deprecated_dep_finder.DeprecatedDepFinder(checker=self.mock_checker, store=self.fake_store)\n development_status = finder._get_development_status_from_pypi('package1')\n expected_development_status = 'Development Status :: 7 - Inactive'\n self.assertEqual(development_status, expected_development_status)\n", "method_code": " def _get_development_status_from_pypi(self, package_name):\n \"\"\"Get the development status for a package.\n \n All kinds of development statuses:\n \n Development Status :: 1 - Planning\n Development Status :: 2 - Pre-Alpha\n Development Status :: 3 - Alpha\n Development Status :: 4 - Beta\n Development Status :: 5 - Production/Stable\n Development Status :: 6 - Mature\n Development Status :: 7 - Inactive\n \n Args:\n package_name: the package needs to be checked.\n \n Returns:\n The development status of the package.\n \"\"\"\n pkg_info = utils.call_pypi_json_api(package_name=package_name)\n try:\n development_status = pkg_info['info']['classifiers'][0]\n except (KeyError, IndexError, TypeError):\n logging.warning('No development status available.')\n development_status = None\n return development_status\n ", "context": "class DeprecatedDepFinder(object):\n def _get_development_status_from_pypi(self, package_name): ...\n def __init__(self, py_version=None, checker=None, store=None, max_workers=50): ...\n def get_deprecated_dep(self, package_name): ...\n def get_deprecated_deps(self, packages=None): ...\n\n self.max_workers = max_workers\n self.py_version = py_version\n self._checker = checker\n self._store = store\n self._dependency_info_getter = utils.DependencyInfo(py_version, self._checker, self._store)\n self._pypi_thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers)\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test__get_development_status_from_pypi_error", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000214.py"} {"focal_file": "compatibility_lib/compatibility_lib/deprecated_dep_finder.py", "focal_class": "compatibility_lib.deprecated_dep_finder.DeprecatedDepFinder", "focal_method": "get_deprecated_dep", "tests": "import unittest\n\nclass Test_compatibility_lib_deprecated_dep_finder_DeprecatedDepFinder_get_deprecated_dep(unittest.TestCase):\n def test_get_deprecated_dep(self):\n mock_call_pypi_json_api = mock.Mock(autospec=True)\n mock_call_pypi_json_api.return_value = self.PKG_INFO\n self.fake_store.save_compatibility_statuses([compatibility_store.CompatibilityResult(packages=[package.Package('opencencus')], python_major_version='3', status=compatibility_store.Status.SUCCESS, details=None, dependency_info=self.DEP_INFO)])\n patch_utils = mock.patch('compatibility_lib.deprecated_dep_finder.utils.call_pypi_json_api', mock_call_pypi_json_api)\n with patch_utils:\n finder = deprecated_dep_finder.DeprecatedDepFinder(checker=self.mock_checker, store=self.fake_store)\n deprecated_deps = finder.get_deprecated_dep('opencencus')\n expected_deprecated_deps = set(['dep1', 'dep2'])\n self.assertEqual(set(deprecated_deps[1]), expected_deprecated_deps)\n", "method_code": " def get_deprecated_dep(self, package_name):\n \"\"\"Get deprecated dep for a single package.\"\"\"\n dependency_info = self._dependency_info_getter.get_dependency_info(package_name)\n deprecated_deps = []\n for dep_name, development_status in zip(dependency_info, self._pypi_thread_pool.map(self._get_development_status_from_pypi, dependency_info)):\n if development_status == DEPRECATED_STATUS:\n deprecated_deps.append(dep_name)\n return (package_name, deprecated_deps)\n ", "context": "class DeprecatedDepFinder(object):\n def get_deprecated_dep(self, package_name): ...\n def __init__(self, py_version=None, checker=None, store=None, max_workers=50): ...\n def _get_development_status_from_pypi(self, package_name): ...\n def get_deprecated_deps(self, packages=None): ...\n\n self.max_workers = max_workers\n self.py_version = py_version\n self._checker = checker\n self._store = store\n self._dependency_info_getter = utils.DependencyInfo(py_version, self._checker, self._store)\n self._pypi_thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers)\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_deprecated_dep", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000215.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.compatibility_store.CompatibilityResult", "focal_method": "with_updated_dependency_info", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_store_CompatibilityResult_with_updated_dependency_info(unittest.TestCase):\n def test_with_updated_dependency_info_new_dependencies(self):\n original_result = compatibility_store.CompatibilityResult(packages=[PACKAGE_1], python_major_version=3, status=compatibility_store.Status.SUCCESS, details='No details', dependency_info={'package1': {'installed_version': '1.2.3'}})\n updated_result = original_result.with_updated_dependency_info({'package2': {'installed_version': '4.5.6'}})\n self.assertEqual(updated_result.dependency_info, {'package1': {'installed_version': '1.2.3'}, 'package2': {'installed_version': '4.5.6'}})\n self.assertEqual(original_result.packages, updated_result.packages)\n self.assertEqual(original_result.python_major_version, updated_result.python_major_version)\n self.assertEqual(original_result.status, updated_result.status)\n self.assertEqual(original_result.details, updated_result.details)\n self.assertEqual(original_result.timestamp, updated_result.timestamp)\n\n def test_with_updated_dependency_info_changed_dependencies(self):\n original_result = compatibility_store.CompatibilityResult(packages=[PACKAGE_1], python_major_version=3, status=compatibility_store.Status.SUCCESS, details='No details', dependency_info={'package1': {'installed_version': '1.2.3'}})\n updated_result = original_result.with_updated_dependency_info({'package1': {'installed_version': '2.3.4'}, 'package2': {'installed_version': '4.5.6'}})\n self.assertEqual(updated_result.dependency_info, {'package1': {'installed_version': '2.3.4'}, 'package2': {'installed_version': '4.5.6'}})\n self.assertEqual(original_result.packages, updated_result.packages)\n self.assertEqual(original_result.python_major_version, updated_result.python_major_version)\n self.assertEqual(original_result.status, updated_result.status)\n self.assertEqual(original_result.details, updated_result.details)\n self.assertEqual(original_result.timestamp, updated_result.timestamp)\n", "method_code": " def with_updated_dependency_info(self, dependency_info: Mapping[str, Mapping[str, Any]]) -> 'CompatibilityResult':\n \"\"\"Return a CompatibilityResult with updated dependency_info.\n \n >>> original_result = compatibility_store.CompatibilityResult(\n ... packages=[PACKAGE_1],\n ... python_major_version=3,\n ... status=compatibility_store.Status.SUCCESS,\n ... dependency_info={\n ... 'package1': {'installed_version': '1.2.3'},\n ... 'package2': {'installed_version': '2.3.4'}})\n >>> updated_result = original_result.with_updated_dependency_info(\n ... {'package2': {'installed_version': '9.8.7'},\n ... 'package3': {'installed_version': '8.7.6'}})\n >>> updated_result.dependency_info\n {'package1': {'installed_version': '1.2.3'},\n 'package2': {'installed_version': '9.8.7'},\n 'package3': {'installed_version': '8.7.6'}}\n \n Args:\n dependency_info: The updated dependency information.\n \n Returns:\n A new CompatibilityResult that is identical to the current one\n except with the given dependency_info merged in.\n \"\"\"\n info = dict(self._dependency_info or {})\n info.update(dependency_info)\n return CompatibilityResult(self.packages, self.python_major_version, self.status, self.details, info, self.timestamp)\n ", "context": "class CompatibilityResult():\n def with_updated_dependency_info(self, dependency_info: Mapping[str, Mapping[str, Any]]) -> 'CompatibilityResult': ...\n def __init__(self, packages: Iterable[package.Package], python_major_version: int, status: Status=Status.UNKNOWN, details: Optional[str]=None, dependency_info: Optional[Mapping[str, Any]]=None, timestamp: Optional[datetime.datetime]=None): ...\n def __repr__(self): ...\n def __hash__(self): ...\n def __eq__(self, o): ...\n def packages(self) -> List[package.Package]: ...\n def python_major_version(self) -> int: ...\n def status(self) -> Status: ...\n def status(self, status: Status): ...\n def details(self) -> Optional[str]: ...\n def dependency_info(self) -> Optional[Mapping[str, Any]]: ...\n def timestamp(self) -> datetime.datetime: ...\n def get_package_version(self) -> str: ...\n\n self._packages = list(packages)\n self._python_major_version = python_major_version\n self._status = status\n self._details = details\n self._dependency_info = dependency_info\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_with_updated_dependency_info_new_dependencies", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000216.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.compatibility_store.CompatibilityStore", "focal_method": "get_packages", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_store_CompatibilityStore_get_packages(unittest.TestCase):\n def test_get_packages(self):\n pkgs = ['google-api-core', 'apache-beam']\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n mock_cursor.fetchall.return_value = [[pkgs[0], 'SUCCESS'], [pkgs[1], 'CHECK WARNING']]\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n with patch_pymysql:\n store = compatibility_store.CompatibilityStore()\n packages = list(store.get_packages())\n self.assertEqual(len(packages), 2)\n for i, pkg in enumerate(packages):\n self.assertTrue(isinstance(pkg, compatibility_store.package.Package))\n self.assertEqual(pkg.install_name, pkgs[i])\n", "method_code": " def get_packages(self) -> Iterable[package.Package]:\n \"\"\"Returns all packages tracked by the system.\"\"\"\n query = 'SELECT DISTINCT install_name FROM self_compatibility_status'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query)\n results = cursor.fetchall()\n for row in results:\n yield package.Package(install_name=row[0])\n ", "context": "class CompatibilityStore():\n def get_packages(self) -> Iterable[package.Package]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_packages", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000217.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.compatibility_store.CompatibilityStore", "focal_method": "get_self_compatibility", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_store_CompatibilityStore_get_self_compatibility(unittest.TestCase):\n def test_get_self_compatibility(self):\n row = (PACKAGE_1.install_name, 'SUCCESS', '3', '2018-07-17 01:07:08.936648 UTC', None)\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n mock_cursor.fetchall.return_value = [row]\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n store = compatibility_store.CompatibilityStore()\n with patch_pymysql:\n res = store.get_self_compatibility(PACKAGE_1)\n self.assertEqual(len(res), 1)\n self.assertTrue(isinstance(res[0], compatibility_store.CompatibilityResult))\n", "method_code": " def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]:\n \"\"\"Returns CompatibilityStatuses for internal package compatibility.\n \n Args:\n p: The package to check internal compatibility for.\n \n Yields:\n A (possibly empty) list of CompatibilityResults, one per Python\n version. The returned CompatibilityResults do not include\n a set `dependency_info`.\n \"\"\"\n return self.get_self_compatibilities([p])[p]\n ", "context": "class CompatibilityStore():\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_self_compatibility", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000218.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.compatibility_store.CompatibilityStore", "focal_method": "get_self_compatibilities", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_store_CompatibilityStore_get_self_compatibilities(unittest.TestCase):\n def test_get_self_compatibilities(self):\n packages = [PACKAGE_1, PACKAGE_2, PACKAGE_3, PACKAGE_4]\n rows = []\n for pkg in packages:\n row = (pkg.install_name, 'SUCCESS', '3', '2018-07-17 01:07:08.936648 UTC', None)\n rows.append(row)\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n mock_cursor.fetchall.return_value = rows\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n store = compatibility_store.CompatibilityStore()\n with patch_pymysql:\n res = store.get_self_compatibilities(packages)\n self.assertEqual(len(res), 4)\n self.assertEqual(frozenset(res.keys()), frozenset(packages))\n", "method_code": " def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]:\n \"\"\"Returns CompatibilityStatuses for internal package compatibility.\n \n Args:\n packages: The packages to check internal compatibility for.\n \n Returns:\n A mapping between the given packages and a (possibly empty)\n list of CompatibilityResults for each one. The returned\n CompatibilityResults do not include a set `dependency_info`.\n \"\"\"\n install_name_to_package = {p.install_name: p for p in packages}\n package_to_result = {p: [] for p in packages}\n packages_list = [p.install_name for p in packages]\n query = 'SELECT * FROM self_compatibility_status WHERE install_name IN %s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, [packages_list])\n results = cursor.fetchall()\n for row in results:\n install_name = row[0]\n p = install_name_to_package[install_name]\n package_to_result[p].append(self._row_to_compatibility_status([p], row))\n return {p: crs for p, crs in package_to_result.items()}\n ", "context": "class CompatibilityStore():\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_self_compatibilities", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000219.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.compatibility_store.CompatibilityStore", "focal_method": "get_pair_compatibility", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_store_CompatibilityStore_get_pair_compatibility(unittest.TestCase):\n def test_get_pair_compatibility_value_error(self):\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n store = compatibility_store.CompatibilityStore()\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n packages = [PACKAGE_1]\n with patch_pymysql, self.assertRaises(ValueError):\n store.get_pair_compatibility(packages)\n\n def test_get_pair_compatibility(self):\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n row = ('pkg1', 'pkg2', 'SUCCESS', '3', '2018-07-17 02:14:27.15768 UTC', None)\n mock_cursor.fetchall.return_value = [row]\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n store = compatibility_store.CompatibilityStore()\n packages = [PACKAGE_1, PACKAGE_2]\n with patch_pymysql:\n res = store.get_pair_compatibility(packages)\n self.assertEqual(len(res), 1)\n self.assertEqual(len(res[0].packages), 2)\n self.assertTrue(isinstance(res[0], compatibility_store.CompatibilityResult))\n", "method_code": " def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]:\n \"\"\"Returns CompatibilityStatuses for a pair of packages.\n \n Args:\n packages: The packages to check compatibility for. Must have a\n length of exactly 2.\n \n Yields:\n One CompatibilityResult per Python version. The returned\n CompatibilityResult does not include a set `dependency_info`.\n \"\"\"\n if len(packages) != 2:\n raise ValueError('expected 2 packages, got {}'.format(len(packages)))\n packages = sorted(packages, key=lambda p: p.install_name)\n query = 'SELECT * FROM pairwise_compatibility_status WHERE install_name_lower=%s AND install_name_higher=%s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, (packages[0].install_name, packages[1].install_name))\n results = cursor.fetchall()\n return [self._row_to_compatibility_status(packages, row) for row in results]\n ", "context": "class CompatibilityStore():\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_pair_compatibility_value_error", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000220.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.compatibility_store.CompatibilityStore", "focal_method": "get_compatibility_combinations", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_store_CompatibilityStore_get_compatibility_combinations(unittest.TestCase):\n def test_compatibility_combinations(self):\n row1 = ('package1', 'package2', 'SUCCESS', '3', '2018-07-17 02:14:27.15768 UTC', None)\n row2 = ('package1', 'package3', 'SUCCESS', '3', '2018-07-17 02:14:27.15768 UTC', None)\n row3 = ('package2', 'package3', 'SUCCESS', '3', '2018-07-17 02:14:27.15768 UTC', None)\n store = compatibility_store.CompatibilityStore()\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n mock_cursor.fetchall.return_value = [row1, row2, row3]\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n packages = [PACKAGE_1, PACKAGE_2, PACKAGE_3]\n with patch_pymysql:\n res = store.get_compatibility_combinations(packages)\n expected_pair_1 = frozenset({PACKAGE_1, PACKAGE_2})\n expected_pair_2 = frozenset({PACKAGE_1, PACKAGE_3})\n expected_pair_3 = frozenset({PACKAGE_2, PACKAGE_3})\n self.assertEqual(len(res.keys()), 3)\n self.assertEqual(frozenset(res.keys()), frozenset({expected_pair_1, expected_pair_2, expected_pair_3}))\n", "method_code": " def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]:\n \"\"\"Returns a mapping between package pairs and CompatibilityResults.\n Args:\n packages: The packages to check compatibility for.\n Returns:\n A mapping between every combination of input packages and their\n CompatibilityResults. The returned CompatibilityResults do not\n include a set `dependency_info`.For example:\n get_compatibility_combinations(packages = [p1, p2, p3]) =>\n {\n frozenset([p1, p2]): [CompatibilityResult...],\n frozenset([p1, p3]): [CompatibilityResult...],\n frozenset([p2, p3]): [CompatibilityResult...],\n }.\n \"\"\"\n install_name_to_package = {p.install_name: p for p in packages}\n packages_to_results = {}\n for p1, p2 in itertools.combinations(packages, r=2):\n packages_to_results[frozenset([p1, p2])] = []\n install_names = [p.install_name for p in packages]\n query = 'SELECT * FROM pairwise_compatibility_status WHERE install_name_lower IN %s AND install_name_higher IN %s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, (install_names, install_names))\n results = cursor.fetchall()\n for row in results:\n install_name_lower, install_name_higher, _, _, _, _ = row\n p_lower = install_name_to_package[install_name_lower]\n p_higher = install_name_to_package[install_name_higher]\n packages_to_results[frozenset([p_lower, p_higher])].append(self._row_to_compatibility_status([p_lower, p_higher], row))\n return {p: crs for p, crs in packages_to_results.items()}\n ", "context": "class CompatibilityStore():\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_compatibility_combinations", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000221.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.compatibility_store.CompatibilityResult", "focal_method": "save_compatibility_statuses", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_store_CompatibilityResult_save_compatibility_statuses(unittest.TestCase):\n def test_save_compatibility_statuses_pair(self):\n packages = [PACKAGE_1, PACKAGE_2]\n status = compatibility_store.Status.SUCCESS\n comp_status = compatibility_store.CompatibilityResult(packages=packages, python_major_version='3', status=status, details=None, dependency_info=None, timestamp=None)\n row_pairwise = ('package1', 'package2', 'SUCCESS', '3', None, None)\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n pair_sql = 'REPLACE INTO pairwise_compatibility_status values (%s, %s, %s, %s, %s, %s)'\n with patch_pymysql:\n store = compatibility_store.CompatibilityStore()\n store.save_compatibility_statuses([comp_status])\n mock_cursor.executemany.assert_called_with(pair_sql, [row_pairwise])\n\n def test_save_compatibility_statuses_self(self):\n packages = [PACKAGE_1]\n status = compatibility_store.Status.SUCCESS\n comp_status = compatibility_store.CompatibilityResult(packages=packages, python_major_version='3', status=status, details=None, dependency_info=None, timestamp=None)\n row_self = ('package1', 'SUCCESS', '3', None, None)\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n self_sql = 'REPLACE INTO self_compatibility_status values (%s, %s, %s, %s, %s)'\n with patch_pymysql:\n store = compatibility_store.CompatibilityStore()\n store.save_compatibility_statuses([comp_status])\n mock_cursor.executemany.assert_called_with(self_sql, [row_self])\n\n def test_save_compatibility_statuses_release_time(self):\n packages = [PACKAGE_1]\n status = compatibility_store.Status.SUCCESS\n comp_status = compatibility_store.CompatibilityResult(packages=packages, python_major_version='3', status=status, details=None, dependency_info={'dep1': {'installed_version': '2.1.0', 'installed_version_time': '2018-05-12T16:26:31', 'latest_version': '2.1.0', 'current_time': '2018-07-13T17:11:29.140608', 'latest_version_time': '2018-05-12T16:26:31', 'is_latest': True}}, timestamp=None)\n row_release_time = ('package1', 'dep1', '2.1.0', '2018-05-12T16:26:31', '2.1.0', '2018-05-12T16:26:31', True, '2018-07-13T17:11:29.140608')\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n sql = 'REPLACE INTO release_time_for_dependencies values (%s, %s, %s, %s, %s, %s, %s, %s)'\n with patch_pymysql:\n store = compatibility_store.CompatibilityStore()\n store.save_compatibility_statuses([comp_status])\n mock_cursor.executemany.assert_called_with(sql, [row_release_time])\n\n def test_save_compatibility_statuses_release_time_for_latest(self):\n packages = [PACKAGE_4]\n timestamp = '2018-07-17 03:01:06.11693 UTC'\n status = compatibility_store.Status.SUCCESS\n comp_status_py2 = compatibility_store.CompatibilityResult(packages=packages, python_major_version='2', status=status, details=None, dependency_info={'package4': {'installed_version': '12.7.0', 'installed_version_time': '2018-05-12T16:26:31', 'latest_version': '12.7.0', 'current_time': '2018-07-13T17:11:29.140608', 'latest_version_time': '2018-05-12T16:26:31', 'is_latest': True}}, timestamp=timestamp)\n comp_status_py3 = compatibility_store.CompatibilityResult(packages=packages, python_major_version='3', status=status, details=None, dependency_info={'package4': {'installed_version': '2.2.0', 'installed_version_time': '2018-05-12T16:26:31', 'latest_version': '2.7.0', 'current_time': '2018-07-13T17:11:29.140608', 'latest_version_time': '2018-05-12T16:26:31', 'is_latest': False}}, timestamp=timestamp)\n row_release_time = ('package4[gcp]', 'package4', '12.7.0', '2018-05-12T16:26:31', '12.7.0', '2018-05-12T16:26:31', True, '2018-07-13T17:11:29.140608')\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n sql = 'REPLACE INTO release_time_for_dependencies values (%s, %s, %s, %s, %s, %s, %s, %s)'\n with patch_pymysql:\n store = compatibility_store.CompatibilityStore()\n store.save_compatibility_statuses([comp_status_py2, comp_status_py3])\n mock_cursor.executemany.assert_called_with(sql, [row_release_time])\n\n def test_save_compatibility_statuses_release_time_for_latest_many_packages(self):\n status = compatibility_store.Status.SUCCESS\n apache_beam_py2 = compatibility_store.CompatibilityResult(packages=[package.Package('apache-beam[gcp]')], python_major_version='2', status=status, details=None, dependency_info={'six': {'installed_version': '9.9.9', 'installed_version_time': '2018-05-12T16:26:31', 'latest_version': '2.7.0', 'current_time': '2018-07-13T17:11:29.140608', 'latest_version_time': '2018-05-12T16:26:31', 'is_latest': False}, 'apache-beam': {'installed_version': '2.7.0', 'installed_version_time': '2018-05-12T16:26:31', 'latest_version': '2.7.0', 'current_time': '2018-07-13T17:11:29.140608', 'latest_version_time': '2018-05-12T16:26:31', 'is_latest': True}}, timestamp=None)\n apache_beam_py3 = compatibility_store.CompatibilityResult(packages=[package.Package('apache-beam[gcp]')], python_major_version='3', status=status, details=None, dependency_info={'apache-beam': {'installed_version': '2.2.0', 'installed_version_time': '2018-05-12T16:26:31', 'latest_version': '2.7.0', 'current_time': '2018-07-13T17:11:29.140608', 'latest_version_time': '2018-05-12T16:26:31', 'is_latest': False}}, timestamp=None)\n google_api_core_py2 = compatibility_store.CompatibilityResult(packages=[package.Package('google-api-core')], python_major_version='2', status=status, details=None, dependency_info={'google-api-core': {'installed_version': '3.7.0', 'installed_version_time': '2018-05-12T16:26:31', 'latest_version': '2.7.0', 'current_time': '2018-07-13T17:11:29.140608', 'latest_version_time': '2018-05-12T16:26:31', 'is_latest': True}}, timestamp=None)\n google_api_core_py3 = compatibility_store.CompatibilityResult(packages=[package.Package('google-api-core')], python_major_version='3', status=status, details=None, dependency_info={'google-api-core': {'installed_version': '3.7.1', 'installed_version_time': '2018-05-12T16:26:31', 'latest_version': '2.7.0', 'current_time': '2018-07-13T17:11:29.140608', 'latest_version_time': '2018-05-12T16:26:31', 'is_latest': False}}, timestamp=None)\n apache_beam_row = ('apache-beam[gcp]', 'apache-beam', '2.7.0', '2018-05-12T16:26:31', '2.7.0', '2018-05-12T16:26:31', True, '2018-07-13T17:11:29.140608')\n six_row = ('apache-beam[gcp]', 'six', '9.9.9', '2018-05-12T16:26:31', '2.7.0', '2018-05-12T16:26:31', False, '2018-07-13T17:11:29.140608')\n google_api_core_row = ('google-api-core', 'google-api-core', '3.7.1', '2018-05-12T16:26:31', '2.7.0', '2018-05-12T16:26:31', False, '2018-07-13T17:11:29.140608')\n mock_pymysql = mock.Mock()\n mock_conn = mock.Mock()\n mock_cursor = mock.Mock()\n mock_pymysql.connect.return_value = mock_conn\n mock_conn.cursor.return_value = mock_cursor\n patch_pymysql = mock.patch('compatibility_lib.compatibility_store.pymysql', mock_pymysql)\n sql = 'REPLACE INTO release_time_for_dependencies values (%s, %s, %s, %s, %s, %s, %s, %s)'\n with patch_pymysql:\n store = compatibility_store.CompatibilityStore()\n store.save_compatibility_statuses([apache_beam_py2, apache_beam_py3, google_api_core_py2, google_api_core_py3])\n mock_cursor.executemany.assert_called_with(sql, [apache_beam_row, six_row, google_api_core_row])\n", "method_code": " def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]):\n \"\"\"Save the given CompatibilityStatuses\"\"\"\n compatibility_statuses = list(compatibility_statuses)\n if any((cs for cs in compatibility_statuses if len(cs.packages) not in [1, 2])):\n raise ValueError('CompatibilityResult must have 1 or 2 packages')\n rows = [self._compatibility_status_to_row(s) for s in compatibility_statuses]\n self_rows = [r for r in rows if len(r) == 5]\n pair_rows = [r for r in rows if len(r) == 6]\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n if self_rows:\n self_sql = 'REPLACE INTO self_compatibility_status values (%s, %s, %s, %s, %s)'\n cursor.executemany(self_sql, self_rows)\n if pair_rows:\n pair_sql = 'REPLACE INTO pairwise_compatibility_status values (%s, %s, %s, %s, %s, %s)'\n cursor.executemany(pair_sql, pair_rows)\n conn.commit()\n name_to_compatibility_result = {}\n for cs in compatibility_statuses:\n if len(cs.packages) == 1:\n install_name = cs.packages[0].install_name\n latest_compatibility_result = get_latest_compatibility_result_by_version([name_to_compatibility_result.get(install_name), cs])\n name_to_compatibility_result[install_name] = latest_compatibility_result\n dependency_rows = itertools.chain(*[self._compatibility_status_to_release_time_rows(cs) for cs in name_to_compatibility_result.values() if cs])\n dependency_rows = sorted(dependency_rows, key=lambda row: (row[0], row[1]))\n if dependency_rows:\n sql = 'REPLACE INTO release_time_for_dependencies values (%s, %s, %s, %s, %s, %s, %s, %s)'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.executemany(sql, dependency_rows)\n conn.commit()\n ", "context": "class CompatibilityStore():\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_save_compatibility_statuses_pair", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000222.py"} {"focal_file": "compatibility_lib/compatibility_lib/dependency_highlighter.py", "focal_class": "compatibility_lib.dependency_highlighter.DependencyHighlighter", "focal_method": "check_package", "tests": "import unittest\n\nclass Test_compatibility_lib_dependency_highlighter_DependencyHighlighter_check_package(unittest.TestCase):\n def test_check_package(self):\n highlighter = dependency_highlighter.DependencyHighlighter(checker=self._checker, store=self._store)\n res = highlighter.check_package('apache-beam[gcp]')\n reprs = [repr(dep) for dep in res]\n reprs.sort()\n zipped = zip(self.expected_check_package_res, reprs)\n for expected, got in zipped:\n self.assertEqual(expected, got)\n highlighter = dependency_highlighter.DependencyHighlighter(checker=self._checker, store=self._store)\n res = highlighter.check_package('not-in-bigquery')\n reprs = [repr(dep) for dep in res]\n reprs.sort()\n zipped = zip(self.expected_check_package_res, reprs)\n for expected, got in zipped:\n self.assertEqual(expected, got)\n", "method_code": " def check_package(self, package_name):\n \"\"\"Looks for and returns outdated dependencies for a single package\n \n Args:\n package_name: the name of the package to query (string)\n Returns:\n a list of outdated dependencies\n \"\"\"\n dependency_info = self._dependency_info_getter.get_dependency_info(package_name)\n outdated_dependencies = []\n for name, info in dependency_info.items():\n if name in configs.IGNORED_DEPENDENCIES:\n continue\n priority = Priority()\n try:\n install = _sanitize_release_tag(info['installed_version'])\n except UnstableReleaseError as err:\n install = None\n priority = Priority(PriorityLevel.HIGH_PRIORITY, str(err))\n if not info['is_latest'] or priority.level != PriorityLevel.UP_TO_DATE:\n current_time = info['current_time']\n latest_version_time = info['latest_version_time']\n if current_time is None or latest_version_time is None:\n logging.warning('Release time for dependency {} is not available.'.format(name))\n continue\n try:\n latest = _sanitize_release_tag(info['latest_version'])\n except UnstableReleaseError:\n logging.warning('The latest version of {} is not a stable release.'.format(name))\n continue\n elapsed_time = current_time - latest_version_time\n if priority.level == PriorityLevel.UP_TO_DATE:\n priority = self._get_update_priority(name, install, latest, elapsed_time)\n dependency = OutdatedDependency(name, package_name, priority, info)\n outdated_dependencies.append(dependency)\n return outdated_dependencies\n ", "context": "class DependencyHighlighter(object):\n def check_package(self, package_name): ...\n def __init__(self, py_version=None, checker=None, store=None): ...\n def _get_update_priority(self, depname, install, latest, elapsed_time): ...\n def check_packages(self, packages, max_workers=20): ...\n\n self.py_version = py_version\n self._checker = checker\n self._store = store\n self._dependency_info_getter = utils.DependencyInfo(py_version, self._checker, self._store)\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_check_package", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000223.py"} {"focal_file": "compatibility_lib/compatibility_lib/dependency_highlighter.py", "focal_class": "compatibility_lib.dependency_highlighter.DependencyHighlighter", "focal_method": "check_packages", "tests": "import unittest\n\nclass Test_compatibility_lib_dependency_highlighter_DependencyHighlighter_check_packages(unittest.TestCase):\n def test_check_packages(self):\n packages = ['apache-beam[gcp]', 'not-in-bigquery']\n highlighter = dependency_highlighter.DependencyHighlighter(checker=self._checker, store=self._store)\n res = highlighter.check_packages(packages)\n for pkgname, outdated in res.items():\n reprs = [repr(dep) for dep in outdated]\n reprs.sort()\n zipped = zip(self.expected_check_package_res, reprs)\n for expected, got in zipped:\n self.assertEqual(expected, got)\n", "method_code": " def check_packages(self, packages, max_workers=20):\n \"\"\"Looks for and returns outdated dependencies for multiple package\n \n Args:\n packages: a list of package names to query (string)\n Returns:\n a dict mapping dependency name to outdated dependencies\n \"\"\"\n results = {}\n with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as p:\n outdated_dependencies = p.map(self.check_package, packages)\n for pkgname, result in zip(packages, outdated_dependencies):\n results[pkgname] = result\n return results\n ", "context": "class DependencyHighlighter(object):\n def check_packages(self, packages, max_workers=20): ...\n def __init__(self, py_version=None, checker=None, store=None): ...\n def _get_update_priority(self, depname, install, latest, elapsed_time): ...\n def check_package(self, package_name): ...\n\n self.py_version = py_version\n self._checker = checker\n self._store = store\n self._dependency_info_getter = utils.DependencyInfo(py_version, self._checker, self._store)\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_check_packages", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000224.py"} {"focal_file": "compatibility_lib/compatibility_lib/dependency_highlighter.py", "focal_class": null, "focal_method": "_sanitize_release_tag", "tests": "import unittest\n\nclass Test_sanitize_release_tag(unittest.TestCase):\n def test__sanitize_release_tag(self):\n for tag, expected in self.good_tags:\n major, minor, patch = expected\n release_info = dependency_highlighter._sanitize_release_tag(tag)\n self.assertEqual(release_info['major'], major)\n self.assertEqual(release_info['minor'], minor)\n self.assertEqual(release_info['patch'], patch)\n for tag in self.bad_tags:\n with self.assertRaises(dependency_highlighter.UnstableReleaseError):\n dependency_highlighter._sanitize_release_tag(tag)\n", "method_code": "def _sanitize_release_tag(release):\n \"\"\"Throws an error if the given release version is unstable\n eg. 1.0.dev, 2.1a0, 1.1rc3\n\n Args:\n release: the semantic release as a string\n Returns:\n a dict that maps the major, minor, and patch (represented as strings)\n to the int value of those fields\n \"\"\"\n patch_match = '^\\\\d+\\\\.\\\\d+$'\n match = '^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$|^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+$'\n errmsg = 'a dependency cannot have an unstable release {}'.format(release)\n if re.match(patch_match, release.strip()):\n release = '%s.0' % release\n elif not re.match(match, release.strip()):\n raise UnstableReleaseError(errmsg)\n segments = release.split('.')\n release_info = {'major': int(segments[0]), 'minor': int(segments[1]), 'patch': int(segments[2])}\n return release_info", "context": "def _sanitize_release_tag(release): ...\ndef _sanitize_release_tag(release): ...\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test__sanitize_release_tag", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000225.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": null, "focal_method": "get_self_compatibility", "tests": "import unittest\n\nclass Test_get_self_compatibility(unittest.TestCase):\n def test_get_self_compatibility(self):\n crs = [PACKAGE_1_PY2_CR, PACKAGE_1_PY2_OLD_CR, PACKAGE_1_PY3_CR, PACKAGE_2_PY2_CR]\n self._store.save_compatibility_statuses(crs)\n self.assertEqual(frozenset(self._store.get_self_compatibility(PACKAGE_1)), frozenset([PACKAGE_1_PY2_CR, PACKAGE_1_PY3_CR]))\n self.assertEqual(frozenset(self._store.get_self_compatibility(PACKAGE_2)), frozenset([PACKAGE_2_PY2_CR]))\n\n def test_get_self_compatibility_no_result(self):\n crs = [PACKAGE_1_PY2_CR, PACKAGE_1_PY2_OLD_CR, PACKAGE_1_PY3_CR, PACKAGE_2_PY2_CR, PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n self.assertFalse(frozenset(self._store.get_self_compatibility(PACKAGE_3)))\n", "method_code": " def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]:\n \"\"\"Returns CompatibilityStatuses for internal package compatibility.\n \n Args:\n p: The package to check internal compatibility for.\n \n Yields:\n A (possibly empty) list of CompatibilityResults, one per Python\n version. The returned CompatibilityResults do not include\n a set `dependency_info`.\n \"\"\"\n return self.get_self_compatibilities([p])[p]\n ", "context": "class CompatibilityStore():\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_self_compatibility", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000226.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": null, "focal_method": "get_self_compatibilities", "tests": "import unittest\n\nclass Test_get_self_compatibilities(unittest.TestCase):\n def test_get_self_compatibilities(self):\n crs = [PACKAGE_1_PY2_CR, PACKAGE_1_PY2_OLD_CR, PACKAGE_1_PY3_CR, PACKAGE_2_PY2_CR, PACKAGE_3_PY2_CR, PACKAGE_3_PY3_CR, PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n self.assertEqual(self._store.get_self_compatibilities([PACKAGE_1, PACKAGE_2]), {PACKAGE_1: [PACKAGE_1_PY2_CR, PACKAGE_1_PY3_CR], PACKAGE_2: [PACKAGE_2_PY2_CR]})\n\n def test_get_self_compatibilities_no_results(self):\n crs = [PACKAGE_1_PY2_CR, PACKAGE_1_PY2_OLD_CR, PACKAGE_1_PY3_CR, PACKAGE_2_PY2_CR, PACKAGE_3_PY2_CR, PACKAGE_3_PY3_CR, PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n self.assertEqual(self._store.get_self_compatibilities([PACKAGE_1, PACKAGE_2, PACKAGE_4]), {PACKAGE_1: [PACKAGE_1_PY2_CR, PACKAGE_1_PY3_CR], PACKAGE_2: [PACKAGE_2_PY2_CR], PACKAGE_4: []})\n", "method_code": " def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]:\n \"\"\"Returns CompatibilityStatuses for internal package compatibility.\n \n Args:\n packages: The packages to check internal compatibility for.\n \n Returns:\n A mapping between the given packages and a (possibly empty)\n list of CompatibilityResults for each one. The returned\n CompatibilityResults do not include a set `dependency_info`.\n \"\"\"\n install_name_to_package = {p.install_name: p for p in packages}\n package_to_result = {p: [] for p in packages}\n packages_list = [p.install_name for p in packages]\n query = 'SELECT * FROM self_compatibility_status WHERE install_name IN %s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, [packages_list])\n results = cursor.fetchall()\n for row in results:\n install_name = row[0]\n p = install_name_to_package[install_name]\n package_to_result[p].append(self._row_to_compatibility_status([p], row))\n return {p: crs for p, crs in package_to_result.items()}\n ", "context": "class CompatibilityStore():\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_self_compatibilities", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000227.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": null, "focal_method": "get_pair_compatibility", "tests": "import unittest\n\nclass Test_get_pair_compatibility(unittest.TestCase):\n def test_get_pair_compatibility(self):\n crs = [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY2_OLD_CR, PACKAGE_1_AND_2_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n self.assertEqual(frozenset(self._store.get_pair_compatibility([PACKAGE_1, PACKAGE_2])), frozenset([PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY3_CR]))\n\n def test_get_pair_compatibility_no_results(self):\n crs = [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n self.assertFalse(frozenset(self._store.get_pair_compatibility([PACKAGE_1, PACKAGE_3])))\n", "method_code": " def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]:\n \"\"\"Returns CompatibilityStatuses for a pair of packages.\n \n Args:\n packages: The packages to check compatibility for. Must have a\n length of exactly 2.\n \n Yields:\n One CompatibilityResult per Python version. The returned\n CompatibilityResult does not include a set `dependency_info`.\n \"\"\"\n if len(packages) != 2:\n raise ValueError('expected 2 packages, got {}'.format(len(packages)))\n packages = sorted(packages, key=lambda p: p.install_name)\n query = 'SELECT * FROM pairwise_compatibility_status WHERE install_name_lower=%s AND install_name_higher=%s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, (packages[0].install_name, packages[1].install_name))\n results = cursor.fetchall()\n return [self._row_to_compatibility_status(packages, row) for row in results]\n ", "context": "class CompatibilityStore():\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_pair_compatibility", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000228.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": null, "focal_method": "get_pairwise_compatibility_for_package", "tests": "import unittest\n\nclass Test_get_pairwise_compatibility_for_package(unittest.TestCase):\n def test_get_pairwise_compatibility_for_package(self):\n crs = [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY2_OLD_CR, PACKAGE_1_AND_2_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n actual_results = self._store.get_pairwise_compatibility_for_package(PACKAGE_1.install_name)\n expected_results = {frozenset([PACKAGE_1, PACKAGE_2]): [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY3_CR]}\n self.assertEqual(actual_results.keys(), expected_results.keys())\n for actual_key, actual_results in actual_results.items():\n self.assertEqual(frozenset(actual_results), frozenset(expected_results[actual_key]))\n\n def test_get_pairwise_compatibility_for_package_no_results(self):\n crs = [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY2_OLD_CR, PACKAGE_1_AND_2_PY3_CR, PACKAGE_3_PY2_CR, PACKAGE_3_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n actual_results = self._store.get_pairwise_compatibility_for_package(PACKAGE_3.install_name)\n self.assertFalse(actual_results)\n", "method_code": " def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]:\n \"\"\"Returns a mapping between package pairs and CompatibilityResults.\n \n Args:\n package_name: The package to check compatibility for.\n \n Returns:\n A mapping between every pairing between the given package with\n each google cloud python package (found in configs.PKG_LIST) and\n their pairwise CompatibilityResults. The returned\n CompatibilityResults do not include a set `dependency_info`.\n For example:\n Given package_name = 'p1', configs.PKG_LIST = [p2, p3, p4] =>\n {\n frozenset([p1, p2]): [CompatibilityResult...],\n frozenset([p1, p3]): [CompatibilityResult...],\n frozenset([p1, p4]): [CompatibilityResult...],\n }.\n \"\"\"\n pkg_sets = [sorted([package_name, pkg]) for pkg in configs.PKG_LIST]\n install_names_lower = [pair[0] for pair in pkg_sets]\n install_names_higher = [pair[1] for pair in pkg_sets]\n packages_to_results = {}\n query = 'SELECT * FROM(SELECT * FROM pairwise_compatibility_status WHERE install_name_lower IN %s AND install_name_higher IN %s) t1 WHERE t1.install_name_lower=%s OR t1.install_name_higher=%s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, (install_names_lower, install_names_higher, package_name, package_name))\n results = cursor.fetchall()\n for row in results:\n install_name_lower, install_name_higher, _, _, _, _ = row\n p_lower = package.Package(install_name_lower)\n p_higher = package.Package(install_name_higher)\n key = frozenset([p_lower, p_higher])\n if not packages_to_results.get(key):\n packages_to_results[key] = []\n packages_to_results[key].append(self._row_to_compatibility_status([p_lower, p_higher], row))\n return packages_to_results\n ", "context": "class CompatibilityStore():\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_pairwise_compatibility_for_package", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000229.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": null, "focal_method": "get_compatibility_combinations", "tests": "import unittest\n\nclass Test_get_compatibility_combinations(unittest.TestCase):\n def test_get_compatibility_combinations(self):\n crs = [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY2_OLD_CR, PACKAGE_1_AND_2_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n self.assertEqual(frozenset(self._store.get_compatibility_combinations([PACKAGE_1, PACKAGE_2])), frozenset({frozenset([PACKAGE_1, PACKAGE_2]): [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY3_CR]}))\n\n def test_get_compatibility_combinations_no_results(self):\n crs = [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY2_OLD_CR, PACKAGE_1_AND_2_PY3_CR]\n self._store.save_compatibility_statuses(crs)\n self.assertEqual(frozenset(self._store.get_compatibility_combinations([PACKAGE_1, PACKAGE_2, PACKAGE_3])), frozenset({frozenset([PACKAGE_1, PACKAGE_2]): [PACKAGE_1_AND_2_PY2_CR, PACKAGE_1_AND_2_PY3_CR], frozenset([PACKAGE_1, PACKAGE_3]): [], frozenset([PACKAGE_2, PACKAGE_3]): []}))\n", "method_code": " def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]:\n \"\"\"Returns a mapping between package pairs and CompatibilityResults.\n Args:\n packages: The packages to check compatibility for.\n Returns:\n A mapping between every combination of input packages and their\n CompatibilityResults. The returned CompatibilityResults do not\n include a set `dependency_info`.For example:\n get_compatibility_combinations(packages = [p1, p2, p3]) =>\n {\n frozenset([p1, p2]): [CompatibilityResult...],\n frozenset([p1, p3]): [CompatibilityResult...],\n frozenset([p2, p3]): [CompatibilityResult...],\n }.\n \"\"\"\n install_name_to_package = {p.install_name: p for p in packages}\n packages_to_results = {}\n for p1, p2 in itertools.combinations(packages, r=2):\n packages_to_results[frozenset([p1, p2])] = []\n install_names = [p.install_name for p in packages]\n query = 'SELECT * FROM pairwise_compatibility_status WHERE install_name_lower IN %s AND install_name_higher IN %s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, (install_names, install_names))\n results = cursor.fetchall()\n for row in results:\n install_name_lower, install_name_higher, _, _, _, _ = row\n p_lower = install_name_to_package[install_name_lower]\n p_higher = install_name_to_package[install_name_higher]\n packages_to_results[frozenset([p_lower, p_higher])].append(self._row_to_compatibility_status([p_lower, p_higher], row))\n return {p: crs for p, crs in packages_to_results.items()}\n ", "context": "class CompatibilityStore():\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_compatibility_combinations", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000230.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": null, "focal_method": "get_dependency_info", "tests": "import unittest\n\nclass Test_get_dependency_info(unittest.TestCase):\n def test_get_dependency_info(self):\n self._store.save_compatibility_statuses([PACKAGE_1_PY3_CR_WITH_RECENT_DEPS])\n self.assertEqual(self._store.get_dependency_info('package1'), RECENT_DEPS_1)\n\n def test_get_dependency_info_old_and_new(self):\n self._store.save_compatibility_statuses([PACKAGE_1_PY3_CR_WITH_OLD_DEPS_VERS, PACKAGE_1_PY3_CR_WITH_RECENT_DEPS])\n self.assertEqual(self._store.get_dependency_info('package1'), RECENT_DEPS_1)\n", "method_code": " def get_dependency_info(self, package_name: str):\n \"\"\"Returns dependency info for an indicated Google OSS package.\n \n Args:\n package_name: The package to lookup for.\n \n Returns:\n A mapping between the dependency names and the info (dict).\n For example:\n {\n 'six':\n {'current_time': datetime.datetime(...),\n 'installed_version': '1.13.0',\n 'installed_version_time': datetime.datetime(...),\n 'is_latest': 1,\n 'latest_version': '1.13.0',\n 'latest_version_time': datetime.datetime(...)},\n 'protobuf':\n {'current_time': datetime.datetime(...),\n 'installed_version': '3.7.1',\n 'installed_version_time': datetime.datetime(...),\n 'is_latest': 1,\n 'latest_version': '3.7.1',\n 'latest_version_time': datetime.datetime(...)},\n }\n \"\"\"\n query = 'SELECT * FROM release_time_for_dependencies WHERE install_name=%s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, package_name)\n results = cursor.fetchall()\n dependency_info = {}\n for row in results:\n install_name, dep_name, installed_version, installed_version_time, latest_version, latest_version_time, is_latest, timestamp = row\n key = dep_name\n value = {'installed_version': installed_version, 'installed_version_time': installed_version_time, 'latest_version': latest_version, 'latest_version_time': latest_version_time, 'is_latest': is_latest, 'current_time': timestamp}\n dependency_info[key] = value\n return dependency_info\n ", "context": "class CompatibilityStore():\n def get_dependency_info(self, package_name: str): ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_dependency_info", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000231.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_checker.py", "focal_class": "compatibility_lib.compatibility_checker.CompatibilityChecker", "focal_method": "check", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_checker_CompatibilityChecker_check(unittest.TestCase):\n def test_check(self):\n checker = compatibility_checker.CompatibilityChecker()\n packages = ['opencensus']\n python_version = 3\n expected_server_url = 'http://34.68.40.69/'\n data = {'python-version': python_version, 'package': packages}\n mock_requests = mock.Mock()\n mock_response = mock.Mock(content=b'{}')\n mock_requests.get.return_value = mock_response\n patch_request = mock.patch('compatibility_lib.compatibility_checker.requests', mock_requests)\n with patch_request:\n checker.check(packages, python_version)\n mock_requests.get.assert_called_with(compatibility_checker.SERVER_URL, params=data, timeout=299)\n self.assertEqual(compatibility_checker.SERVER_URL, expected_server_url)\n", "method_code": " def check(self, packages, python_version):\n \"\"\"Call the checker server to get back status results.\"\"\"\n if not utils._is_package_in_whitelist(packages):\n UNKNOWN_STATUS_RESULT['packages'] = packages\n UNKNOWN_STATUS_RESULT['description'] = 'Package is not supported by our checker server.'\n return UNKNOWN_STATUS_RESULT\n start_time = time.time()\n data = {'python-version': python_version, 'package': packages}\n try:\n result = requests.get(SERVER_URL, params=data, timeout=299)\n content = result.content.decode('utf-8')\n except Exception as e:\n check_time = time.time() - start_time\n logging.getLogger('compatibility_lib').error('Checked {} in {:.1f} seconds: {}'.format(packages, check_time, e))\n raise\n check_time = time.time() - start_time\n if result.ok:\n logging.getLogger('compatibility_lib').debug('Checked {} in {:.1f} seconds (success!)'.format(packages, check_time))\n else:\n logging.getLogger('compatibility_lib').debug('Checked {} in {:.1f} seconds: {}'.format(packages, check_time, content))\n result.raise_for_status()\n return (json.loads(content), python_version)\n ", "context": "class CompatibilityChecker(object):\n def check(self, packages, python_version): ...\n def __init__(self, max_workers=20): ...\n def filter_packages(self, packages, python_version): ...\n def retrying_check(self, args): ...\n def collect_check_packages(self, python_version=None, packages=None, pkg_sets=None): ...\n def get_compatibility(self, python_version=None, packages=None, pkg_sets=None): ...\n\n self.max_workers = max_workers\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_check", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000232.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_checker.py", "focal_class": "compatibility_lib.compatibility_checker.CompatibilityChecker", "focal_method": "get_compatibility", "tests": "import unittest\n\nclass Test_compatibility_lib_compatibility_checker_CompatibilityChecker_get_compatibility(unittest.TestCase):\n def test_get_compatibility(self):\n checker = compatibility_checker.CompatibilityChecker()\n pkg_list = ['pkg1', 'pkg2', 'pkg3']\n pkg_py_version_not_supported = {2: ['tensorflow'], 3: ['apache-beam[gcp]', 'gsutil']}\n mock_config = mock.Mock()\n mock_config.PKG_LIST = pkg_list\n mock_config.PKG_PY_VERSION_NOT_SUPPORTED = pkg_py_version_not_supported\n patch_config = mock.patch('compatibility_lib.compatibility_checker.configs', mock_config)\n patch_executor = mock.patch('compatibility_lib.compatibility_checker.concurrent.futures.ThreadPoolExecutor', FakeExecutor)\n patch_retrying_check = mock.patch.object(compatibility_checker.CompatibilityChecker, 'retrying_check', self._mock_retrying_check)\n res = []\n with patch_config, patch_executor, patch_retrying_check:\n result = checker.get_compatibility()\n for item in result:\n res.append(item)\n expected = sorted([((['pkg1'], '2', 'SUCCESS'),), ((['pkg2'], '2', 'SUCCESS'),), ((['pkg3'], '2', 'SUCCESS'),), ((['pkg1'], '3', 'SUCCESS'),), ((['pkg2'], '3', 'SUCCESS'),), ((['pkg3'], '3', 'SUCCESS'),), ((['pkg1', 'pkg2'], '2', 'SUCCESS'),), ((['pkg1', 'pkg3'], '2', 'SUCCESS'),), ((['pkg2', 'pkg3'], '2', 'SUCCESS'),), ((['pkg1', 'pkg2'], '3', 'SUCCESS'),), ((['pkg1', 'pkg3'], '3', 'SUCCESS'),), ((['pkg2', 'pkg3'], '3', 'SUCCESS'),)])\n self.assertEqual(sorted(res), expected)\n", "method_code": " def get_compatibility(self, python_version=None, packages=None, pkg_sets=None):\n \"\"\"Get the compatibility data for each package and package pairs.\"\"\"\n check_packages = self.collect_check_packages(python_version, packages, pkg_sets)\n start_time = time.time()\n with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers) as p:\n pkg_set_results = p.map(self.retrying_check, tuple(check_packages))\n for count, result in enumerate(zip(pkg_set_results)):\n if count and count % self.max_workers == 0 or count == len(check_packages) - 1:\n logging.getLogger('compatibility_lib').info('Successfully checked {}/{} in {:.1f}s'.format(count, len(check_packages), time.time() - start_time))\n yield result\n ", "context": "class CompatibilityChecker(object):\n def get_compatibility(self, python_version=None, packages=None, pkg_sets=None): ...\n def __init__(self, max_workers=20): ...\n def check(self, packages, python_version): ...\n def filter_packages(self, packages, python_version): ...\n def retrying_check(self, args): ...\n def collect_check_packages(self, python_version=None, packages=None, pkg_sets=None): ...\n\n self.max_workers = max_workers\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_compatibility", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000233.py"} {"focal_file": "compatibility_lib/compatibility_lib/get_compatibility_data.py", "focal_class": null, "focal_method": "get_package_pairs", "tests": "import unittest\n\nclass Test_get_package_pairs(unittest.TestCase):\n def test_get_package_pairs_pypi(self):\n mock_config = mock.Mock()\n PKG_LIST = ['package1', 'package2', 'package3']\n mock_config.PKG_LIST = PKG_LIST\n WHITELIST_URLS = {'github.com/pkg1.git': 'package1', 'github.com/pkg2.git': 'package2', 'github.com/pkg3.git': 'package3'}\n mock_config.WHITELIST_URLS = WHITELIST_URLS\n patch_config = mock.patch('compatibility_lib.get_compatibility_data.configs', mock_config)\n with patch_config, self.patch_constructor, self.patch_checker, self.patch_store:\n from compatibility_lib import get_compatibility_data\n self_packages, pair_packages = get_compatibility_data.get_package_pairs(check_pypi=True, check_github=False)\n expected_self_packages = sorted(['package1', 'package2', 'package3'])\n self.assertEqual(sorted(self_packages), expected_self_packages)\n expected_pair_packages = sorted([('package1', 'package2'), ('package1', 'package3'), ('package2', 'package3')])\n self.assertEqual(sorted(pair_packages), expected_pair_packages)\n\n def test_get_package_pairs_github(self):\n mock_config = mock.Mock()\n PKG_LIST = ['package1', 'package2', 'package3']\n mock_config.PKG_LIST = PKG_LIST\n WHITELIST_URLS = {'github.com/pkg1.git': 'package1', 'github.com/pkg2.git': 'package2', 'github.com/pkg3.git': 'package3'}\n mock_config.WHITELIST_URLS = WHITELIST_URLS\n patch_config = mock.patch('compatibility_lib.get_compatibility_data.configs', mock_config)\n with patch_config, self.patch_constructor, self.patch_checker, self.patch_store:\n from compatibility_lib import get_compatibility_data\n self_packages, pair_packages = get_compatibility_data.get_package_pairs(check_pypi=False, check_github=True)\n expected_self_packages = sorted(['github.com/pkg1.git', 'github.com/pkg2.git', 'github.com/pkg3.git'])\n self.assertEqual(sorted(self_packages), expected_self_packages)\n expected_pair_packages = sorted([('github.com/pkg1.git', 'package2'), ('github.com/pkg1.git', 'package3'), ('github.com/pkg2.git', 'package1'), ('github.com/pkg2.git', 'package3'), ('github.com/pkg3.git', 'package1'), ('github.com/pkg3.git', 'package2')])\n self.assertEqual(sorted(pair_packages), expected_pair_packages)\n", "method_code": "def get_package_pairs(check_pypi=False, check_github=False):\n \"\"\"Get package pairs for pypi and github head.\"\"\"\n self_packages = []\n pair_packages = []\n if check_pypi:\n self_packages.extend(configs.PKG_LIST)\n pypi_pairs = list(itertools.combinations(configs.PKG_LIST, 2))\n pair_packages.extend(pypi_pairs)\n if check_github:\n self_packages.extend(list(configs.WHITELIST_URLS.keys()))\n for gh_url in configs.WHITELIST_URLS:\n pairs = []\n gh_name = configs.WHITELIST_URLS[gh_url]\n for pypi_pkg in configs.PKG_LIST:\n if pypi_pkg != gh_name:\n pairs.append((gh_url, pypi_pkg))\n pair_packages.extend(pairs)\n return (self_packages, pair_packages)", "context": "def get_package_pairs(check_pypi=False, check_github=False): ...\ndef _result_dict_to_compatibility_result(results): ...\ndef run_cloud_sql_proxy(cloud_sql_proxy_path): ...\ndef get_package_pairs(check_pypi=False, check_github=False): ...\ndef write_to_status_table(check_pypi=False, check_github=False, cloud_sql_proxy_path=None): ...\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_package_pairs_pypi", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000234.py"} {"focal_file": "compatibility_lib/compatibility_lib/get_compatibility_data.py", "focal_class": null, "focal_method": "_result_dict_to_compatibility_result", "tests": "import unittest\n\nclass Test_result_dict_to_compatibility_result(unittest.TestCase):\n def test__result_dict_to_compatibility_result(self):\n with self.patch_constructor, self.patch_checker, self.patch_store:\n from compatibility_lib import compatibility_store\n from compatibility_lib import get_compatibility_data\n res_list = get_compatibility_data._result_dict_to_compatibility_result(self.results)\n self.assertTrue(isinstance(res_list[0], compatibility_store.CompatibilityResult))\n self.assertEqual(res_list[0].dependency_info, self.dependency_info)\n self.assertEqual(res_list[0].packages, self.packages)\n self.assertEqual(res_list[0].status, self.status)\n", "method_code": "def _result_dict_to_compatibility_result(results):\n res_list = []\n for item in results:\n res_dict = item[0]\n result_content, python_version = res_dict\n check_result = result_content.get('result')\n packages_list = [package.Package(pkg) for pkg in result_content.get('packages')]\n details = result_content.get('description')\n timestamp = datetime.datetime.now().isoformat()\n dependency_info = result_content.get('dependency_info')\n compatibility_result = compatibility_store.CompatibilityResult(packages=packages_list, python_major_version=python_version, status=compatibility_store.Status(check_result), details=details, timestamp=timestamp, dependency_info=dependency_info)\n res_list.append(compatibility_result)\n return res_list", "context": "def _result_dict_to_compatibility_result(results): ...\ndef _result_dict_to_compatibility_result(results): ...\ndef run_cloud_sql_proxy(cloud_sql_proxy_path): ...\ndef get_package_pairs(check_pypi=False, check_github=False): ...\ndef write_to_status_table(check_pypi=False, check_github=False, cloud_sql_proxy_path=None): ...\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test__result_dict_to_compatibility_result", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000235.py"} {"focal_file": "compatibility_lib/compatibility_lib/get_compatibility_data.py", "focal_class": null, "focal_method": "write_to_status_table", "tests": "import unittest\n\nclass Test_write_to_status_table(unittest.TestCase):\n def test_write_to_status_table(self):\n patch_cloud_sql_proxy = mock.patch('compatibility_lib.get_compatibility_data.run_cloud_sql_proxy', return_value=MockProxy())\n with self.patch_checker, self.patch_store, patch_cloud_sql_proxy:\n from compatibility_lib import get_compatibility_data\n get_compatibility_data.write_to_status_table()\n self.assertTrue(self.mock_checker.get_compatibility.called)\n saved_results = self.fake_store._packages_to_compatibility_result.get(frozenset({self.packages[0]}))\n self.assertIsNotNone(saved_results)\n self.assertEqual(len(saved_results), 1)\n saved_item = saved_results[0]\n self.assertEqual(saved_item.packages, self.packages)\n self.assertEqual(saved_item.dependency_info, self.dependency_info)\n self.assertEqual(saved_item.status, self.status)\n", "method_code": "def write_to_status_table(check_pypi=False, check_github=False, cloud_sql_proxy_path=None):\n \"\"\"Get the compatibility status for PyPI versions.\"\"\"\n self_packages, pair_packages = get_package_pairs(check_pypi, check_github)\n results = checker.get_compatibility(packages=self_packages, pkg_sets=pair_packages)\n res_list = _result_dict_to_compatibility_result(results)\n with run_cloud_sql_proxy(cloud_sql_proxy_path):\n store.save_compatibility_statuses(res_list)", "context": "def write_to_status_table(check_pypi=False, check_github=False, cloud_sql_proxy_path=None): ...\ndef _result_dict_to_compatibility_result(results): ...\ndef run_cloud_sql_proxy(cloud_sql_proxy_path): ...\ndef get_package_pairs(check_pypi=False, check_github=False): ...\ndef write_to_status_table(check_pypi=False, check_github=False, cloud_sql_proxy_path=None): ...\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_write_to_status_table", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000236.py"} {"focal_file": "compatibility_lib/compatibility_lib/utils.py", "focal_class": "compatibility_lib.utils.DependencyInfo", "focal_method": "_get_from_cloud_sql", "tests": "import unittest\n\nclass Test_compatibility_lib_utils_DependencyInfo_get_from_cloud_sql(unittest.TestCase):\n def test__get_from_cloud_sql_exists(self):\n dep_info_getter = utils.DependencyInfo(checker=self.mock_checker, store=self.fake_store)\n dep_info = dep_info_getter._get_from_cloud_sql('opencensus')\n self.assertIsNotNone(dep_info)\n\n def test__get_from_cloud_sql_not_exists(self):\n dep_info_getter = utils.DependencyInfo(checker=self.mock_checker, store=self.fake_store)\n dep_info = dep_info_getter._get_from_cloud_sql('pkg_not_in_config')\n self.assertIsNone(dep_info)\n", "method_code": " def _get_from_cloud_sql(self, package_name):\n \"\"\"Gets the package dependency info from compatibility store\n which gets its dependnecy info from cloud sql.\n \n Args:\n package_name: the name of the package to query\n Returns:\n a dict mapping from dependency package name (string) to\n the info (dict)\n \"\"\"\n if self.store is not None:\n if package_name in configs.PKG_LIST or package_name in configs.WHITELIST_URLS:\n depinfo = self.store.get_dependency_info(package_name)\n return depinfo\n else:\n return None\n ", "context": "class DependencyInfo(object):\n def _get_from_cloud_sql(self, package_name): ...\n def __init__(self, py_version=None, checker=None, store=None): ...\n def _get_from_endpoint(self, package_name): ...\n def get_dependency_info(self, package_name): ...\n\n self.py_version = py_version\n self.checker = checker\n self.store = store\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test__get_from_cloud_sql_exists", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000237.py"} {"focal_file": "compatibility_lib/compatibility_lib/utils.py", "focal_class": "compatibility_lib.utils.DependencyInfo", "focal_method": "_get_from_endpoint", "tests": "import unittest\n\nclass Test_compatibility_lib_utils_DependencyInfo_get_from_endpoint(unittest.TestCase):\n def test__get_from_endpoint(self):\n dep_info_getter = utils.DependencyInfo(checker=self.mock_checker, store=self.fake_store)\n dep_info = dep_info_getter._get_from_endpoint('opencensus')\n self.assertEqual(dep_info, DEP_INFO)\n\n def test__get_from_endpoint_raise_exception(self):\n dep_info_getter = utils.DependencyInfo(checker=self.mock_checker, store=self.fake_store)\n with self.assertRaises(utils.PackageNotSupportedError):\n dep_info_getter._get_from_endpoint('pkg_not_in_config')\n", "method_code": " def _get_from_endpoint(self, package_name):\n \"\"\"Gets the package dependency info from the compatibility checker\n endpoint.\n \n Args:\n package_name: the name of the package to query (string)\n Returns:\n a dict mapping from dependency package name (string) to\n the info (dict)\n \"\"\"\n _result = self.checker.get_compatibility(python_version=self.py_version, packages=[package_name])\n result = [item for item in _result]\n depinfo = result[0][0].get('dependency_info')\n if depinfo is None:\n logging.warning('Could not get the dependency info of package {} from server.'.format(package_name))\n raise PackageNotSupportedError(package_name)\n fields = ('installed_version_time', 'current_time', 'latest_version_time')\n for pkgname in depinfo.keys():\n for field in fields:\n depinfo[pkgname][field] = _parse_datetime(depinfo[pkgname][field])\n return depinfo\n ", "context": "class DependencyInfo(object):\n def _get_from_endpoint(self, package_name): ...\n def __init__(self, py_version=None, checker=None, store=None): ...\n def _get_from_cloud_sql(self, package_name): ...\n def get_dependency_info(self, package_name): ...\n\n self.py_version = py_version\n self.checker = checker\n self.store = store\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test__get_from_endpoint", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000238.py"} {"focal_file": "compatibility_lib/compatibility_lib/utils.py", "focal_class": "compatibility_lib.utils.DependencyInfo", "focal_method": "get_dependency_info", "tests": "import unittest\n\nclass Test_compatibility_lib_utils_DependencyInfo_get_dependency_info(unittest.TestCase):\n def test_get_dependency_info_compatibility_store(self):\n dep_info_getter = utils.DependencyInfo(checker=self.mock_checker, store=self.fake_store)\n dep_info = dep_info_getter.get_dependency_info('opencensus')\n self.assertIsNotNone(dep_info)\n", "method_code": " def get_dependency_info(self, package_name):\n \"\"\"Gets the package dependency info\n \n Args:\n package_name: the name of the package to query (string)\n Returns:\n a dict mapping from dependency package name (string) to\n the info (dict)\n \"\"\"\n depinfo = self._get_from_cloud_sql(package_name)\n if depinfo is None:\n depinfo = self._get_from_endpoint(package_name)\n return depinfo\n ", "context": "class DependencyInfo(object):\n def get_dependency_info(self, package_name): ...\n def __init__(self, py_version=None, checker=None, store=None): ...\n def _get_from_cloud_sql(self, package_name): ...\n def _get_from_endpoint(self, package_name): ...\n\n self.py_version = py_version\n self.checker = checker\n self.store = store\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_get_dependency_info_compatibility_store", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000239.py"} {"focal_file": "compatibility_lib/compatibility_lib/utils.py", "focal_class": null, "focal_method": "_parse_datetime", "tests": "import unittest\n\nclass Test_parse_datetime(unittest.TestCase):\n def test__parse_datetime(self):\n date_string = '2018-08-16T15:42:04.351677'\n expected = '2018-08-16 00:00:00'\n res = utils._parse_datetime(date_string)\n self.assertEqual(str(res), expected)\n\n def test__parse_datetime_empty(self):\n res = utils._parse_datetime(None)\n self.assertIsNone(res)\n", "method_code": "def _parse_datetime(date_string):\n \"\"\"Converts a date string into a datetime obj\n\n Args:\n date_string: a date as a string\n Returns:\n the date as a datetime obj\n \"\"\"\n if date_string is None:\n return None\n date_string = date_string.replace('T', ' ')\n short_date = date_string.split(' ')[0]\n return datetime.strptime(short_date, DATETIME_FORMAT)", "context": "def _parse_datetime(date_string): ...\ndef call_pypi_json_api(package_name, pkg_version=None): ...\ndef _is_package_in_whitelist(packages): ...\ndef _parse_datetime(date_string): ...\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test__parse_datetime", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000240.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.fake_compatibility_store.CompatibilityStore", "focal_method": "get_self_compatibilities", "tests": "import unittest\n\nclass Test_compatibility_lib_fake_compatibility_store_CompatibilityStore_get_self_compatibilities(unittest.TestCase):\n def test_self_failure(self):\n \"\"\"CompatibilityResult failure installing a single package.\"\"\"\n packages = [PACKAGE_1, PACKAGE_2]\n store = fake_compatibility_store.CompatibilityStore()\n store.save_compatibility_statuses([compatibility_store.CompatibilityResult(packages=[PACKAGE_1], python_major_version=3, status=compatibility_store.Status.INSTALL_ERROR, details='Installation failure'), compatibility_store.CompatibilityResult(packages=[PACKAGE_2], python_major_version=3, status=compatibility_store.Status.SUCCESS)])\n with self.patch_finder, self.patch_highlighter:\n package_to_results = store.get_self_compatibilities(packages)\n pairwise_to_results = store.get_compatibility_combinations(packages)\n results = dashboard_builder._ResultHolder(package_to_results, pairwise_to_results)\n builder = dashboard_builder.DashboardBuilder(packages, results)\n html_grid = builder.build_dashboard('dashboard/grid-template.html')\n self.assertIn('Installation failure', html_grid)\n", "method_code": " def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]:\n \"\"\"Returns CompatibilityStatuses for internal package compatibility.\n \n Args:\n packages: The packages to check internal compatibility for.\n \n Returns:\n A mapping between the given packages and a (possibly empty)\n list of CompatibilityResults for each one. The returned\n CompatibilityResults do not include a set `dependency_info`.\n \"\"\"\n install_name_to_package = {p.install_name: p for p in packages}\n package_to_result = {p: [] for p in packages}\n packages_list = [p.install_name for p in packages]\n query = 'SELECT * FROM self_compatibility_status WHERE install_name IN %s'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.execute(query, [packages_list])\n results = cursor.fetchall()\n for row in results:\n install_name = row[0]\n p = install_name_to_package[install_name]\n package_to_result[p].append(self._row_to_compatibility_status([p], row))\n return {p: crs for p, crs in package_to_result.items()}\n ", "context": "class CompatibilityStore():\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_self_failure", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000241.py"} {"focal_file": "compatibility_lib/compatibility_lib/compatibility_store.py", "focal_class": "compatibility_lib.fake_compatibility_store.CompatibilityStore", "focal_method": "save_compatibility_statuses", "tests": "import unittest\n\nclass Test_compatibility_lib_fake_compatibility_store_CompatibilityStore_save_compatibility_statuses(unittest.TestCase):\n def test_not_show_py_ver_incompatible_results(self):\n \"\"\"CompatibilityResult failure between pair of packages. Do not display\n the packages that are incompatible with a specific Python version.\n \"\"\"\n packages = [PACKAGE_1, PACKAGE_2]\n store = fake_compatibility_store.CompatibilityStore()\n store.save_compatibility_statuses([compatibility_store.CompatibilityResult(packages=[PACKAGE_1], python_major_version=3, status=compatibility_store.Status.SUCCESS), compatibility_store.CompatibilityResult(packages=[PACKAGE_3], python_major_version=3, status=compatibility_store.Status.INSTALL_ERROR), compatibility_store.CompatibilityResult(packages=[PACKAGE_1, PACKAGE_3], python_major_version=3, status=compatibility_store.Status.INSTALL_ERROR, details='Installation failure')])\n patch = mock.patch('compatibility_lib.configs.PKG_PY_VERSION_NOT_SUPPORTED', {2: ['package4'], 3: ['package3']})\n with patch, self.patch_finder, self.patch_highlighter:\n package_to_results = store.get_self_compatibilities(packages)\n pairwise_to_results = store.get_compatibility_combinations(packages)\n results = dashboard_builder._ResultHolder(package_to_results, pairwise_to_results)\n builder = dashboard_builder.DashboardBuilder(packages, results)\n html_grid = builder.build_dashboard('dashboard/grid-template.html')\n self.assertNotIn('Installation failure', html_grid)\n", "method_code": " def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]):\n \"\"\"Save the given CompatibilityStatuses\"\"\"\n compatibility_statuses = list(compatibility_statuses)\n if any((cs for cs in compatibility_statuses if len(cs.packages) not in [1, 2])):\n raise ValueError('CompatibilityResult must have 1 or 2 packages')\n rows = [self._compatibility_status_to_row(s) for s in compatibility_statuses]\n self_rows = [r for r in rows if len(r) == 5]\n pair_rows = [r for r in rows if len(r) == 6]\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n if self_rows:\n self_sql = 'REPLACE INTO self_compatibility_status values (%s, %s, %s, %s, %s)'\n cursor.executemany(self_sql, self_rows)\n if pair_rows:\n pair_sql = 'REPLACE INTO pairwise_compatibility_status values (%s, %s, %s, %s, %s, %s)'\n cursor.executemany(pair_sql, pair_rows)\n conn.commit()\n name_to_compatibility_result = {}\n for cs in compatibility_statuses:\n if len(cs.packages) == 1:\n install_name = cs.packages[0].install_name\n latest_compatibility_result = get_latest_compatibility_result_by_version([name_to_compatibility_result.get(install_name), cs])\n name_to_compatibility_result[install_name] = latest_compatibility_result\n dependency_rows = itertools.chain(*[self._compatibility_status_to_release_time_rows(cs) for cs in name_to_compatibility_result.values() if cs])\n dependency_rows = sorted(dependency_rows, key=lambda row: (row[0], row[1]))\n if dependency_rows:\n sql = 'REPLACE INTO release_time_for_dependencies values (%s, %s, %s, %s, %s, %s, %s, %s)'\n with closing(self.connect()) as conn:\n with closing(conn.cursor()) as cursor:\n cursor.executemany(sql, dependency_rows)\n conn.commit()\n ", "context": "class CompatibilityStore():\n def save_compatibility_statuses(self, compatibility_statuses: Iterable[CompatibilityResult]): ...\n def __init__(self, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=3306, mysql_unix_socket=None, mysql_db=None): ...\n def connect(self): ...\n def _row_to_compatibility_status(packages: Iterable[package.Package], row: tuple) -> CompatibilityResult: ...\n def _compatibility_status_to_row(cs: CompatibilityResult) -> Tuple: ...\n def _compatibility_status_to_release_time_rows(cs: CompatibilityResult) -> List[Tuple]: ...\n def get_packages(self) -> Iterable[package.Package]: ...\n def get_self_compatibility(self, p: package.Package) -> Iterable[CompatibilityResult]: ...\n def get_self_compatibilities(self, packages: Iterable[package.Package]) -> Mapping[package.Package, List[CompatibilityResult]]: ...\n def get_pair_compatibility(self, packages: List[package.Package]) -> Iterable[CompatibilityResult]: ...\n def get_compatibility_combinations(self, packages: List[package.Package]) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_pairwise_compatibility_for_package(self, package_name) -> Mapping[FrozenSet[package.Package], List[CompatibilityResult]]: ...\n def get_dependency_info(self, package_name: str): ...\n\n self.mysql_user = mysql_user\n self.mysql_password = mysql_password\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_unix_socket = mysql_unix_socket\n self.mysql_db = mysql_db\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test_not_show_py_ver_incompatible_results", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000242.py"} {"focal_file": "compatibility_server/pip_checker.py", "focal_class": null, "focal_method": "_run_command", "tests": "import unittest\n\nclass Test_run_command(unittest.TestCase):\n def test__run_command_success(self):\n checker = pip_checker._OneshotPipCheck(['python3', '-m', 'pip'], packages=['six'], stats=self._stats)\n container = checker._run_container(MockDockerClient())\n returncode, output = checker._run_command(container, ['echo', 'testing'], stdout=True, stderr=True, raise_on_failure=False)\n self.assertEqual(output, 'testing\\n')\n docker_view_name = views.DOCKER_ERROR_VIEW.name\n docker_view_data = self._stats.view_manager.get_view(docker_view_name)\n self.assertEqual(docker_view_data._tag_value_aggregation_data_map, {})\n\n def test__run_command_timeout(self):\n checker = pip_checker._OneshotPipCheck(['python3', '-m', 'pip'], packages=['six'], stats=self._stats)\n TIME_OUT = 0.1\n patch_timeout = mock.patch('pip_checker.TIME_OUT', TIME_OUT)\n with patch_timeout, self.assertRaisesRegex(pip_checker.PipCheckerError, 'killed by signal 9'):\n container = checker._run_container(MockDockerClient())\n checker._run_command(container, ['sleep', '1'], stdout=True, stderr=True, raise_on_failure=False)\n docker_view_name = views.DOCKER_ERROR_VIEW.name\n docker_view_data = self._stats.view_manager.get_view(docker_view_name)\n docker_data_map = docker_view_data._tag_value_aggregation_data_map\n self.assertEqual(len(docker_data_map), 1)\n", "method_code": " def _run_command(self, container: docker.models.containers.Container, command: List[str], stdout: bool, stderr: bool, raise_on_failure: Optional[bool]=True) -> Tuple[int, str]:\n \"\"\"Run docker commands using docker python sdk.\n \n Args:\n container: The docker container that runs this command.\n command: The command to run in docker container.\n stdout: Whether to include stdout in output.\n stderr: Whether to include stderr in output.\n raise_on_failure: Whether to raise on failure.\n \n Returns:\n A tuple containing the return code of the given command and the\n output of that command.\n \"\"\"\n try:\n returncode, output = container.exec_run(command, stdout=stdout, stderr=stderr)\n output = output.decode('utf-8')\n except docker.errors.APIError as e:\n self._cleanup_container(container)\n self._mmap.measure_int_put(views.DOCKER_ERROR_MEASURE, 1)\n self._mmap.record(self._tmap)\n raise PipCheckerError(error_msg='Error occurs when executing commands in container.Error message: {}'.format(e.explanation))\n except IOError as e:\n self._mmap.measure_int_put(views.DOCKER_ERROR_MEASURE, 1)\n self._mmap.record(self._tmap)\n raise PipCheckerError(error_msg='An error occurred while running the command {} incontainer. Error message: {}'.format(command, e))\n if returncode > 128 and returncode <= 137:\n self._mmap.measure_int_put(views.DOCKER_ERROR_MEASURE, 1)\n self._mmap.record(self._tmap)\n raise PipCheckerError(error_msg='The command {} was killed by signal {}. This likely means that the Docker container timed out. Error msg: {}'.format(command, returncode - 128, output))\n elif returncode and raise_on_failure:\n raise PipError(error_msg=output, command=command, returncode=returncode)\n return (returncode, output)\n ", "context": "class _OneshotPipCheck():\n def _run_command(self, container: docker.models.containers.Container, command: List[str], stdout: bool, stderr: bool, raise_on_failure: Optional[bool]=True) -> Tuple[int, str]: ...\n def __init__(self, pip_command: List[str], packages: List[str], stats: stats_module.Stats): ...\n def _get_base_image(self): ...\n def _run_container(self, docker_client) -> docker.models.containers.Container: ...\n def _cleanup_container(self, container: docker.models.containers.Container): ...\n def _call_pypi_json_api(pkg_name: str, pkg_version: str): ...\n def _build_command(self, subcommands: List[str]): ...\n def _clone_repo(self, container: docker.models.containers.Container, github_url: str): ...\n def _install(self, container: docker.models.containers.Container): ...\n def _check(self, container: docker.models.containers.Container): ...\n def _list(self, container: docker.models.containers.Container): ...\n def run(self) -> PipCheckResult: ...\n\n self._pip_command = pip_command\n self._packages = packages\n self._stats = stats\n self._mmap = self._stats.stats_recorder.new_measurement_map()\n self._tmap = tag_map_module.TagMap()\n", "repository": "GoogleCloudPlatform/cloud-opensource-python", "test_name": "test__run_command_success", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000243.py"} {"focal_file": "aiortc-master/src/aiortc/clock.py", "focal_class": null, "focal_method": "current_ms", "tests": "import unittest\n\nclass Test_current_ms(unittest.TestCase):\n @patch('aiortc.clock.current_datetime')\n def test_current_ms(self, mock_now):\n mock_now.return_value = datetime.datetime(2018, 9, 11, tzinfo=datetime.timezone.utc)\n self.assertEqual(clock.current_ms(), 3745612800000)\n mock_now.return_value = datetime.datetime(2018, 9, 11, 0, 0, 1, tzinfo=datetime.timezone.utc)\n self.assertEqual(clock.current_ms(), 3745612801000)\n", "method_code": "def current_ms() -> int:\n delta = current_datetime() - NTP_EPOCH\n return int(delta.total_seconds() * 1000)", "context": "def current_ms() -> int: ...\ndef current_datetime() -> datetime.datetime: ...\ndef current_ms() -> int: ...\ndef current_ntp_time() -> int: ...\ndef datetime_from_ntp(ntp: int) -> datetime.datetime: ...\ndef datetime_to_ntp(dt: datetime.datetime) -> int: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000244.py"} {"focal_file": "aiortc-master/src/aiortc/clock.py", "focal_class": null, "focal_method": "datetime_from_ntp", "tests": "import unittest\n\nclass Test_datetime_from_ntp(unittest.TestCase):\n def test_datetime_from_ntp(self):\n dt = datetime.datetime(2018, 6, 28, 9, 3, 5, 423998, tzinfo=datetime.timezone.utc)\n self.assertEqual(clock.datetime_from_ntp(16059593044731306503), dt)\n", "method_code": "def datetime_from_ntp(ntp: int) -> datetime.datetime:\n seconds = ntp >> 32\n microseconds = (ntp & 4294967295) * 1000000 / (1 << 32)\n return NTP_EPOCH + datetime.timedelta(seconds=seconds, microseconds=microseconds)", "context": "def datetime_from_ntp(ntp: int) -> datetime.datetime: ...\ndef current_datetime() -> datetime.datetime: ...\ndef current_ms() -> int: ...\ndef current_ntp_time() -> int: ...\ndef datetime_from_ntp(ntp: int) -> datetime.datetime: ...\ndef datetime_to_ntp(dt: datetime.datetime) -> int: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_datetime_from_ntp", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000245.py"} {"focal_file": "aiortc-master/src/aiortc/clock.py", "focal_class": null, "focal_method": "datetime_to_ntp", "tests": "import unittest\n\nclass Test_datetime_to_ntp(unittest.TestCase):\n def test_datetime_to_ntp(self):\n dt = datetime.datetime(2018, 6, 28, 9, 3, 5, 423998, tzinfo=datetime.timezone.utc)\n self.assertEqual(clock.datetime_to_ntp(dt), 16059593044731306503)\n", "method_code": "def datetime_to_ntp(dt: datetime.datetime) -> int:\n delta = dt - NTP_EPOCH\n high = int(delta.total_seconds())\n low = round(delta.microseconds * (1 << 32) // 1000000)\n return high << 32 | low", "context": "def datetime_to_ntp(dt: datetime.datetime) -> int: ...\ndef current_datetime() -> datetime.datetime: ...\ndef current_ms() -> int: ...\ndef current_ntp_time() -> int: ...\ndef datetime_from_ntp(ntp: int) -> datetime.datetime: ...\ndef datetime_to_ntp(dt: datetime.datetime) -> int: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_datetime_to_ntp", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000246.py"} {"focal_file": "aiortc-master/src/aiortc/contrib/signaling.py", "focal_class": null, "focal_method": "object_from_string", "tests": "import unittest\n\nclass Test_object_from_string(unittest.TestCase):\n def test_bye_from_string(self):\n self.assertEqual(object_from_string('{\"type\": \"bye\"}'), BYE)\n\n def test_candidate_from_string(self):\n candidate = object_from_string('{\"candidate\": \"candidate:0 1 UDP 2122252543 192.168.99.7 33543 typ host\", \"id\": \"audio\", \"label\": 0, \"type\": \"candidate\"}')\n self.assertEqual(candidate.component, 1)\n self.assertEqual(candidate.foundation, '0')\n self.assertEqual(candidate.ip, '192.168.99.7')\n self.assertEqual(candidate.port, 33543)\n self.assertEqual(candidate.priority, 2122252543)\n self.assertEqual(candidate.protocol, 'UDP')\n self.assertEqual(candidate.sdpMid, 'audio')\n self.assertEqual(candidate.sdpMLineIndex, 0)\n self.assertEqual(candidate.type, 'host')\n", "method_code": "def object_from_string(message_str):\n message = json.loads(message_str)\n if message['type'] in ['answer', 'offer']:\n return RTCSessionDescription(**message)\n elif message['type'] == 'candidate' and message['candidate']:\n candidate = candidate_from_sdp(message['candidate'].split(':', 1)[1])\n candidate.sdpMid = message['id']\n candidate.sdpMLineIndex = message['label']\n return candidate\n elif message['type'] == 'bye':\n return BYE", "context": "def object_from_string(message_str): ...\ndef object_from_string(message_str): ...\ndef object_to_string(obj): ...\ndef add_signaling_arguments(parser): ...\ndef create_signaling(args): ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_bye_from_string", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000247.py"} {"focal_file": "aiortc-master/src/aiortc/contrib/signaling.py", "focal_class": null, "focal_method": "object_to_string", "tests": "import unittest\n\nclass Test_object_to_string(unittest.TestCase):\n def test_bye_to_string(self):\n self.assertEqual(object_to_string(BYE), '{\"type\": \"bye\"}')\n\n def test_candidate_to_string(self):\n candidate = RTCIceCandidate(component=1, foundation='0', ip='192.168.99.7', port=33543, priority=2122252543, protocol='UDP', type='host')\n candidate.sdpMid = 'audio'\n candidate.sdpMLineIndex = 0\n self.assertEqual(object_to_string(candidate), '{\"candidate\": \"candidate:0 1 UDP 2122252543 192.168.99.7 33543 typ host\", \"id\": \"audio\", \"label\": 0, \"type\": \"candidate\"}')\n", "method_code": "def object_to_string(obj):\n if isinstance(obj, RTCSessionDescription):\n message = {'sdp': obj.sdp, 'type': obj.type}\n elif isinstance(obj, RTCIceCandidate):\n message = {'candidate': 'candidate:' + candidate_to_sdp(obj), 'id': obj.sdpMid, 'label': obj.sdpMLineIndex, 'type': 'candidate'}\n else:\n assert obj is BYE\n message = {'type': 'bye'}\n return json.dumps(message, sort_keys=True)", "context": "def object_to_string(obj): ...\ndef object_from_string(message_str): ...\ndef object_to_string(obj): ...\ndef add_signaling_arguments(parser): ...\ndef create_signaling(args): ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_bye_to_string", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000248.py"} {"focal_file": "aiortc-master/src/aiortc/codecs/h264.py", "focal_class": null, "focal_method": "_split_bitstream", "tests": "import unittest\n\nclass Test_split_bitstream(unittest.TestCase):\n def test_split_bitstream(self):\n packages = list(H264Encoder._split_bitstream(b'\\x00\\x00\\x01\\x0cf\\x00\\x00\\x01\\x0cf'))\n self.assertEqual(len(packages), 2)\n packages = list(H264Encoder._split_bitstream(b'\\x00\\x00\\x00\\x01\\x0cf'))\n self.assertEqual(len(packages), 1)\n packages = list(H264Encoder._split_bitstream(b'\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x0cf\\x00\\x00\\x00\\x00\\x00'))\n self.assertEqual(len(packages), 1)\n", "method_code": " def _split_bitstream(buf: bytes) -> Iterator[bytes]:\n i = 0\n while True:\n while (buf[i] != 0 or buf[i + 1] != 0 or buf[i + 2] != 1) and (buf[i] != 0 or buf[i + 1] != 0 or buf[i + 2] != 0 or (buf[i + 3] != 1)):\n i += 1\n if i + 4 >= len(buf):\n return\n if buf[i] != 0 or buf[i + 1] != 0 or buf[i + 2] != 1:\n i += 1\n i += 3\n nal_start = i\n while (buf[i] != 0 or buf[i + 1] != 0 or buf[i + 2] != 0) and (buf[i] != 0 or buf[i + 1] != 0 or buf[i + 2] != 1):\n i += 1\n if i + 3 >= len(buf):\n nal_end = len(buf)\n yield buf[nal_start:nal_end]\n return\n nal_end = i\n yield buf[nal_start:nal_end]\n ", "context": "class H264Encoder(Encoder):\n @staticmethod\n def _split_bitstream(buf: bytes) -> Iterator[bytes]: ...\n def __init__(self) -> None: ...\n def _packetize_fu_a(data: bytes) -> List[bytes]: ...\n def _packetize_stap_a(data: bytes, packages_iterator: Iterator[bytes]) -> Tuple[bytes, bytes]: ...\n def _packetize(cls, packages: Iterator[bytes]) -> List[bytes]: ...\n def _encode_frame(self, frame: av.VideoFrame, force_keyframe: bool) -> Iterator[bytes]: ...\n def encode(self, frame: Frame, force_keyframe: bool=False) -> Tuple[List[bytes], int]: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_split_bitstream", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000249.py"} {"focal_file": "aiortc-master/src/aiortc/jitterbuffer.py", "focal_class": "JitterBuffer", "focal_method": "remove", "tests": "import unittest\n\nclass Test_JitterBuffer_remove(unittest.TestCase):\n def test_remove(self):\n jbuffer = JitterBuffer(capacity=4)\n jbuffer.add(RtpPacket(sequence_number=0, timestamp=1234))\n jbuffer.add(RtpPacket(sequence_number=1, timestamp=1234))\n jbuffer.add(RtpPacket(sequence_number=2, timestamp=1234))\n jbuffer.add(RtpPacket(sequence_number=3, timestamp=1234))\n self.assertEqual(jbuffer._origin, 0)\n self.assertPackets(jbuffer, [0, 1, 2, 3])\n jbuffer.remove(1)\n self.assertEqual(jbuffer._origin, 1)\n self.assertPackets(jbuffer, [None, 1, 2, 3])\n jbuffer.remove(2)\n self.assertEqual(jbuffer._origin, 3)\n self.assertPackets(jbuffer, [None, None, None, 3])\n", "method_code": " def remove(self, count: int) -> None:\n assert count <= self._capacity\n for i in range(count):\n pos = self._origin % self._capacity\n self._packets[pos] = None\n self._origin += 1\n ", "context": "class JitterBuffer():\n def remove(self, count: int) -> None: ...\n def __init__(self, capacity: int, prefetch: int=0) -> None: ...\n def capacity(self) -> int: ...\n def add(self, packet: RtpPacket) -> Optional[JitterFrame]: ...\n def _remove_frame(self, sequence_number: int) -> Optional[JitterFrame]: ...\n\n self._capacity = capacity\n self._prefetch = prefetch\n", "repository": "0julio0/Icom_openpose", "test_name": "test_remove", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000250.py"} {"focal_file": "aiortc-master/src/aiortc/rate.py", "focal_class": "RateCounter", "focal_method": "add", "tests": "import unittest\n\nclass Test_RateCounter_add(unittest.TestCase):\n def test_add(self):\n counter = RateCounter(10)\n counter.add(500, 123)\n self.assertEqual(counter._buckets, [RateBucket(1, 500), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket()])\n self.assertEqual(counter._origin_index, 0)\n self.assertEqual(counter._origin_ms, 123)\n self.assertEqual(counter._total, RateBucket(1, 500))\n self.assertIsNone(counter.rate(123))\n counter.add(501, 123)\n self.assertEqual(counter._buckets, [RateBucket(2, 1001), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket()])\n self.assertEqual(counter._origin_index, 0)\n self.assertEqual(counter._origin_ms, 123)\n self.assertEqual(counter._total, RateBucket(2, 1001))\n self.assertIsNone(counter.rate(123))\n counter.add(502, 125)\n self.assertEqual(counter._buckets, [RateBucket(2, 1001), RateBucket(), RateBucket(1, 502), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket(), RateBucket()])\n self.assertEqual(counter._origin_index, 0)\n self.assertEqual(counter._origin_ms, 123)\n self.assertEqual(counter._total, RateBucket(3, 1503))\n self.assertEqual(counter.rate(125), 4008000)\n counter.add(503, 128)\n self.assertEqual(counter._buckets, [RateBucket(2, 1001), RateBucket(), RateBucket(1, 502), RateBucket(), RateBucket(), RateBucket(1, 503), RateBucket(), RateBucket(), RateBucket(), RateBucket()])\n self.assertEqual(counter._origin_index, 0)\n self.assertEqual(counter._origin_ms, 123)\n self.assertEqual(counter._total, RateBucket(4, 2006))\n self.assertEqual(counter.rate(128), 2674667)\n counter.add(504, 132)\n self.assertEqual(counter._buckets, [RateBucket(2, 1001), RateBucket(), RateBucket(1, 502), RateBucket(), RateBucket(), RateBucket(1, 503), RateBucket(), RateBucket(), RateBucket(), RateBucket(1, 504)])\n self.assertEqual(counter._origin_index, 0)\n self.assertEqual(counter._origin_ms, 123)\n self.assertEqual(counter._total, RateBucket(5, 2510))\n self.assertEqual(counter.rate(132), 2008000)\n counter.add(505, 134)\n self.assertEqual(counter._buckets, [RateBucket(), RateBucket(1, 505), RateBucket(1, 502), RateBucket(), RateBucket(), RateBucket(1, 503), RateBucket(), RateBucket(), RateBucket(), RateBucket(1, 504)])\n self.assertEqual(counter._origin_index, 2)\n self.assertEqual(counter._origin_ms, 125)\n self.assertEqual(counter._total, RateBucket(4, 2014))\n self.assertEqual(counter.rate(134), 1611200)\n counter.add(506, 135)\n self.assertEqual(counter._buckets, [RateBucket(), RateBucket(1, 505), RateBucket(1, 506), RateBucket(), RateBucket(), RateBucket(1, 503), RateBucket(), RateBucket(), RateBucket(), RateBucket(1, 504)])\n self.assertEqual(counter._origin_index, 3)\n self.assertEqual(counter._origin_ms, 126)\n self.assertEqual(counter._total, RateBucket(4, 2018))\n self.assertEqual(counter.rate(135), 1614400)\n", "method_code": " def add(self, value: int, now_ms: int) -> None:\n if self._origin_ms is None:\n self._origin_ms = now_ms\n else:\n self._erase_old(now_ms)\n index = (self._origin_index + now_ms - self._origin_ms) % self._window_size\n self._buckets[index].count += 1\n self._buckets[index].value += value\n self._total.count += 1\n self._total.value += value\n ", "context": "class RateCounter():\n def add(self, value: int, now_ms: int) -> None: ...\n def __init__(self, window_size: int, scale: int=8000) -> None: ...\n def rate(self, now_ms: int) -> Optional[int]: ...\n def reset(self) -> None: ...\n def _erase_old(self, now_ms: int) -> None: ...\n\n self._origin_index = 0\n self._scale = scale\n self._window_size = window_size\n", "repository": "0julio0/Icom_openpose", "test_name": "test_add", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000251.py"} {"focal_file": "aiortc-master/src/aiortc/rtcdtlstransport.py", "focal_class": "RtpRouter", "focal_method": "route_rtcp", "tests": "import unittest\n\nclass Test_RtpRouter_route_rtcp(unittest.TestCase):\n def test_route_rtcp(self):\n receiver = object()\n sender = object()\n router = RtpRouter()\n router.register_receiver(receiver, ssrcs=[1234, 2345], payload_types=[96, 97])\n router.register_sender(sender, ssrc=3456)\n packet = RtcpByePacket(sources=[1234, 2345])\n self.assertEqual(router.route_rtcp(packet), set([receiver]))\n packet = RtcpRrPacket(ssrc=1234, reports=[RtcpReceiverInfo(ssrc=3456, fraction_lost=0, packets_lost=0, highest_sequence=630, jitter=1906, lsr=0, dlsr=0)])\n self.assertEqual(router.route_rtcp(packet), set([sender]))\n packet = RtcpSrPacket(ssrc=1234, sender_info=RtcpSenderInfo(ntp_timestamp=0, rtp_timestamp=0, packet_count=0, octet_count=0), reports=[RtcpReceiverInfo(ssrc=3456, fraction_lost=0, packets_lost=0, highest_sequence=630, jitter=1906, lsr=0, dlsr=0)])\n self.assertEqual(router.route_rtcp(packet), set([receiver, sender]))\n packet = RtcpPsfbPacket(fmt=RTCP_PSFB_PLI, ssrc=1234, media_ssrc=3456)\n self.assertEqual(router.route_rtcp(packet), set([sender]))\n packet = RtcpPsfbPacket(fmt=RTCP_PSFB_APP, ssrc=1234, media_ssrc=0, fci=pack_remb_fci(4160000, [3456]))\n self.assertEqual(router.route_rtcp(packet), set([sender]))\n packet = RtcpPsfbPacket(fmt=RTCP_PSFB_APP, ssrc=1234, media_ssrc=0, fci=b'JUNK')\n self.assertEqual(router.route_rtcp(packet), set())\n packet = RtcpRtpfbPacket(fmt=RTCP_RTPFB_NACK, ssrc=1234, media_ssrc=3456)\n self.assertEqual(router.route_rtcp(packet), set([sender]))\n", "method_code": " def route_rtcp(self, packet: AnyRtcpPacket) -> Set:\n recipients = set()\n \n def add_recipient(recipient) -> None:\n if recipient is not None:\n recipients.add(recipient)\n if isinstance(packet, RtcpSrPacket):\n add_recipient(self.ssrc_table.get(packet.ssrc))\n elif isinstance(packet, RtcpByePacket):\n for source in packet.sources:\n add_recipient(self.ssrc_table.get(source))\n if isinstance(packet, (RtcpRrPacket, RtcpSrPacket)):\n for report in packet.reports:\n add_recipient(self.senders.get(report.ssrc))\n elif isinstance(packet, (RtcpPsfbPacket, RtcpRtpfbPacket)):\n add_recipient(self.senders.get(packet.media_ssrc))\n if isinstance(packet, RtcpPsfbPacket) and packet.fmt == rtp.RTCP_PSFB_APP:\n try:\n for ssrc in rtp.unpack_remb_fci(packet.fci)[1]:\n add_recipient(self.senders.get(ssrc))\n except ValueError:\n pass\n return recipients\n ", "context": "class RtpRouter():\n def route_rtcp(self, packet: AnyRtcpPacket) -> Set: ...\n def __init__(self) -> None: ...\n def register_receiver(self, receiver, ssrcs: List[int], payload_types: List[int], mid: Optional[str]=None): ...\n def register_sender(self, sender, ssrc: int) -> None: ...\n def route_rtp(self, packet: RtpPacket) -> Optional[Any]: ...\n def unregister_receiver(self, receiver) -> None: ...\n def unregister_sender(self, sender) -> None: ...\n def __discard(self, d: Dict, value: Any) -> None: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_route_rtcp", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000252.py"} {"focal_file": "aiortc-master/src/aiortc/rtcdtlstransport.py", "focal_class": "RtpRouter", "focal_method": "route_rtp", "tests": "import unittest\n\nclass Test_RtpRouter_route_rtp(unittest.TestCase):\n def test_route_rtp(self):\n receiver1 = object()\n receiver2 = object()\n router = RtpRouter()\n router.register_receiver(receiver1, ssrcs=[1234, 2345], payload_types=[96, 97])\n router.register_receiver(receiver2, ssrcs=[3456, 4567], payload_types=[98, 99])\n self.assertEqual(router.route_rtp(RtpPacket(ssrc=1234, payload_type=96)), receiver1)\n self.assertEqual(router.route_rtp(RtpPacket(ssrc=2345, payload_type=97)), receiver1)\n self.assertEqual(router.route_rtp(RtpPacket(ssrc=3456, payload_type=98)), receiver2)\n self.assertEqual(router.route_rtp(RtpPacket(ssrc=4567, payload_type=99)), receiver2)\n self.assertEqual(router.route_rtp(RtpPacket(ssrc=5678, payload_type=96)), receiver1)\n self.assertEqual(router.ssrc_table[5678], receiver1)\n self.assertEqual(router.route_rtp(RtpPacket(ssrc=6789, payload_type=100)), None)\n", "method_code": " def route_rtp(self, packet: RtpPacket) -> Optional[Any]:\n ssrc_receiver = self.ssrc_table.get(packet.ssrc)\n pt_receiver = self.payload_type_table.get(packet.payload_type)\n if ssrc_receiver is not None and ssrc_receiver == pt_receiver:\n return ssrc_receiver\n if ssrc_receiver is None and pt_receiver is not None:\n self.ssrc_table[packet.ssrc] = pt_receiver\n return pt_receiver\n return None\n ", "context": "class RtpRouter():\n def route_rtp(self, packet: RtpPacket) -> Optional[Any]: ...\n def __init__(self) -> None: ...\n def register_receiver(self, receiver, ssrcs: List[int], payload_types: List[int], mid: Optional[str]=None): ...\n def register_sender(self, sender, ssrc: int) -> None: ...\n def route_rtcp(self, packet: AnyRtcpPacket) -> Set: ...\n def unregister_receiver(self, receiver) -> None: ...\n def unregister_sender(self, sender) -> None: ...\n def __discard(self, d: Dict, value: Any) -> None: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_route_rtp", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000253.py"} {"focal_file": "aiortc-master/src/aiortc/rtcicetransport.py", "focal_class": null, "focal_method": "parse_stun_turn_uri", "tests": "import unittest\n\nclass Test_parse_stun_turn_uri(unittest.TestCase):\n def test_invalid_uri(self):\n with self.assertRaises(ValueError) as cm:\n parse_stun_turn_uri('stun')\n self.assertEqual(str(cm.exception), 'malformed uri')\n\n def test_stun_with_port(self):\n uri = parse_stun_turn_uri('stun:stun.l.google.com:19302')\n self.assertEqual(uri, {'host': 'stun.l.google.com', 'port': 19302, 'scheme': 'stun'})\n\n def test_turn(self):\n uri = parse_stun_turn_uri('turn:1.2.3.4')\n self.assertEqual(uri, {'host': '1.2.3.4', 'port': 3478, 'scheme': 'turn', 'transport': 'udp'})\n\n def test_turns(self):\n uri = parse_stun_turn_uri('turns:1.2.3.4')\n self.assertEqual(uri, {'host': '1.2.3.4', 'port': 5349, 'scheme': 'turns', 'transport': 'tcp'})\n", "method_code": "def parse_stun_turn_uri(uri: str) -> Dict[str, Any]:\n if uri.startswith('stun'):\n match = STUN_REGEX.fullmatch(uri)\n elif uri.startswith('turn'):\n match = TURN_REGEX.fullmatch(uri)\n else:\n raise ValueError('malformed uri: invalid scheme')\n if not match:\n raise ValueError('malformed uri')\n parsed: Dict[str, Any] = match.groupdict()\n if parsed['port']:\n parsed['port'] = int(parsed['port'])\n elif parsed['scheme'] in ['stuns', 'turns']:\n parsed['port'] = 5349\n else:\n parsed['port'] = 3478\n if parsed['scheme'] == 'turn' and (not parsed['transport']):\n parsed['transport'] = 'udp'\n elif parsed['scheme'] == 'turns' and (not parsed['transport']):\n parsed['transport'] = 'tcp'\n return parsed", "context": "def parse_stun_turn_uri(uri: str) -> Dict[str, Any]: ...\ndef candidate_from_aioice(x: Candidate) -> RTCIceCandidate: ...\ndef candidate_to_aioice(x: RTCIceCandidate) -> Candidate: ...\ndef connection_kwargs(servers: List[RTCIceServer]) -> Dict[str, Any]: ...\ndef parse_stun_turn_uri(uri: str) -> Dict[str, Any]: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_invalid_uri", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000254.py"} {"focal_file": "aiortc-master/src/aiortc/rtcpeerconnection.py", "focal_class": null, "focal_method": "find_common_codecs", "tests": "import unittest\n\nclass Test_find_common_codecs(unittest.TestCase):\n def test_common_dynamic(self):\n local_codecs = [RTCRtpCodecParameters(mimeType='audio/opus', clockRate=48000, channels=2, payloadType=96), RTCRtpCodecParameters(mimeType='audio/PCMU', clockRate=8000, channels=1, payloadType=0), RTCRtpCodecParameters(mimeType='audio/PCMA', clockRate=8000, channels=1, payloadType=8)]\n remote_codecs = [RTCRtpCodecParameters(mimeType='audio/opus', clockRate=48000, channels=2, payloadType=100), RTCRtpCodecParameters(mimeType='audio/PCMA', clockRate=8000, channels=1, payloadType=8)]\n common = find_common_codecs(local_codecs, remote_codecs)\n self.assertEqual(common, [RTCRtpCodecParameters(mimeType='audio/opus', clockRate=48000, channels=2, payloadType=100), RTCRtpCodecParameters(mimeType='audio/PCMA', clockRate=8000, channels=1, payloadType=8)])\n\n def test_common_feedback(self):\n local_codecs = [RTCRtpCodecParameters(mimeType='video/VP8', clockRate=90000, payloadType=100, rtcpFeedback=[RTCRtcpFeedback(type='nack'), RTCRtcpFeedback(type='nack', parameter='pli')])]\n remote_codecs = [RTCRtpCodecParameters(mimeType='video/VP8', clockRate=90000, payloadType=120, rtcpFeedback=[RTCRtcpFeedback(type='nack'), RTCRtcpFeedback(type='nack', parameter='sli')])]\n common = find_common_codecs(local_codecs, remote_codecs)\n self.assertEqual(len(common), 1)\n self.assertEqual(common[0].clockRate, 90000)\n self.assertEqual(common[0].name, 'VP8')\n self.assertEqual(common[0].payloadType, 120)\n self.assertEqual(common[0].rtcpFeedback, [RTCRtcpFeedback(type='nack')])\n", "method_code": "def find_common_codecs(local_codecs: List[RTCRtpCodecParameters], remote_codecs: List[RTCRtpCodecParameters]) -> List[RTCRtpCodecParameters]:\n common = []\n common_base: Dict[int, RTCRtpCodecParameters] = {}\n for c in remote_codecs:\n if is_rtx(c):\n if c.parameters.get('apt') in common_base:\n base = common_base[c.parameters['apt']]\n if c.clockRate == base.clockRate:\n common.append(copy.deepcopy(c))\n continue\n for codec in local_codecs:\n if codec.mimeType.lower() == c.mimeType.lower() and codec.clockRate == c.clockRate:\n if codec.mimeType.lower() == 'video/h264':\n parameters_compatible = True\n for param in ['packetization-mode', 'profile-level-id']:\n if c.parameters.get(param) != codec.parameters.get(param):\n parameters_compatible = False\n if not parameters_compatible:\n continue\n codec = copy.deepcopy(codec)\n if c.payloadType in rtp.DYNAMIC_PAYLOAD_TYPES:\n codec.payloadType = c.payloadType\n codec.rtcpFeedback = list(filter(lambda x: x in c.rtcpFeedback, codec.rtcpFeedback))\n common.append(codec)\n common_base[codec.payloadType] = codec\n break\n return common", "context": "def find_common_codecs(local_codecs: List[RTCRtpCodecParameters], remote_codecs: List[RTCRtpCodecParameters]) -> List[RTCRtpCodecParameters]: ...\ndef filter_preferred_codecs(codecs: List[RTCRtpCodecParameters], preferred: List[RTCRtpCodecCapability]) -> List[RTCRtpCodecParameters]: ...\ndef find_common_codecs(local_codecs: List[RTCRtpCodecParameters], remote_codecs: List[RTCRtpCodecParameters]) -> List[RTCRtpCodecParameters]: ...\ndef find_common_header_extensions(local_extensions: List[RTCRtpHeaderExtensionParameters], remote_extensions: List[RTCRtpHeaderExtensionParameters]) -> List[RTCRtpHeaderExtensionParameters]: ...\ndef add_transport_description(media: sdp.MediaDescription, dtlsTransport: RTCDtlsTransport) -> None: ...\ndef add_remote_candidates(iceTransport: RTCIceTransport, media: sdp.MediaDescription) -> None: ...\ndef allocate_mid(mids: Set[str]) -> str: ...\ndef create_media_description_for_sctp(sctp: RTCSctpTransport, legacy: bool, mid: str) -> sdp.MediaDescription: ...\ndef create_media_description_for_transceiver(transceiver: RTCRtpTransceiver, cname: str, direction: str, mid: str) -> sdp.MediaDescription: ...\ndef and_direction(a: str, b: str) -> str: ...\ndef or_direction(a: str, b: str) -> str: ...\ndef reverse_direction(direction: str) -> str: ...\ndef wrap_session_description(session_description: Optional[sdp.SessionDescription]) -> Optional[RTCSessionDescription]: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_common_dynamic", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000255.py"} {"focal_file": "aiortc-master/src/aiortc/rtcpeerconnection.py", "focal_class": null, "focal_method": "filter_preferred_codecs", "tests": "import unittest\n\nclass Test_filter_preferred_codecs(unittest.TestCase):\n def test_filter_preferred(self):\n codecs = [RTCRtpCodecParameters(mimeType='video/VP8', clockRate=90000, payloadType=100), RTCRtpCodecParameters(mimeType='video/rtx', clockRate=90000, payloadType=101, parameters={'apt': 100}), RTCRtpCodecParameters(mimeType='video/H264', clockRate=90000, payloadType=102), RTCRtpCodecParameters(mimeType='video/rtx', clockRate=90000, payloadType=103, parameters={'apt': 102})]\n self.assertEqual(filter_preferred_codecs(codecs, []), codecs)\n self.assertEqual(filter_preferred_codecs(codecs, [RTCRtpCodecCapability(mimeType='video/VP8', clockRate=90000), RTCRtpCodecCapability(mimeType='video/rtx', clockRate=90000), RTCRtpCodecCapability(mimeType='video/H264', clockRate=90000)]), [RTCRtpCodecParameters(mimeType='video/VP8', clockRate=90000, payloadType=100), RTCRtpCodecParameters(mimeType='video/rtx', clockRate=90000, payloadType=101, parameters={'apt': 100}), RTCRtpCodecParameters(mimeType='video/H264', clockRate=90000, payloadType=102), RTCRtpCodecParameters(mimeType='video/rtx', clockRate=90000, payloadType=103, parameters={'apt': 102})])\n self.assertEqual(filter_preferred_codecs(codecs, [RTCRtpCodecCapability(mimeType='video/H264', clockRate=90000), RTCRtpCodecCapability(mimeType='video/rtx', clockRate=90000), RTCRtpCodecCapability(mimeType='video/VP8', clockRate=90000)]), [RTCRtpCodecParameters(mimeType='video/H264', clockRate=90000, payloadType=102), RTCRtpCodecParameters(mimeType='video/rtx', clockRate=90000, payloadType=103, parameters={'apt': 102}), RTCRtpCodecParameters(mimeType='video/VP8', clockRate=90000, payloadType=100), RTCRtpCodecParameters(mimeType='video/rtx', clockRate=90000, payloadType=101, parameters={'apt': 100})])\n self.assertEqual(filter_preferred_codecs(codecs, [RTCRtpCodecCapability(mimeType='video/VP8', clockRate=90000), RTCRtpCodecCapability(mimeType='video/H264', clockRate=90000)]), [RTCRtpCodecParameters(mimeType='video/VP8', clockRate=90000, payloadType=100), RTCRtpCodecParameters(mimeType='video/H264', clockRate=90000, payloadType=102)])\n", "method_code": "def filter_preferred_codecs(codecs: List[RTCRtpCodecParameters], preferred: List[RTCRtpCodecCapability]) -> List[RTCRtpCodecParameters]:\n if not preferred:\n return codecs\n rtx_codecs = list(filter(is_rtx, codecs))\n rtx_enabled = next(filter(is_rtx, preferred), None) is not None\n filtered = []\n for pref in filter(lambda x: not is_rtx(x), preferred):\n for codec in codecs:\n if codec.mimeType.lower() == pref.mimeType.lower() and codec.parameters == pref.parameters:\n filtered.append(codec)\n if rtx_enabled:\n for rtx in rtx_codecs:\n if rtx.parameters['apt'] == codec.payloadType:\n filtered.append(rtx)\n break\n break\n return filtered", "context": "def filter_preferred_codecs(codecs: List[RTCRtpCodecParameters], preferred: List[RTCRtpCodecCapability]) -> List[RTCRtpCodecParameters]: ...\ndef filter_preferred_codecs(codecs: List[RTCRtpCodecParameters], preferred: List[RTCRtpCodecCapability]) -> List[RTCRtpCodecParameters]: ...\ndef find_common_codecs(local_codecs: List[RTCRtpCodecParameters], remote_codecs: List[RTCRtpCodecParameters]) -> List[RTCRtpCodecParameters]: ...\ndef find_common_header_extensions(local_extensions: List[RTCRtpHeaderExtensionParameters], remote_extensions: List[RTCRtpHeaderExtensionParameters]) -> List[RTCRtpHeaderExtensionParameters]: ...\ndef add_transport_description(media: sdp.MediaDescription, dtlsTransport: RTCDtlsTransport) -> None: ...\ndef add_remote_candidates(iceTransport: RTCIceTransport, media: sdp.MediaDescription) -> None: ...\ndef allocate_mid(mids: Set[str]) -> str: ...\ndef create_media_description_for_sctp(sctp: RTCSctpTransport, legacy: bool, mid: str) -> sdp.MediaDescription: ...\ndef create_media_description_for_transceiver(transceiver: RTCRtpTransceiver, cname: str, direction: str, mid: str) -> sdp.MediaDescription: ...\ndef and_direction(a: str, b: str) -> str: ...\ndef or_direction(a: str, b: str) -> str: ...\ndef reverse_direction(direction: str) -> str: ...\ndef wrap_session_description(session_description: Optional[sdp.SessionDescription]) -> Optional[RTCSessionDescription]: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_filter_preferred", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000256.py"} {"focal_file": "aiortc-master/src/aiortc/rtcpeerconnection.py", "focal_class": "RTCPeerConnection", "focal_method": "addTrack", "tests": "import unittest\n\nclass Test_RTCPeerConnection_addTrack(unittest.TestCase):\n def test_addTrack_audio(self):\n pc = RTCPeerConnection()\n track1 = AudioStreamTrack()\n sender1 = pc.addTrack(track1)\n self.assertIsNotNone(sender1)\n self.assertEqual(sender1.track, track1)\n self.assertEqual(pc.getSenders(), [sender1])\n self.assertEqual(len(pc.getTransceivers()), 1)\n with self.assertRaises(InvalidAccessError) as cm:\n pc.addTrack(track1)\n self.assertEqual(str(cm.exception), 'Track already has a sender')\n track2 = AudioStreamTrack()\n sender2 = pc.addTrack(track2)\n self.assertIsNotNone(sender2)\n self.assertEqual(sender2.track, track2)\n self.assertEqual(pc.getSenders(), [sender1, sender2])\n self.assertEqual(len(pc.getTransceivers()), 2)\n\n def test_addTrack_bogus(self):\n pc = RTCPeerConnection()\n with self.assertRaises(InternalError) as cm:\n pc.addTrack(BogusStreamTrack())\n self.assertEqual(str(cm.exception), 'Invalid track kind \"bogus\"')\n\n def test_addTrack_video(self):\n pc = RTCPeerConnection()\n video_track1 = VideoStreamTrack()\n video_sender1 = pc.addTrack(video_track1)\n self.assertIsNotNone(video_sender1)\n self.assertEqual(video_sender1.track, video_track1)\n self.assertEqual(pc.getSenders(), [video_sender1])\n self.assertEqual(len(pc.getTransceivers()), 1)\n with self.assertRaises(InvalidAccessError) as cm:\n pc.addTrack(video_track1)\n self.assertEqual(str(cm.exception), 'Track already has a sender')\n video_track2 = VideoStreamTrack()\n video_sender2 = pc.addTrack(video_track2)\n self.assertIsNotNone(video_sender2)\n self.assertEqual(video_sender2.track, video_track2)\n self.assertEqual(pc.getSenders(), [video_sender1, video_sender2])\n self.assertEqual(len(pc.getTransceivers()), 2)\n audio_track = AudioStreamTrack()\n audio_sender = pc.addTrack(audio_track)\n self.assertIsNotNone(audio_sender)\n self.assertEqual(audio_sender.track, audio_track)\n self.assertEqual(pc.getSenders(), [video_sender1, video_sender2, audio_sender])\n self.assertEqual(len(pc.getTransceivers()), 3)\n\n def test_addTrack_closed(self):\n pc = RTCPeerConnection()\n run(pc.close())\n with self.assertRaises(InvalidStateError) as cm:\n pc.addTrack(AudioStreamTrack())\n self.assertEqual(str(cm.exception), 'RTCPeerConnection is closed')\n", "method_code": " def addTrack(self, track: MediaStreamTrack) -> RTCRtpSender:\n \"\"\"\n Add a :class:`MediaStreamTrack` to the set of media tracks which\n will be transmitted to the remote peer.\n \"\"\"\n self.__assertNotClosed()\n if track.kind not in ['audio', 'video']:\n raise InternalError(f'Invalid track kind \"{track.kind}\"')\n self.__assertTrackHasNoSender(track)\n for transceiver in self.__transceivers:\n if transceiver.kind == track.kind:\n if transceiver.sender.track is None:\n transceiver.sender.replaceTrack(track)\n transceiver.direction = or_direction(transceiver.direction, 'sendonly')\n return transceiver.sender\n transceiver = self.__createTransceiver(direction='sendrecv', kind=track.kind, sender_track=track)\n return transceiver.sender\n ", "context": "class RTCPeerConnection(AsyncIOEventEmitter):\n def addTrack(self, track: MediaStreamTrack) -> RTCRtpSender: ...\n def __init__(self, configuration: Optional[RTCConfiguration]=None) -> None: ...\n def iceConnectionState(self) -> str: ...\n def iceGatheringState(self) -> str: ...\n def localDescription(self) -> RTCSessionDescription: ...\n def remoteDescription(self) -> RTCSessionDescription: ...\n def sctp(self) -> Optional[RTCSctpTransport]: ...\n def signalingState(self): ...\n def addIceCandidate(self, candidate: RTCIceCandidate) -> None: ...\n def addTransceiver(self, trackOrKind: Union[str, MediaStreamTrack], direction: str='sendrecv') -> RTCRtpTransceiver: ...\n def close(self): ...\n def createAnswer(self): ...\n def createDataChannel(self, label, maxPacketLifeTime=None, maxRetransmits=None, ordered=True, protocol='', negotiated=False, id=None): ...\n def createOffer(self) -> RTCSessionDescription: ...\n def getReceivers(self) -> List[RTCRtpReceiver]: ...\n def getSenders(self) -> List[RTCRtpSender]: ...\n def getStats(self) -> RTCStatsReport: ...\n def getTransceivers(self) -> List[RTCRtpTransceiver]: ...\n def setLocalDescription(self, sessionDescription: RTCSessionDescription) -> None: ...\n def setRemoteDescription(self, sessionDescription: RTCSessionDescription) -> None: ...\n def __connect(self) -> None: ...\n def __gather(self) -> None: ...\n def __assertNotClosed(self) -> None: ...\n def __assertTrackHasNoSender(self, track: MediaStreamTrack) -> None: ...\n def __createDtlsTransport(self) -> RTCDtlsTransport: ...\n def __createSctpTransport(self) -> None: ...\n def __createTransceiver(self, direction: str, kind: str, sender_track=None) -> RTCRtpTransceiver: ...\n def __getTransceiverByMid(self, mid: str) -> Optional[RTCRtpTransceiver]: ...\n def __getTransceiverByMLineIndex(self, index: int) -> Optional[RTCRtpTransceiver]: ...\n def __localDescription(self) -> Optional[sdp.SessionDescription]: ...\n def __localRtp(self, transceiver: RTCRtpTransceiver) -> RTCRtpSendParameters: ...\n def __remoteDescription(self) -> Optional[sdp.SessionDescription]: ...\n def __remoteRtp(self, transceiver: RTCRtpTransceiver) -> RTCRtpReceiveParameters: ...\n def __setSignalingState(self, state: str) -> None: ...\n def __updateIceConnectionState(self) -> None: ...\n def __updateIceGatheringState(self) -> None: ...\n def __validate_description(self, description: sdp.SessionDescription, is_local: bool) -> None: ...\n\n self.__certificates = [RTCCertificate.generateCertificate()]\n self.__cname = f'{uuid.uuid4()}'\n self.__configuration = configuration or RTCConfiguration()\n self._sctpLegacySdp = True\n self.__sctpRemoteCaps = None\n self.__stream_id = str(uuid.uuid4())\n self.__iceConnectionState = 'new'\n self.__iceGatheringState = 'new'\n self.__isClosed = False\n self.__signalingState = 'stable'\n", "repository": "0julio0/Icom_openpose", "test_name": "test_addTrack_audio", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000257.py"} {"focal_file": "aiortc-master/src/aiortc/rtcpeerconnection.py", "focal_class": "RTCPeerConnection", "focal_method": "addTransceiver", "tests": "import unittest\n\nclass Test_RTCPeerConnection_addTransceiver(unittest.TestCase):\n def test_addTransceiver_audio_inactive(self):\n pc = RTCPeerConnection()\n transceiver = pc.addTransceiver('audio', direction='inactive')\n self.assertIsNotNone(transceiver)\n self.assertEqual(transceiver.currentDirection, None)\n self.assertEqual(transceiver.direction, 'inactive')\n self.assertEqual(transceiver.sender.track, None)\n self.assertEqual(transceiver.stopped, False)\n self.assertEqual(pc.getSenders(), [transceiver.sender])\n self.assertEqual(len(pc.getTransceivers()), 1)\n track = AudioStreamTrack()\n pc.addTrack(track)\n self.assertEqual(transceiver.currentDirection, None)\n self.assertEqual(transceiver.direction, 'sendonly')\n self.assertEqual(transceiver.sender.track, track)\n self.assertEqual(transceiver.stopped, False)\n self.assertEqual(len(pc.getTransceivers()), 1)\n run(transceiver.stop())\n self.assertEqual(transceiver.currentDirection, None)\n self.assertEqual(transceiver.direction, 'sendonly')\n self.assertEqual(transceiver.sender.track, track)\n self.assertEqual(transceiver.stopped, True)\n\n def test_addTransceiver_audio_sendrecv(self):\n pc = RTCPeerConnection()\n transceiver = pc.addTransceiver('audio')\n self.assertIsNotNone(transceiver)\n self.assertEqual(transceiver.currentDirection, None)\n self.assertEqual(transceiver.direction, 'sendrecv')\n self.assertEqual(transceiver.sender.track, None)\n self.assertEqual(transceiver.stopped, False)\n self.assertEqual(pc.getSenders(), [transceiver.sender])\n self.assertEqual(len(pc.getTransceivers()), 1)\n track = AudioStreamTrack()\n pc.addTrack(track)\n self.assertEqual(transceiver.currentDirection, None)\n self.assertEqual(transceiver.direction, 'sendrecv')\n self.assertEqual(transceiver.sender.track, track)\n self.assertEqual(transceiver.stopped, False)\n self.assertEqual(len(pc.getTransceivers()), 1)\n\n def test_addTransceiver_audio_track(self):\n pc = RTCPeerConnection()\n track1 = AudioStreamTrack()\n transceiver1 = pc.addTransceiver(track1)\n self.assertIsNotNone(transceiver1)\n self.assertEqual(transceiver1.currentDirection, None)\n self.assertEqual(transceiver1.direction, 'sendrecv')\n self.assertEqual(transceiver1.sender.track, track1)\n self.assertEqual(transceiver1.stopped, False)\n self.assertEqual(pc.getSenders(), [transceiver1.sender])\n self.assertEqual(len(pc.getTransceivers()), 1)\n with self.assertRaises(InvalidAccessError) as cm:\n pc.addTransceiver(track1)\n self.assertEqual(str(cm.exception), 'Track already has a sender')\n track2 = AudioStreamTrack()\n transceiver2 = pc.addTransceiver(track2)\n self.assertIsNotNone(transceiver2)\n self.assertEqual(transceiver2.currentDirection, None)\n self.assertEqual(transceiver2.direction, 'sendrecv')\n self.assertEqual(transceiver2.sender.track, track2)\n self.assertEqual(transceiver2.stopped, False)\n self.assertEqual(pc.getSenders(), [transceiver1.sender, transceiver2.sender])\n self.assertEqual(len(pc.getTransceivers()), 2)\n\n def test_addTransceiver_bogus_direction(self):\n pc = RTCPeerConnection()\n with self.assertRaises(InternalError) as cm:\n pc.addTransceiver('audio', direction='bogus')\n self.assertEqual(str(cm.exception), 'Invalid direction \"bogus\"')\n\n def test_addTransceiver_bogus_kind(self):\n pc = RTCPeerConnection()\n with self.assertRaises(InternalError) as cm:\n pc.addTransceiver('bogus')\n self.assertEqual(str(cm.exception), 'Invalid track kind \"bogus\"')\n\n def test_addTransceiver_bogus_track(self):\n pc = RTCPeerConnection()\n with self.assertRaises(InternalError) as cm:\n pc.addTransceiver(BogusStreamTrack())\n self.assertEqual(str(cm.exception), 'Invalid track kind \"bogus\"')\n", "method_code": " def addTransceiver(self, trackOrKind: Union[str, MediaStreamTrack], direction: str='sendrecv') -> RTCRtpTransceiver:\n \"\"\"\n Add a new :class:`RTCRtpTransceiver`.\n \"\"\"\n self.__assertNotClosed()\n if isinstance(trackOrKind, MediaStreamTrack):\n kind = trackOrKind.kind\n track = trackOrKind\n else:\n kind = trackOrKind\n track = None\n if kind not in ['audio', 'video']:\n raise InternalError(f'Invalid track kind \"{kind}\"')\n if direction not in sdp.DIRECTIONS:\n raise InternalError(f'Invalid direction \"{direction}\"')\n if track:\n self.__assertTrackHasNoSender(track)\n return self.__createTransceiver(direction=direction, kind=kind, sender_track=track)\n ", "context": "class RTCPeerConnection(AsyncIOEventEmitter):\n def addTransceiver(self, trackOrKind: Union[str, MediaStreamTrack], direction: str='sendrecv') -> RTCRtpTransceiver: ...\n def __init__(self, configuration: Optional[RTCConfiguration]=None) -> None: ...\n def iceConnectionState(self) -> str: ...\n def iceGatheringState(self) -> str: ...\n def localDescription(self) -> RTCSessionDescription: ...\n def remoteDescription(self) -> RTCSessionDescription: ...\n def sctp(self) -> Optional[RTCSctpTransport]: ...\n def signalingState(self): ...\n def addIceCandidate(self, candidate: RTCIceCandidate) -> None: ...\n def addTrack(self, track: MediaStreamTrack) -> RTCRtpSender: ...\n def close(self): ...\n def createAnswer(self): ...\n def createDataChannel(self, label, maxPacketLifeTime=None, maxRetransmits=None, ordered=True, protocol='', negotiated=False, id=None): ...\n def createOffer(self) -> RTCSessionDescription: ...\n def getReceivers(self) -> List[RTCRtpReceiver]: ...\n def getSenders(self) -> List[RTCRtpSender]: ...\n def getStats(self) -> RTCStatsReport: ...\n def getTransceivers(self) -> List[RTCRtpTransceiver]: ...\n def setLocalDescription(self, sessionDescription: RTCSessionDescription) -> None: ...\n def setRemoteDescription(self, sessionDescription: RTCSessionDescription) -> None: ...\n def __connect(self) -> None: ...\n def __gather(self) -> None: ...\n def __assertNotClosed(self) -> None: ...\n def __assertTrackHasNoSender(self, track: MediaStreamTrack) -> None: ...\n def __createDtlsTransport(self) -> RTCDtlsTransport: ...\n def __createSctpTransport(self) -> None: ...\n def __createTransceiver(self, direction: str, kind: str, sender_track=None) -> RTCRtpTransceiver: ...\n def __getTransceiverByMid(self, mid: str) -> Optional[RTCRtpTransceiver]: ...\n def __getTransceiverByMLineIndex(self, index: int) -> Optional[RTCRtpTransceiver]: ...\n def __localDescription(self) -> Optional[sdp.SessionDescription]: ...\n def __localRtp(self, transceiver: RTCRtpTransceiver) -> RTCRtpSendParameters: ...\n def __remoteDescription(self) -> Optional[sdp.SessionDescription]: ...\n def __remoteRtp(self, transceiver: RTCRtpTransceiver) -> RTCRtpReceiveParameters: ...\n def __setSignalingState(self, state: str) -> None: ...\n def __updateIceConnectionState(self) -> None: ...\n def __updateIceGatheringState(self) -> None: ...\n def __validate_description(self, description: sdp.SessionDescription, is_local: bool) -> None: ...\n\n self.__certificates = [RTCCertificate.generateCertificate()]\n self.__cname = f'{uuid.uuid4()}'\n self.__configuration = configuration or RTCConfiguration()\n self._sctpLegacySdp = True\n self.__sctpRemoteCaps = None\n self.__stream_id = str(uuid.uuid4())\n self.__iceConnectionState = 'new'\n self.__iceGatheringState = 'new'\n self.__isClosed = False\n self.__signalingState = 'stable'\n", "repository": "0julio0/Icom_openpose", "test_name": "test_addTransceiver_audio_inactive", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000258.py"} {"focal_file": "aiortc-master/src/aiortc/rtcrtpsender.py", "focal_class": "RTCRtpSender", "focal_method": "_send_keyframe", "tests": "import unittest\n\nclass Test_RTCRtpSender_send_keyframe(unittest.TestCase):\n def test_send_keyframe(self):\n \"\"\"\n Ask for a keyframe.\n \"\"\"\n queue = asyncio.Queue()\n\n async def mock_send_rtp(data):\n if not is_rtcp(data):\n await queue.put(RtpPacket.parse(data))\n self.local_transport._send_rtp = mock_send_rtp\n sender = RTCRtpSender(VideoStreamTrack(), self.local_transport)\n self.assertEqual(sender.kind, 'video')\n run(sender.send(RTCRtpParameters(codecs=[VP8_CODEC])))\n run(queue.get())\n sender._send_keyframe()\n run(asyncio.sleep(0.1))\n run(sender.stop())\n", "method_code": " def _send_keyframe(self) -> None:\n \"\"\"\n Request the next frame to be a keyframe.\n \"\"\"\n self.__force_keyframe = True\n ", "context": "class RTCRtpSender():\n def _send_keyframe(self) -> None: ...\n def __init__(self, trackOrKind: Union[MediaStreamTrack, str], transport) -> None: ...\n def kind(self): ...\n def track(self) -> MediaStreamTrack: ...\n def transport(self): ...\n def getCapabilities(self, kind): ...\n def getStats(self) -> RTCStatsReport: ...\n def replaceTrack(self, track: Optional[MediaStreamTrack]) -> None: ...\n def setTransport(self, transport) -> None: ...\n def send(self, parameters: RTCRtpSendParameters) -> None: ...\n def stop(self): ...\n def _handle_rtcp_packet(self, packet): ...\n def _next_encoded_frame(self, codec: RTCRtpCodecParameters): ...\n def _retransmit(self, sequence_number: int) -> None: ...\n def _run_rtp(self, codec: RTCRtpCodecParameters) -> None: ...\n def _run_rtcp(self) -> None: ...\n def _send_rtcp(self, packets: List[AnyRtcpPacket]) -> None: ...\n def __log_debug(self, msg: str, *args) -> None: ...\n def __log_warning(self, msg: str, *args) -> None: ...\n\n self._ssrc = random32()\n self._rtx_ssrc = random32()\n self._stream_id = str(uuid.uuid4())\n self.__force_keyframe = False\n self.__loop = asyncio.get_event_loop()\n self.__rtp_exited = asyncio.Event()\n self.__rtp_header_extensions_map = rtp.HeaderExtensionsMap()\n self.__rtcp_exited = asyncio.Event()\n self.__rtx_sequence_number = random16()\n self.__started = False\n self.__stats = RTCStatsReport()\n self.__transport = transport\n self.__ntp_timestamp = 0\n self.__rtp_timestamp = 0\n self.__octet_count = 0\n self.__packet_count = 0\n self.__rtt = None\n", "repository": "0julio0/Icom_openpose", "test_name": "test_send_keyframe", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000259.py"} {"focal_file": "aiortc-master/src/aiortc/rtcrtptransceiver.py", "focal_class": "RTCRtpTransceiver", "focal_method": "setCodecPreferences", "tests": "import unittest\n\nclass Test_RTCRtpTransceiver_setCodecPreferences(unittest.TestCase):\n def test_codec_preferences(self):\n transceiver = RTCRtpTransceiver('audio', None, None)\n self.assertEqual(transceiver._preferred_codecs, [])\n transceiver.setCodecPreferences([])\n self.assertEqual(transceiver._preferred_codecs, [])\n transceiver.setCodecPreferences([RTCRtpCodecCapability(mimeType='audio/PCMU', clockRate=8000, channels=1)])\n self.assertEqual(transceiver._preferred_codecs, [RTCRtpCodecCapability(mimeType='audio/PCMU', clockRate=8000, channels=1)])\n transceiver.setCodecPreferences([RTCRtpCodecCapability(mimeType='audio/PCMU', clockRate=8000, channels=1), RTCRtpCodecCapability(mimeType='audio/PCMU', clockRate=8000, channels=1)])\n self.assertEqual(transceiver._preferred_codecs, [RTCRtpCodecCapability(mimeType='audio/PCMU', clockRate=8000, channels=1)])\n with self.assertRaises(ValueError) as cm:\n transceiver.setCodecPreferences([RTCRtpCodecCapability(mimeType='audio/bogus', clockRate=8000, channels=1)])\n self.assertEqual(str(cm.exception), 'Codec is not in capabilities')\n", "method_code": " def setCodecPreferences(self, codecs: List[RTCRtpCodecCapability]) -> None:\n \"\"\"\n Override the default codec preferences.\n \n See :meth:`RTCRtpSender.getCapabilities` and :meth:`RTCRtpReceiver.getCapabilities`\n for the supported codecs.\n \n :param codecs: A list of :class:`RTCRtpCodecCapability`, in decreasing order\n of preference. If empty, restores the default preferences.\n \"\"\"\n if not codecs:\n self._preferred_codecs = []\n capabilities = get_capabilities(self.kind).codecs\n unique: List[RTCRtpCodecCapability] = []\n for codec in reversed(codecs):\n if codec not in capabilities:\n raise ValueError('Codec is not in capabilities')\n if codec not in unique:\n unique.insert(0, codec)\n self._preferred_codecs = unique\n ", "context": "class RTCRtpTransceiver():\n def setCodecPreferences(self, codecs: List[RTCRtpCodecCapability]) -> None: ...\n def __init__(self, kind: str, receiver: RTCRtpReceiver, sender: RTCRtpSender, direction: str='sendrecv'): ...\n def currentDirection(self) -> Optional[str]: ...\n def direction(self) -> str: ...\n def direction(self, direction: str) -> None: ...\n def kind(self) -> str: ...\n def mid(self) -> Optional[str]: ...\n def receiver(self) -> RTCRtpReceiver: ...\n def sender(self) -> RTCRtpSender: ...\n def stopped(self) -> bool: ...\n def stop(self): ...\n def _set_mid(self, mid: str) -> None: ...\n def _get_mline_index(self) -> Optional[int]: ...\n def _set_mline_index(self, idx: int) -> None: ...\n\n self.__direction = direction\n self.__kind = kind\n self.__receiver = receiver\n self.__sender = sender\n self.__stopped = False\n self._bundled = False\n", "repository": "0julio0/Icom_openpose", "test_name": "test_codec_preferences", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000260.py"} {"focal_file": "aiortc-master/src/aiortc/rtcsctptransport.py", "focal_class": "InboundStream", "focal_method": "prune_chunks", "tests": "import unittest\n\nclass Test_InboundStream_prune_chunks(unittest.TestCase):\n def test_prune_chunks(self):\n stream = InboundStream()\n factory = ChunkFactory(tsn=100)\n chunks = factory.create([b'foo', b'bar']) + factory.create([b'baz', b'qux'])\n for i in [1, 2]:\n stream.add_chunk(chunks[i])\n self.assertEqual(list(stream.pop_messages()), [])\n self.assertEqual(stream.reassembly, [chunks[1], chunks[2]])\n self.assertEqual(stream.sequence_number, 0)\n stream.sequence_number = 2\n self.assertEqual(list(stream.pop_messages()), [])\n self.assertEqual(stream.reassembly, [chunks[1], chunks[2]])\n self.assertEqual(stream.sequence_number, 2)\n self.assertEqual(stream.prune_chunks(101), 3)\n self.assertEqual(stream.reassembly, [chunks[2]])\n self.assertEqual(stream.sequence_number, 2)\n", "method_code": " def prune_chunks(self, tsn: int) -> int:\n \"\"\"\n Prune chunks up to the given TSN.\n \"\"\"\n pos = -1\n size = 0\n for i, chunk in enumerate(self.reassembly):\n if uint32_gte(tsn, chunk.tsn):\n pos = i\n size += len(chunk.user_data)\n else:\n break\n self.reassembly = self.reassembly[pos + 1:]\n return size\n ", "context": "class InboundStream():\n def prune_chunks(self, tsn: int) -> int: ...\n def __init__(self) -> None: ...\n def add_chunk(self, chunk: DataChunk) -> None: ...\n def pop_messages(self) -> Iterator[Tuple[int, int, bytes]]: ...\n\n self.sequence_number = 0\n", "repository": "0julio0/Icom_openpose", "test_name": "test_prune_chunks", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000261.py"} {"focal_file": "aiortc-master/src/aiortc/rtcsctptransport.py", "focal_class": null, "focal_method": "tsn_minus_one", "tests": "import unittest\n\nclass Test_tsn_minus_one(unittest.TestCase):\n def test_tsn_minus_one(self):\n self.assertEqual(tsn_minus_one(0), 4294967295)\n self.assertEqual(tsn_minus_one(1), 0)\n self.assertEqual(tsn_minus_one(4294967294), 4294967293)\n self.assertEqual(tsn_minus_one(4294967295), 4294967294)\n", "method_code": "def tsn_minus_one(a: int) -> int:\n return (a - 1) % SCTP_TSN_MODULO", "context": "def tsn_minus_one(a: int) -> int: ...\ndef chunk_type(chunk) -> str: ...\ndef decode_params(body: bytes) -> List[Tuple[int, bytes]]: ...\ndef encode_params(params: List[Tuple[int, bytes]]) -> bytes: ...\ndef padl(l: int) -> int: ...\ndef tsn_minus_one(a: int) -> int: ...\ndef tsn_plus_one(a: int) -> int: ...\ndef parse_packet(data: bytes) -> Tuple[int, int, int, List[Any]]: ...\ndef serialize_packet(source_port: int, destination_port: int, verification_tag: int, chunk: Chunk) -> bytes: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_tsn_minus_one", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000262.py"} {"focal_file": "aiortc-master/src/aiortc/rtcsctptransport.py", "focal_class": null, "focal_method": "tsn_plus_one", "tests": "import unittest\n\nclass Test_tsn_plus_one(unittest.TestCase):\n def test_tsn_plus_one(self):\n self.assertEqual(tsn_plus_one(0), 1)\n self.assertEqual(tsn_plus_one(1), 2)\n self.assertEqual(tsn_plus_one(4294967294), 4294967295)\n self.assertEqual(tsn_plus_one(4294967295), 0)\n", "method_code": "def tsn_plus_one(a: int) -> int:\n return (a + 1) % SCTP_TSN_MODULO", "context": "def tsn_plus_one(a: int) -> int: ...\ndef chunk_type(chunk) -> str: ...\ndef decode_params(body: bytes) -> List[Tuple[int, bytes]]: ...\ndef encode_params(params: List[Tuple[int, bytes]]) -> bytes: ...\ndef padl(l: int) -> int: ...\ndef tsn_minus_one(a: int) -> int: ...\ndef tsn_plus_one(a: int) -> int: ...\ndef parse_packet(data: bytes) -> Tuple[int, int, int, List[Any]]: ...\ndef serialize_packet(source_port: int, destination_port: int, verification_tag: int, chunk: Chunk) -> bytes: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_tsn_plus_one", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000263.py"} {"focal_file": "aiortc-master/src/aiortc/rtcsctptransport.py", "focal_class": "RTCSctpTransport", "focal_method": "_maybe_abandon", "tests": "import unittest\n\nclass Test_RTCSctpTransport_maybe_abandon(unittest.TestCase):\n def test_maybe_abandon(self):\n\n async def mock_send_chunk(chunk):\n pass\n client = RTCSctpTransport(self.client_transport)\n client._local_tsn = 0\n client._send_chunk = mock_send_chunk\n run(client._send(123, 456, b'M' * USERDATA_MAX_LENGTH * 3))\n self.assertEqual(outstanding_tsns(client), [0, 1, 2])\n self.assertEqual(queued_tsns(client), [])\n for chunk in client._outbound_queue:\n self.assertEqual(chunk._abandoned, False)\n client._maybe_abandon(client._sent_queue[1])\n for chunk in client._outbound_queue:\n self.assertEqual(chunk._abandoned, False)\n\n def test_maybe_abandon_max_retransmits(self):\n\n async def mock_send_chunk(chunk):\n pass\n client = RTCSctpTransport(self.client_transport)\n client._local_tsn = 1\n client._last_sacked_tsn = 0\n client._advanced_peer_ack_tsn = 0\n client._send_chunk = mock_send_chunk\n run(client._send(123, 456, b'M' * USERDATA_MAX_LENGTH * 3, max_retransmits=0))\n self.assertEqual(outstanding_tsns(client), [1, 2, 3])\n self.assertEqual(queued_tsns(client), [])\n self.assertEqual(client._local_tsn, 4)\n self.assertEqual(client._advanced_peer_ack_tsn, 0)\n for chunk in client._outbound_queue:\n self.assertEqual(chunk._abandoned, False)\n client._maybe_abandon(client._sent_queue[1])\n for chunk in client._outbound_queue:\n self.assertEqual(chunk._abandoned, True)\n client._maybe_abandon(client._sent_queue[1])\n for chunk in client._outbound_queue:\n self.assertEqual(chunk._abandoned, True)\n client._update_advanced_peer_ack_point()\n self.assertEqual(outstanding_tsns(client), [])\n self.assertEqual(queued_tsns(client), [])\n self.assertEqual(client._advanced_peer_ack_tsn, 3)\n self.assertIsNotNone(client._forward_tsn_chunk)\n self.assertEqual(client._forward_tsn_chunk.cumulative_tsn, 3)\n self.assertEqual(client._forward_tsn_chunk.streams, [(123, 0)])\n client._t3_cancel()\n run(client._transmit())\n self.assertIsNone(client._forward_tsn_chunk)\n self.assertIsNotNone(client._t3_handle)\n", "method_code": " def _maybe_abandon(self, chunk: DataChunk) -> bool:\n \"\"\"\n Determine if a chunk needs to be marked as abandoned.\n \n If it does, it marks the chunk and any other chunk belong to the same\n message as abandoned.\n \"\"\"\n if chunk._abandoned:\n return True\n abandon = chunk._max_retransmits is not None and chunk._sent_count > chunk._max_retransmits or (chunk._expiry is not None and chunk._expiry < time.time())\n if not abandon:\n return False\n chunk_pos = self._sent_queue.index(chunk)\n for pos in range(chunk_pos, -1, -1):\n ochunk = self._sent_queue[pos]\n ochunk._abandoned = True\n ochunk._retransmit = False\n if ochunk.flags & SCTP_DATA_FIRST_FRAG:\n break\n for pos in range(chunk_pos, len(self._sent_queue)):\n ochunk = self._sent_queue[pos]\n ochunk._abandoned = True\n ochunk._retransmit = False\n if ochunk.flags & SCTP_DATA_LAST_FRAG:\n break\n return True\n ", "context": "class RTCSctpTransport(AsyncIOEventEmitter):\n @no_type_check\n def _maybe_abandon(self, chunk: DataChunk) -> bool: ...\n def __init__(self, transport: RTCDtlsTransport, port: int=5000) -> None: ...\n def is_server(self) -> bool: ...\n def port(self) -> int: ...\n def state(self) -> str: ...\n def transport(self): ...\n def getCapabilities(cls) -> RTCSctpCapabilities: ...\n def setTransport(self, transport) -> None: ...\n def start(self, remoteCaps: RTCSctpCapabilities, remotePort: int) -> None: ...\n def stop(self) -> None: ...\n def _abort(self) -> None: ...\n def _init(self) -> None: ...\n def _flight_size_decrease(self, chunk: DataChunk) -> None: ...\n def _flight_size_increase(self, chunk: DataChunk) -> None: ...\n def _get_extensions(self, params: List[Tuple[int, bytes]]) -> None: ...\n def _set_extensions(self, params: List[Tuple[int, bytes]]) -> None: ...\n def _get_inbound_stream(self, stream_id: int) -> InboundStream: ...\n def _get_timestamp(self) -> int: ...\n def _handle_data(self, data): ...\n def _mark_received(self, tsn: int) -> bool: ...\n def _receive(self, stream_id: int, pp_id: int, data: bytes) -> None: ...\n def _receive_chunk(self, chunk): ...\n def _receive_data_chunk(self, chunk: DataChunk) -> None: ...\n def _receive_forward_tsn_chunk(self, chunk: ForwardTsnChunk) -> None: ...\n def _receive_sack_chunk(self, chunk: SackChunk) -> None: ...\n def _receive_reconfig_param(self, param): ...\n def _send(self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float]=None, max_retransmits: Optional[int]=None, ordered: bool=True) -> None: ...\n def _send_chunk(self, chunk: Chunk) -> None: ...\n def _send_reconfig_param(self, param): ...\n def _send_sack(self): ...\n def _set_state(self, state) -> None: ...\n def _t1_cancel(self) -> None: ...\n def _t1_expired(self) -> None: ...\n def _t1_start(self, chunk: Chunk) -> None: ...\n def _t2_cancel(self) -> None: ...\n def _t2_expired(self) -> None: ...\n def _t2_start(self, chunk) -> None: ...\n def _t3_expired(self) -> None: ...\n def _t3_restart(self) -> None: ...\n def _t3_start(self) -> None: ...\n def _t3_cancel(self) -> None: ...\n def _transmit(self) -> None: ...\n def _transmit_reconfig(self): ...\n def _update_advanced_peer_ack_point(self) -> None: ...\n def _update_rto(self, R: float) -> None: ...\n def _data_channel_close(self, channel, transmit=True): ...\n def _data_channel_closed(self, stream_id: int) -> None: ...\n def _data_channel_flush(self) -> None: ...\n def _data_channel_add_negotiated(self, channel: RTCDataChannel) -> None: ...\n def _data_channel_open(self, channel: RTCDataChannel) -> None: ...\n def _data_channel_receive(self, stream_id: int, pp_id: int, data: bytes) -> None: ...\n def _data_channel_send(self, channel: RTCDataChannel, data: bytes) -> None: ...\n\n self._association_state = self.State.CLOSED\n self.__started = False\n self.__state = 'new'\n self.__transport = transport\n self._loop = asyncio.get_event_loop()\n self._hmac_key = os.urandom(16)\n self._local_partial_reliability = True\n self._local_port = port\n self._local_verification_tag = random32()\n self._remote_partial_reliability = False\n self._remote_verification_tag = 0\n self._advertised_rwnd = 1024 * 1024\n self._inbound_streams_count = 0\n self._inbound_streams_max = MAX_STREAMS\n self._sack_needed = False\n self._cwnd = 3 * USERDATA_MAX_LENGTH\n self._fast_recovery_exit = None\n self._fast_recovery_transmit = False\n self._flight_size = 0\n self._local_tsn = random32()\n self._last_sacked_tsn = tsn_minus_one(self._local_tsn)\n self._advanced_peer_ack_tsn = tsn_minus_one(self._local_tsn)\n self._outbound_streams_count = MAX_STREAMS\n self._partial_bytes_acked = 0\n self._reconfig_request = None\n self._reconfig_request_seq = self._local_tsn\n self._reconfig_response_seq = 0\n self._rto = SCTP_RTO_INITIAL\n self._t1_failures = 0\n self._t2_failures = 0\n self._bundled = False\n", "repository": "0julio0/Icom_openpose", "test_name": "test_maybe_abandon", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000264.py"} {"focal_file": "aiortc-master/src/aiortc/rtcsctptransport.py", "focal_class": "RTCSctpTransport", "focal_method": "_mark_received", "tests": "import unittest\n\nclass Test_RTCSctpTransport_mark_received(unittest.TestCase):\n def test_mark_received(self):\n client = RTCSctpTransport(self.client_transport)\n client._last_received_tsn = 0\n self.assertFalse(client._mark_received(1))\n self.assertEqual(client._last_received_tsn, 1)\n self.assertEqual(client._sack_misordered, set())\n self.assertFalse(client._mark_received(3))\n self.assertEqual(client._last_received_tsn, 1)\n self.assertEqual(client._sack_misordered, set([3]))\n self.assertFalse(client._mark_received(4))\n self.assertEqual(client._last_received_tsn, 1)\n self.assertEqual(client._sack_misordered, set([3, 4]))\n self.assertFalse(client._mark_received(6))\n self.assertEqual(client._last_received_tsn, 1)\n self.assertEqual(client._sack_misordered, set([3, 4, 6]))\n self.assertFalse(client._mark_received(2))\n self.assertEqual(client._last_received_tsn, 4)\n self.assertEqual(client._sack_misordered, set([6]))\n", "method_code": " def _mark_received(self, tsn: int) -> bool:\n \"\"\"\n Mark an incoming data TSN as received.\n \"\"\"\n if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered:\n self._sack_duplicates.append(tsn)\n return True\n self._sack_misordered.add(tsn)\n for tsn in sorted(self._sack_misordered):\n if tsn == tsn_plus_one(self._last_received_tsn):\n self._last_received_tsn = tsn\n else:\n break\n \n def is_obsolete(x):\n return uint32_gt(x, self._last_received_tsn)\n self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates))\n self._sack_misordered = set(filter(is_obsolete, self._sack_misordered))\n return False\n ", "context": "class RTCSctpTransport(AsyncIOEventEmitter):\n def _mark_received(self, tsn: int) -> bool: ...\n def __init__(self, transport: RTCDtlsTransport, port: int=5000) -> None: ...\n def is_server(self) -> bool: ...\n def port(self) -> int: ...\n def state(self) -> str: ...\n def transport(self): ...\n def getCapabilities(cls) -> RTCSctpCapabilities: ...\n def setTransport(self, transport) -> None: ...\n def start(self, remoteCaps: RTCSctpCapabilities, remotePort: int) -> None: ...\n def stop(self) -> None: ...\n def _abort(self) -> None: ...\n def _init(self) -> None: ...\n def _flight_size_decrease(self, chunk: DataChunk) -> None: ...\n def _flight_size_increase(self, chunk: DataChunk) -> None: ...\n def _get_extensions(self, params: List[Tuple[int, bytes]]) -> None: ...\n def _set_extensions(self, params: List[Tuple[int, bytes]]) -> None: ...\n def _get_inbound_stream(self, stream_id: int) -> InboundStream: ...\n def _get_timestamp(self) -> int: ...\n def _handle_data(self, data): ...\n def _maybe_abandon(self, chunk: DataChunk) -> bool: ...\n def _receive(self, stream_id: int, pp_id: int, data: bytes) -> None: ...\n def _receive_chunk(self, chunk): ...\n def _receive_data_chunk(self, chunk: DataChunk) -> None: ...\n def _receive_forward_tsn_chunk(self, chunk: ForwardTsnChunk) -> None: ...\n def _receive_sack_chunk(self, chunk: SackChunk) -> None: ...\n def _receive_reconfig_param(self, param): ...\n def _send(self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float]=None, max_retransmits: Optional[int]=None, ordered: bool=True) -> None: ...\n def _send_chunk(self, chunk: Chunk) -> None: ...\n def _send_reconfig_param(self, param): ...\n def _send_sack(self): ...\n def _set_state(self, state) -> None: ...\n def _t1_cancel(self) -> None: ...\n def _t1_expired(self) -> None: ...\n def _t1_start(self, chunk: Chunk) -> None: ...\n def _t2_cancel(self) -> None: ...\n def _t2_expired(self) -> None: ...\n def _t2_start(self, chunk) -> None: ...\n def _t3_expired(self) -> None: ...\n def _t3_restart(self) -> None: ...\n def _t3_start(self) -> None: ...\n def _t3_cancel(self) -> None: ...\n def _transmit(self) -> None: ...\n def _transmit_reconfig(self): ...\n def _update_advanced_peer_ack_point(self) -> None: ...\n def _update_rto(self, R: float) -> None: ...\n def _data_channel_close(self, channel, transmit=True): ...\n def _data_channel_closed(self, stream_id: int) -> None: ...\n def _data_channel_flush(self) -> None: ...\n def _data_channel_add_negotiated(self, channel: RTCDataChannel) -> None: ...\n def _data_channel_open(self, channel: RTCDataChannel) -> None: ...\n def _data_channel_receive(self, stream_id: int, pp_id: int, data: bytes) -> None: ...\n def _data_channel_send(self, channel: RTCDataChannel, data: bytes) -> None: ...\n\n self._association_state = self.State.CLOSED\n self.__started = False\n self.__state = 'new'\n self.__transport = transport\n self._loop = asyncio.get_event_loop()\n self._hmac_key = os.urandom(16)\n self._local_partial_reliability = True\n self._local_port = port\n self._local_verification_tag = random32()\n self._remote_partial_reliability = False\n self._remote_verification_tag = 0\n self._advertised_rwnd = 1024 * 1024\n self._inbound_streams_count = 0\n self._inbound_streams_max = MAX_STREAMS\n self._sack_needed = False\n self._cwnd = 3 * USERDATA_MAX_LENGTH\n self._fast_recovery_exit = None\n self._fast_recovery_transmit = False\n self._flight_size = 0\n self._local_tsn = random32()\n self._last_sacked_tsn = tsn_minus_one(self._local_tsn)\n self._advanced_peer_ack_tsn = tsn_minus_one(self._local_tsn)\n self._outbound_streams_count = MAX_STREAMS\n self._partial_bytes_acked = 0\n self._reconfig_request = None\n self._reconfig_request_seq = self._local_tsn\n self._reconfig_response_seq = 0\n self._rto = SCTP_RTO_INITIAL\n self._t1_failures = 0\n self._t2_failures = 0\n self._bundled = False\n", "repository": "0julio0/Icom_openpose", "test_name": "test_mark_received", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000265.py"} {"focal_file": "aiortc-master/src/aiortc/rtcsctptransport.py", "focal_class": "RTCSctpTransport", "focal_method": "_t3_expired", "tests": "import unittest\n\nclass Test_RTCSctpTransport_t3_expired(unittest.TestCase):\n def test_t3_expired(self):\n\n async def mock_send_chunk(chunk):\n pass\n\n async def mock_transmit():\n pass\n client = RTCSctpTransport(self.client_transport)\n client._local_tsn = 0\n client._send_chunk = mock_send_chunk\n run(client._send(123, 456, b'M' * USERDATA_MAX_LENGTH))\n self.assertIsNotNone(client._t3_handle)\n self.assertEqual(outstanding_tsns(client), [0])\n self.assertEqual(queued_tsns(client), [])\n client._transmit = mock_transmit\n client._t3_expired()\n self.assertIsNone(client._t3_handle)\n self.assertEqual(outstanding_tsns(client), [0])\n self.assertEqual(queued_tsns(client), [])\n for chunk in client._outbound_queue:\n self.assertEqual(chunk._retransmit, True)\n run(asyncio.sleep(0))\n", "method_code": " def _t3_expired(self) -> None:\n self._t3_handle = None\n self.__log_debug('x T3 expired')\n for chunk in self._sent_queue:\n if not self._maybe_abandon(chunk):\n chunk._retransmit = True\n self._update_advanced_peer_ack_point()\n self._fast_recovery_exit = None\n self._flight_size = 0\n self._partial_bytes_acked = 0\n self._ssthresh = max(self._cwnd // 2, 4 * USERDATA_MAX_LENGTH)\n self._cwnd = USERDATA_MAX_LENGTH\n asyncio.ensure_future(self._transmit())\n ", "context": "class RTCSctpTransport(AsyncIOEventEmitter):\n @no_type_check\n def _t3_expired(self) -> None: ...\n def __init__(self, transport: RTCDtlsTransport, port: int=5000) -> None: ...\n def is_server(self) -> bool: ...\n def port(self) -> int: ...\n def state(self) -> str: ...\n def transport(self): ...\n def getCapabilities(cls) -> RTCSctpCapabilities: ...\n def setTransport(self, transport) -> None: ...\n def start(self, remoteCaps: RTCSctpCapabilities, remotePort: int) -> None: ...\n def stop(self) -> None: ...\n def _abort(self) -> None: ...\n def _init(self) -> None: ...\n def _flight_size_decrease(self, chunk: DataChunk) -> None: ...\n def _flight_size_increase(self, chunk: DataChunk) -> None: ...\n def _get_extensions(self, params: List[Tuple[int, bytes]]) -> None: ...\n def _set_extensions(self, params: List[Tuple[int, bytes]]) -> None: ...\n def _get_inbound_stream(self, stream_id: int) -> InboundStream: ...\n def _get_timestamp(self) -> int: ...\n def _handle_data(self, data): ...\n def _maybe_abandon(self, chunk: DataChunk) -> bool: ...\n def _mark_received(self, tsn: int) -> bool: ...\n def _receive(self, stream_id: int, pp_id: int, data: bytes) -> None: ...\n def _receive_chunk(self, chunk): ...\n def _receive_data_chunk(self, chunk: DataChunk) -> None: ...\n def _receive_forward_tsn_chunk(self, chunk: ForwardTsnChunk) -> None: ...\n def _receive_sack_chunk(self, chunk: SackChunk) -> None: ...\n def _receive_reconfig_param(self, param): ...\n def _send(self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float]=None, max_retransmits: Optional[int]=None, ordered: bool=True) -> None: ...\n def _send_chunk(self, chunk: Chunk) -> None: ...\n def _send_reconfig_param(self, param): ...\n def _send_sack(self): ...\n def _set_state(self, state) -> None: ...\n def _t1_cancel(self) -> None: ...\n def _t1_expired(self) -> None: ...\n def _t1_start(self, chunk: Chunk) -> None: ...\n def _t2_cancel(self) -> None: ...\n def _t2_expired(self) -> None: ...\n def _t2_start(self, chunk) -> None: ...\n def _t3_restart(self) -> None: ...\n def _t3_start(self) -> None: ...\n def _t3_cancel(self) -> None: ...\n def _transmit(self) -> None: ...\n def _transmit_reconfig(self): ...\n def _update_advanced_peer_ack_point(self) -> None: ...\n def _update_rto(self, R: float) -> None: ...\n def _data_channel_close(self, channel, transmit=True): ...\n def _data_channel_closed(self, stream_id: int) -> None: ...\n def _data_channel_flush(self) -> None: ...\n def _data_channel_add_negotiated(self, channel: RTCDataChannel) -> None: ...\n def _data_channel_open(self, channel: RTCDataChannel) -> None: ...\n def _data_channel_receive(self, stream_id: int, pp_id: int, data: bytes) -> None: ...\n def _data_channel_send(self, channel: RTCDataChannel, data: bytes) -> None: ...\n\n self._association_state = self.State.CLOSED\n self.__started = False\n self.__state = 'new'\n self.__transport = transport\n self._loop = asyncio.get_event_loop()\n self._hmac_key = os.urandom(16)\n self._local_partial_reliability = True\n self._local_port = port\n self._local_verification_tag = random32()\n self._remote_partial_reliability = False\n self._remote_verification_tag = 0\n self._advertised_rwnd = 1024 * 1024\n self._inbound_streams_count = 0\n self._inbound_streams_max = MAX_STREAMS\n self._sack_needed = False\n self._cwnd = 3 * USERDATA_MAX_LENGTH\n self._fast_recovery_exit = None\n self._fast_recovery_transmit = False\n self._flight_size = 0\n self._local_tsn = random32()\n self._last_sacked_tsn = tsn_minus_one(self._local_tsn)\n self._advanced_peer_ack_tsn = tsn_minus_one(self._local_tsn)\n self._outbound_streams_count = MAX_STREAMS\n self._partial_bytes_acked = 0\n self._reconfig_request = None\n self._reconfig_request_seq = self._local_tsn\n self._reconfig_response_seq = 0\n self._rto = SCTP_RTO_INITIAL\n self._t1_failures = 0\n self._t2_failures = 0\n self._bundled = False\n", "repository": "0julio0/Icom_openpose", "test_name": "test_t3_expired", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000266.py"} {"focal_file": "aiortc-master/src/aiortc/rtp.py", "focal_class": null, "focal_method": "clamp_packets_lost", "tests": "import unittest\n\nclass Test_clamp_packets_lost(unittest.TestCase):\n def test_clamp_packets_lost(self):\n self.assertEqual(clamp_packets_lost(-8388609), -8388608)\n self.assertEqual(clamp_packets_lost(-8388608), -8388608)\n self.assertEqual(clamp_packets_lost(0), 0)\n self.assertEqual(clamp_packets_lost(8388607), 8388607)\n self.assertEqual(clamp_packets_lost(8388608), 8388607)\n", "method_code": "def clamp_packets_lost(count: int) -> int:\n return max(PACKETS_LOST_MIN, min(count, PACKETS_LOST_MAX))", "context": "def clamp_packets_lost(count: int) -> int: ...\ndef clamp_packets_lost(count: int) -> int: ...\ndef pack_packets_lost(count: int) -> bytes: ...\ndef unpack_packets_lost(d: bytes) -> int: ...\ndef pack_rtcp_packet(packet_type: int, count: int, payload: bytes) -> bytes: ...\ndef pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes: ...\ndef unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]: ...\ndef is_rtcp(msg: bytes) -> bool: ...\ndef padl(l: int) -> int: ...\ndef unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: ...\ndef pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]: ...\ndef unwrap_rtx(rtx: RtpPacket, payload_type: int, ssrc: int) -> RtpPacket: ...\ndef wrap_rtx(packet: RtpPacket, payload_type: int, sequence_number: int, ssrc: int) -> RtpPacket: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_clamp_packets_lost", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000267.py"} {"focal_file": "aiortc-master/src/aiortc/rtp.py", "focal_class": null, "focal_method": "pack_packets_lost", "tests": "import unittest\n\nclass Test_pack_packets_lost(unittest.TestCase):\n def test_pack_packets_lost(self):\n self.assertEqual(pack_packets_lost(-8388608), b'\\x80\\x00\\x00')\n self.assertEqual(pack_packets_lost(-1), b'\\xff\\xff\\xff')\n self.assertEqual(pack_packets_lost(0), b'\\x00\\x00\\x00')\n self.assertEqual(pack_packets_lost(1), b'\\x00\\x00\\x01')\n self.assertEqual(pack_packets_lost(8388607), b'\\x7f\\xff\\xff')\n", "method_code": "def pack_packets_lost(count: int) -> bytes:\n return pack('!l', count)[1:]", "context": "def pack_packets_lost(count: int) -> bytes: ...\ndef clamp_packets_lost(count: int) -> int: ...\ndef pack_packets_lost(count: int) -> bytes: ...\ndef unpack_packets_lost(d: bytes) -> int: ...\ndef pack_rtcp_packet(packet_type: int, count: int, payload: bytes) -> bytes: ...\ndef pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes: ...\ndef unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]: ...\ndef is_rtcp(msg: bytes) -> bool: ...\ndef padl(l: int) -> int: ...\ndef unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: ...\ndef pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]: ...\ndef unwrap_rtx(rtx: RtpPacket, payload_type: int, ssrc: int) -> RtpPacket: ...\ndef wrap_rtx(packet: RtpPacket, payload_type: int, sequence_number: int, ssrc: int) -> RtpPacket: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_pack_packets_lost", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000268.py"} {"focal_file": "aiortc-master/src/aiortc/rtp.py", "focal_class": null, "focal_method": "pack_remb_fci", "tests": "import unittest\n\nclass Test_pack_remb_fci(unittest.TestCase):\n def test_pack_remb_fci(self):\n data = pack_remb_fci(0, [2529072847])\n self.assertEqual(data, b'REMB\\x01\\x00\\x00\\x00\\x96\\xbe\\x96\\xcf')\n data = pack_remb_fci(262143, [2529072847])\n self.assertEqual(data, b'REMB\\x01\\x03\\xff\\xff\\x96\\xbe\\x96\\xcf')\n data = pack_remb_fci(262144, [2529072847])\n self.assertEqual(data, b'REMB\\x01\\x06\\x00\\x00\\x96\\xbe\\x96\\xcf')\n data = pack_remb_fci(4160000, [2529072847])\n self.assertEqual(data, b'REMB\\x01\\x13\\xf7\\xa0\\x96\\xbe\\x96\\xcf')\n data = pack_remb_fci(262143 << 63, [2529072847])\n self.assertEqual(data, b'REMB\\x01\\xff\\xff\\xff\\x96\\xbe\\x96\\xcf')\n", "method_code": "def pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes:\n \"\"\"\n Pack the FCI for a Receiver Estimated Maximum Bitrate report.\n\n https://tools.ietf.org/html/draft-alvestrand-rmcat-remb-03\n \"\"\"\n data = b'REMB'\n exponent = 0\n mantissa = bitrate\n while mantissa > 262143:\n mantissa >>= 1\n exponent += 1\n data += pack('!BBH', len(ssrcs), exponent << 2 | mantissa >> 16, mantissa & 65535)\n for ssrc in ssrcs:\n data += pack('!L', ssrc)\n return data", "context": "def pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes: ...\ndef clamp_packets_lost(count: int) -> int: ...\ndef pack_packets_lost(count: int) -> bytes: ...\ndef unpack_packets_lost(d: bytes) -> int: ...\ndef pack_rtcp_packet(packet_type: int, count: int, payload: bytes) -> bytes: ...\ndef pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes: ...\ndef unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]: ...\ndef is_rtcp(msg: bytes) -> bool: ...\ndef padl(l: int) -> int: ...\ndef unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: ...\ndef pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]: ...\ndef unwrap_rtx(rtx: RtpPacket, payload_type: int, ssrc: int) -> RtpPacket: ...\ndef wrap_rtx(packet: RtpPacket, payload_type: int, sequence_number: int, ssrc: int) -> RtpPacket: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_pack_remb_fci", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000269.py"} {"focal_file": "aiortc-master/src/aiortc/rtp.py", "focal_class": null, "focal_method": "unpack_packets_lost", "tests": "import unittest\n\nclass Test_unpack_packets_lost(unittest.TestCase):\n def test_unpack_packets_lost(self):\n self.assertEqual(unpack_packets_lost(b'\\x80\\x00\\x00'), -8388608)\n self.assertEqual(unpack_packets_lost(b'\\xff\\xff\\xff'), -1)\n self.assertEqual(unpack_packets_lost(b'\\x00\\x00\\x00'), 0)\n self.assertEqual(unpack_packets_lost(b'\\x00\\x00\\x01'), 1)\n self.assertEqual(unpack_packets_lost(b'\\x7f\\xff\\xff'), 8388607)\n", "method_code": "def unpack_packets_lost(d: bytes) -> int:\n if d[0] & 128:\n d = b'\\xff' + d\n else:\n d = b'\\x00' + d\n return unpack('!l', d)[0]", "context": "def unpack_packets_lost(d: bytes) -> int: ...\ndef clamp_packets_lost(count: int) -> int: ...\ndef pack_packets_lost(count: int) -> bytes: ...\ndef unpack_packets_lost(d: bytes) -> int: ...\ndef pack_rtcp_packet(packet_type: int, count: int, payload: bytes) -> bytes: ...\ndef pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes: ...\ndef unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]: ...\ndef is_rtcp(msg: bytes) -> bool: ...\ndef padl(l: int) -> int: ...\ndef unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: ...\ndef pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]: ...\ndef unwrap_rtx(rtx: RtpPacket, payload_type: int, ssrc: int) -> RtpPacket: ...\ndef wrap_rtx(packet: RtpPacket, payload_type: int, sequence_number: int, ssrc: int) -> RtpPacket: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_unpack_packets_lost", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000270.py"} {"focal_file": "aiortc-master/src/aiortc/rtp.py", "focal_class": null, "focal_method": "unpack_remb_fci", "tests": "import unittest\n\nclass Test_unpack_remb_fci(unittest.TestCase):\n def test_unpack_remb_fci(self):\n with self.assertRaises(ValueError):\n unpack_remb_fci(b'JUNK')\n bitrate, ssrcs = unpack_remb_fci(b'REMB\\x01\\x00\\x00\\x00\\x96\\xbe\\x96\\xcf')\n self.assertEqual(bitrate, 0)\n self.assertEqual(ssrcs, [2529072847])\n bitrate, ssrcs = unpack_remb_fci(b'REMB\\x01\\x03\\xff\\xff\\x96\\xbe\\x96\\xcf')\n self.assertEqual(bitrate, 262143)\n self.assertEqual(ssrcs, [2529072847])\n bitrate, ssrcs = unpack_remb_fci(b'REMB\\x01\\x06\\x00\\x00\\x96\\xbe\\x96\\xcf')\n self.assertEqual(bitrate, 262144)\n self.assertEqual(ssrcs, [2529072847])\n bitrate, ssrcs = unpack_remb_fci(b'REMB\\x01\\x13\\xf7\\xa0\\x96\\xbe\\x96\\xcf')\n self.assertEqual(bitrate, 4160000)\n self.assertEqual(ssrcs, [2529072847])\n bitrate, ssrcs = unpack_remb_fci(b'REMB\\x01\\xff\\xff\\xff\\x96\\xbe\\x96\\xcf')\n self.assertEqual(bitrate, 262143 << 63)\n self.assertEqual(ssrcs, [2529072847])\n", "method_code": "def unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]:\n \"\"\"\n Unpack the FCI for a Receiver Estimated Maximum Bitrate report.\n\n https://tools.ietf.org/html/draft-alvestrand-rmcat-remb-03\n \"\"\"\n if len(data) < 8 or data[0:4] != b'REMB':\n raise ValueError('Invalid REMB prefix')\n exponent = (data[5] & 252) >> 2\n mantissa = (data[5] & 3) << 16 | data[6] << 8 | data[7]\n bitrate = mantissa << exponent\n pos = 8\n ssrcs = []\n for r in range(data[4]):\n ssrcs.append(unpack_from('!L', data, pos)[0])\n pos += 4\n return (bitrate, ssrcs)", "context": "def unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]: ...\ndef clamp_packets_lost(count: int) -> int: ...\ndef pack_packets_lost(count: int) -> bytes: ...\ndef unpack_packets_lost(d: bytes) -> int: ...\ndef pack_rtcp_packet(packet_type: int, count: int, payload: bytes) -> bytes: ...\ndef pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes: ...\ndef unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]: ...\ndef is_rtcp(msg: bytes) -> bool: ...\ndef padl(l: int) -> int: ...\ndef unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: ...\ndef pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]: ...\ndef unwrap_rtx(rtx: RtpPacket, payload_type: int, ssrc: int) -> RtpPacket: ...\ndef wrap_rtx(packet: RtpPacket, payload_type: int, sequence_number: int, ssrc: int) -> RtpPacket: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_unpack_remb_fci", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000271.py"} {"focal_file": "aiortc-master/src/aiortc/rtp.py", "focal_class": null, "focal_method": "unpack_header_extensions", "tests": "import unittest\n\nclass Test_unpack_header_extensions(unittest.TestCase):\n def test_unpack_header_extensions(self):\n self.assertEqual(unpack_header_extensions(0, None), [])\n self.assertEqual(unpack_header_extensions(48862, b'\\x900'), [(9, b'0')])\n self.assertEqual(unpack_header_extensions(48862, b'\\x900\\x00\\x0001'), [(9, b'0'), (3, b'1')])\n self.assertEqual(unpack_header_extensions(48862, b'\\x10\\xc18sdparta_0'), [(1, b'\\xc1'), (3, b'sdparta_0')])\n self.assertEqual(unpack_header_extensions(4096, b'\\xff\\x010'), [(255, b'0')])\n self.assertEqual(unpack_header_extensions(4096, b'\\xff\\x010\\x00\\xf0\\x0212'), [(255, b'0'), (240, b'12')])\n\n def test_unpack_header_extensions_bad(self):\n with self.assertRaises(ValueError) as cm:\n unpack_header_extensions(48862, b'\\x90')\n self.assertEqual(str(cm.exception), 'RTP one-byte header extension value is truncated')\n with self.assertRaises(ValueError) as cm:\n unpack_header_extensions(4096, b'\\xff')\n self.assertEqual(str(cm.exception), 'RTP two-byte header extension is truncated')\n with self.assertRaises(ValueError) as cm:\n unpack_header_extensions(4096, b'\\xff\\x020')\n self.assertEqual(str(cm.exception), 'RTP two-byte header extension value is truncated')\n", "method_code": "def unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]:\n \"\"\"\n Parse header extensions according to RFC 5285.\n \"\"\"\n extensions = []\n pos = 0\n if extension_profile == 48862:\n while pos < len(extension_value):\n if extension_value[pos] == 0:\n pos += 1\n continue\n x_id = (extension_value[pos] & 240) >> 4\n x_length = (extension_value[pos] & 15) + 1\n pos += 1\n if len(extension_value) < pos + x_length:\n raise ValueError('RTP one-byte header extension value is truncated')\n x_value = extension_value[pos:pos + x_length]\n extensions.append((x_id, x_value))\n pos += x_length\n elif extension_profile == 4096:\n while pos < len(extension_value):\n if extension_value[pos] == 0:\n pos += 1\n continue\n if len(extension_value) < pos + 2:\n raise ValueError('RTP two-byte header extension is truncated')\n x_id, x_length = unpack_from('!BB', extension_value, pos)\n pos += 2\n if len(extension_value) < pos + x_length:\n raise ValueError('RTP two-byte header extension value is truncated')\n x_value = extension_value[pos:pos + x_length]\n extensions.append((x_id, x_value))\n pos += x_length\n return extensions", "context": "def unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: ...\ndef clamp_packets_lost(count: int) -> int: ...\ndef pack_packets_lost(count: int) -> bytes: ...\ndef unpack_packets_lost(d: bytes) -> int: ...\ndef pack_rtcp_packet(packet_type: int, count: int, payload: bytes) -> bytes: ...\ndef pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes: ...\ndef unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]: ...\ndef is_rtcp(msg: bytes) -> bool: ...\ndef padl(l: int) -> int: ...\ndef unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: ...\ndef pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]: ...\ndef unwrap_rtx(rtx: RtpPacket, payload_type: int, ssrc: int) -> RtpPacket: ...\ndef wrap_rtx(packet: RtpPacket, payload_type: int, sequence_number: int, ssrc: int) -> RtpPacket: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_unpack_header_extensions", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000272.py"} {"focal_file": "aiortc-master/src/aiortc/rtp.py", "focal_class": null, "focal_method": "pack_header_extensions", "tests": "import unittest\n\nclass Test_pack_header_extensions(unittest.TestCase):\n def test_pack_header_extensions(self):\n self.assertEqual(pack_header_extensions([]), (0, b''))\n self.assertEqual(pack_header_extensions([(9, b'0')]), (48862, b'\\x900\\x00\\x00'))\n self.assertEqual(pack_header_extensions([(1, b'\\xc1'), (3, b'sdparta_0')]), (48862, b'\\x10\\xc18sdparta_0'))\n self.assertEqual(pack_header_extensions([(255, b'0')]), (4096, b'\\xff\\x010\\x00'))\n", "method_code": "def pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]:\n \"\"\"\n Serialize header extensions according to RFC 5285.\n \"\"\"\n extension_profile = 0\n extension_value = b''\n if not extensions:\n return (extension_profile, extension_value)\n one_byte = True\n for x_id, x_value in extensions:\n x_length = len(x_value)\n assert x_id > 0 and x_id < 256\n assert x_length >= 0 and x_length < 256\n if x_id > 14 or x_length == 0 or x_length > 16:\n one_byte = False\n if one_byte:\n extension_profile = 48862\n extension_value = b''\n for x_id, x_value in extensions:\n x_length = len(x_value)\n extension_value += pack('!B', x_id << 4 | x_length - 1)\n extension_value += x_value\n else:\n extension_profile = 4096\n extension_value = b''\n for x_id, x_value in extensions:\n x_length = len(x_value)\n extension_value += pack('!BB', x_id, x_length)\n extension_value += x_value\n extension_value += b'\\x00' * padl(len(extension_value))\n return (extension_profile, extension_value)", "context": "def pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]: ...\ndef clamp_packets_lost(count: int) -> int: ...\ndef pack_packets_lost(count: int) -> bytes: ...\ndef unpack_packets_lost(d: bytes) -> int: ...\ndef pack_rtcp_packet(packet_type: int, count: int, payload: bytes) -> bytes: ...\ndef pack_remb_fci(bitrate: int, ssrcs: List[int]) -> bytes: ...\ndef unpack_remb_fci(data: bytes) -> Tuple[int, List[int]]: ...\ndef is_rtcp(msg: bytes) -> bool: ...\ndef padl(l: int) -> int: ...\ndef unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: ...\ndef pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]: ...\ndef unwrap_rtx(rtx: RtpPacket, payload_type: int, ssrc: int) -> RtpPacket: ...\ndef wrap_rtx(packet: RtpPacket, payload_type: int, sequence_number: int, ssrc: int) -> RtpPacket: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_pack_header_extensions", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000273.py"} {"focal_file": "aiortc-master/src/aiortc/utils.py", "focal_class": null, "focal_method": "uint16_add", "tests": "import unittest\n\nclass Test_uint16_add(unittest.TestCase):\n def test_uint16_add(self):\n self.assertEqual(uint16_add(0, 1), 1)\n self.assertEqual(uint16_add(1, 1), 2)\n self.assertEqual(uint16_add(1, 2), 3)\n self.assertEqual(uint16_add(65534, 1), 65535)\n self.assertEqual(uint16_add(65535, 1), 0)\n self.assertEqual(uint16_add(65535, 3), 2)\n", "method_code": "def uint16_add(a: int, b: int) -> int:\n \"\"\"\n Return a + b.\n \"\"\"\n return a + b & 65535", "context": "def uint16_add(a: int, b: int) -> int: ...\ndef random16() -> int: ...\ndef random32() -> int: ...\ndef uint16_add(a: int, b: int) -> int: ...\ndef uint16_gt(a: int, b: int) -> bool: ...\ndef uint16_gte(a: int, b: int) -> bool: ...\ndef uint32_add(a: int, b: int) -> int: ...\ndef uint32_gt(a: int, b: int) -> bool: ...\ndef uint32_gte(a: int, b: int) -> bool: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_uint16_add", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000274.py"} {"focal_file": "aiortc-master/src/aiortc/utils.py", "focal_class": null, "focal_method": "uint16_gt", "tests": "import unittest\n\nclass Test_uint16_gt(unittest.TestCase):\n def test_uint16_gt(self):\n self.assertFalse(uint16_gt(0, 1))\n self.assertFalse(uint16_gt(1, 1))\n self.assertTrue(uint16_gt(2, 1))\n self.assertTrue(uint16_gt(32768, 1))\n self.assertFalse(uint16_gt(32769, 1))\n self.assertFalse(uint16_gt(65535, 1))\n", "method_code": "def uint16_gt(a: int, b: int) -> bool:\n \"\"\"\n Return a > b.\n \"\"\"\n half_mod = 32768\n return a < b and b - a > half_mod or (a > b and a - b < half_mod)", "context": "def uint16_gt(a: int, b: int) -> bool: ...\ndef random16() -> int: ...\ndef random32() -> int: ...\ndef uint16_add(a: int, b: int) -> int: ...\ndef uint16_gt(a: int, b: int) -> bool: ...\ndef uint16_gte(a: int, b: int) -> bool: ...\ndef uint32_add(a: int, b: int) -> int: ...\ndef uint32_gt(a: int, b: int) -> bool: ...\ndef uint32_gte(a: int, b: int) -> bool: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_uint16_gt", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000275.py"} {"focal_file": "aiortc-master/src/aiortc/utils.py", "focal_class": null, "focal_method": "uint16_gte", "tests": "import unittest\n\nclass Test_uint16_gte(unittest.TestCase):\n def test_uint16_gte(self):\n self.assertFalse(uint16_gte(0, 1))\n self.assertTrue(uint16_gte(1, 1))\n self.assertTrue(uint16_gte(2, 1))\n self.assertTrue(uint16_gte(32768, 1))\n self.assertFalse(uint16_gte(32769, 1))\n self.assertFalse(uint16_gte(65535, 1))\n", "method_code": "def uint16_gte(a: int, b: int) -> bool:\n \"\"\"\n Return a >= b.\n \"\"\"\n return a == b or uint16_gt(a, b)", "context": "def uint16_gte(a: int, b: int) -> bool: ...\ndef random16() -> int: ...\ndef random32() -> int: ...\ndef uint16_add(a: int, b: int) -> int: ...\ndef uint16_gt(a: int, b: int) -> bool: ...\ndef uint16_gte(a: int, b: int) -> bool: ...\ndef uint32_add(a: int, b: int) -> int: ...\ndef uint32_gt(a: int, b: int) -> bool: ...\ndef uint32_gte(a: int, b: int) -> bool: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_uint16_gte", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000276.py"} {"focal_file": "aiortc-master/src/aiortc/utils.py", "focal_class": null, "focal_method": "uint32_add", "tests": "import unittest\n\nclass Test_uint32_add(unittest.TestCase):\n def test_uint32_add(self):\n self.assertEqual(uint32_add(0, 1), 1)\n self.assertEqual(uint32_add(1, 1), 2)\n self.assertEqual(uint32_add(1, 2), 3)\n self.assertEqual(uint32_add(4294967294, 1), 4294967295)\n self.assertEqual(uint32_add(4294967295, 1), 0)\n self.assertEqual(uint32_add(4294967295, 3), 2)\n", "method_code": "def uint32_add(a: int, b: int) -> int:\n \"\"\"\n Return a + b.\n \"\"\"\n return a + b & 4294967295", "context": "def uint32_add(a: int, b: int) -> int: ...\ndef random16() -> int: ...\ndef random32() -> int: ...\ndef uint16_add(a: int, b: int) -> int: ...\ndef uint16_gt(a: int, b: int) -> bool: ...\ndef uint16_gte(a: int, b: int) -> bool: ...\ndef uint32_add(a: int, b: int) -> int: ...\ndef uint32_gt(a: int, b: int) -> bool: ...\ndef uint32_gte(a: int, b: int) -> bool: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_uint32_add", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000277.py"} {"focal_file": "aiortc-master/src/aiortc/utils.py", "focal_class": null, "focal_method": "uint32_gt", "tests": "import unittest\n\nclass Test_uint32_gt(unittest.TestCase):\n def test_uint32_gt(self):\n self.assertFalse(uint32_gt(0, 1))\n self.assertFalse(uint32_gt(1, 1))\n self.assertTrue(uint32_gt(2, 1))\n self.assertTrue(uint32_gt(2147483648, 1))\n self.assertFalse(uint32_gt(2147483649, 1))\n self.assertFalse(uint32_gt(4294967295, 1))\n", "method_code": "def uint32_gt(a: int, b: int) -> bool:\n \"\"\"\n Return a > b.\n \"\"\"\n half_mod = 2147483648\n return a < b and b - a > half_mod or (a > b and a - b < half_mod)", "context": "def uint32_gt(a: int, b: int) -> bool: ...\ndef random16() -> int: ...\ndef random32() -> int: ...\ndef uint16_add(a: int, b: int) -> int: ...\ndef uint16_gt(a: int, b: int) -> bool: ...\ndef uint16_gte(a: int, b: int) -> bool: ...\ndef uint32_add(a: int, b: int) -> int: ...\ndef uint32_gt(a: int, b: int) -> bool: ...\ndef uint32_gte(a: int, b: int) -> bool: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_uint32_gt", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000278.py"} {"focal_file": "aiortc-master/src/aiortc/utils.py", "focal_class": null, "focal_method": "uint32_gte", "tests": "import unittest\n\nclass Test_uint32_gte(unittest.TestCase):\n def test_uint32_gte(self):\n self.assertFalse(uint32_gte(0, 1))\n self.assertTrue(uint32_gte(1, 1))\n self.assertTrue(uint32_gte(2, 1))\n self.assertTrue(uint32_gte(2147483648, 1))\n self.assertFalse(uint32_gte(2147483649, 1))\n self.assertFalse(uint32_gte(4294967295, 1))\n", "method_code": "def uint32_gte(a: int, b: int) -> bool:\n \"\"\"\n Return a >= b.\n \"\"\"\n return a == b or uint32_gt(a, b)", "context": "def uint32_gte(a: int, b: int) -> bool: ...\ndef random16() -> int: ...\ndef random32() -> int: ...\ndef uint16_add(a: int, b: int) -> int: ...\ndef uint16_gt(a: int, b: int) -> bool: ...\ndef uint16_gte(a: int, b: int) -> bool: ...\ndef uint32_add(a: int, b: int) -> int: ...\ndef uint32_gt(a: int, b: int) -> bool: ...\ndef uint32_gte(a: int, b: int) -> bool: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_uint32_gte", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000279.py"} {"focal_file": "aiortc-master/src/aiortc/codecs/vpx.py", "focal_class": null, "focal_method": "_vpx_assert", "tests": "import unittest\n\nclass Test_vpx_assert(unittest.TestCase):\n def test_assert(self):\n with self.assertRaises(Exception) as cm:\n _vpx_assert(1)\n self.assertEqual(str(cm.exception), 'libvpx error: Unspecified internal error')\n", "method_code": "def _vpx_assert(err: int) -> None:\n if err != lib.VPX_CODEC_OK:\n reason = ffi.string(lib.vpx_codec_err_to_string(err))\n raise Exception('libvpx error: ' + reason.decode('utf8'))", "context": "def _vpx_assert(err: int) -> None: ...\ndef number_of_threads(pixels: int, cpus: int) -> int: ...\ndef _vpx_assert(err: int) -> None: ...\ndef vp8_depayload(payload: bytes) -> bytes: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_assert", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000280.py"} {"focal_file": "aiortc-master/src/aiortc/codecs/vpx.py", "focal_class": null, "focal_method": "number_of_threads", "tests": "import unittest\n\nclass Test_number_of_threads(unittest.TestCase):\n def test_number_of_threads(self):\n self.assertEqual(number_of_threads(1920 * 1080, 16), 8)\n self.assertEqual(number_of_threads(1920 * 1080, 8), 3)\n self.assertEqual(number_of_threads(1920 * 1080, 4), 2)\n self.assertEqual(number_of_threads(1920 * 1080, 2), 1)\n", "method_code": "def number_of_threads(pixels: int, cpus: int) -> int:\n if pixels >= 1920 * 1080 and cpus > 8:\n return 8\n elif pixels > 1280 * 960 and cpus >= 6:\n return 3\n elif pixels > 640 * 480 and cpus >= 3:\n return 2\n else:\n return 1", "context": "def number_of_threads(pixels: int, cpus: int) -> int: ...\ndef number_of_threads(pixels: int, cpus: int) -> int: ...\ndef _vpx_assert(err: int) -> None: ...\ndef vp8_depayload(payload: bytes) -> bytes: ...\n", "repository": "0julio0/Icom_openpose", "test_name": "test_number_of_threads", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000281.py"} {"focal_file": "russian_g2p/Grapheme2Phoneme.py", "focal_class": null, "focal_method": "phrase_to_phonemes", "tests": "import unittest\n\nclass Test_phrase_to_phonemes(unittest.TestCase):\n def test_phrase_to_phonemes_positive_tlp7_001(self):\n \"\"\" Checking line 1 for vowels.\"\"\"\n self.assertEqual(['TSH0', 'J0', 'A0'], self.__g2p.phrase_to_phonemes('чья+'))\n self.assertEqual(['TSH0', 'J0', 'I0'], self.__g2p.phrase_to_phonemes('чьи+'))\n self.assertEqual(['U0', 'S0', 'T0', 'J0', 'I'], self.__g2p.phrase_to_phonemes('у+стье'))\n self.assertEqual(['M', 'A0', 'R0', 'J0', 'A'], self.__g2p.phrase_to_phonemes('Ма+рья'))\n self.assertEqual(['K', 'A', 'E0', 'L0', 'J0', 'A'], self.__g2p.phrase_to_phonemes('Коэ+льо'))\n self.assertEqual(['B', 'Y0', 'TSH0', 'J0', 'I'], self.__g2p.phrase_to_phonemes('бы+чьи'))\n self.assertEqual(['B0', 'E0', 'L', 'A', 'J0', 'A'], self.__g2p.phrase_to_phonemes('бе+лая'))\n self.assertEqual(['T', 'V', 'A', 'I0'], self.__g2p.phrase_to_phonemes('твои+'))\n\n def test_phrase_to_phonemes_positive_tlp7_002(self):\n \"\"\" Checking line 2 for vowels.\"\"\"\n self.assertEqual(['R', 'A', 'Z', 'J0', 'O0', 'M'], self.__g2p.phrase_to_phonemes('разъё+м'))\n self.assertEqual(['P', 'A', 'D', 'J0', 'U0', 'P', 'K', 'A', 'J0'], self.__g2p.phrase_to_phonemes('под ю+бкой'))\n self.assertEqual(['B', 'U', 'L0', 'J0', 'O0', 'N'], self.__g2p.phrase_to_phonemes('бульо+н'))\n self.assertEqual(['J0', 'I', 'M', 'SH0', 'I0', 'K'], self.__g2p.phrase_to_phonemes('ямщи+к'))\n self.assertEqual(['V', 'Y0', 'B', 'A', 'R'], self.__g2p.phrase_to_phonemes('вы+бор'))\n self.assertEqual(['A', 'O0', 'R', 'T', 'A'], self.__g2p.phrase_to_phonemes('ао+рта'))\n\n def test_phrase_to_phonemes_positive_tlp7_003(self):\n \"\"\" Checking line 3 for vowels.\"\"\"\n self.assertEqual(['TSH0', 'O0'], self.__g2p.phrase_to_phonemes('чё+'))\n self.assertEqual(['M', 'A0', 'J0', 'A'], self.__g2p.phrase_to_phonemes('ма+йя'))\n self.assertEqual(['SH0', 'I0'], self.__g2p.phrase_to_phonemes('щи+'))\n self.assertEqual(['K0', 'I', 'SH0', 'A0', 'N'], self.__g2p.phrase_to_phonemes('Кещя+н'))\n self.assertEqual(['J0', 'A0', 'R', 'TSH0', 'I'], self.__g2p.phrase_to_phonemes('я+рче'))\n self.assertEqual(['G', 'A', 'S', 'P', 'A0', 'TSH0', 'A'], self.__g2p.phrase_to_phonemes('гаспа+чо'))\n self.assertEqual(['U', 'D', 'A0', 'TSH0', 'A'], self.__g2p.phrase_to_phonemes('уда+ча'))\n\n def test_phrase_to_phonemes_positive_tlp7_004(self):\n \"\"\" Checking line 4 for vowels.\"\"\"\n self.assertEqual(['M', 'A', 'J0', 'A0', 'M0', 'I'], self.__g2p.phrase_to_phonemes('майа+ми'))\n self.assertEqual(['TSH0', 'O0', 'R', 'N', 'Y', 'J0'], self.__g2p.phrase_to_phonemes('чё+рный'))\n self.assertEqual(['TSH0', 'I', 'S', 'T', 'O0', 'T', 'Y'], self.__g2p.phrase_to_phonemes('часто+ты'))\n\n def test_phrase_to_phonemes_positive_tlp7_005(self):\n \"\"\" Checking line 5 for vowels.\"\"\"\n self.assertEqual(['N', 'R', 'A0', 'V0', 'I', 'TS', 'A'], self.__g2p.phrase_to_phonemes('нра+вится'))\n self.assertEqual(['S', 'T', 'R0', 'I', 'ZH', 'Y0'], self.__g2p.phrase_to_phonemes('стрижи+'))\n\n def test_phrase_to_phonemes_positive_tlp7_006(self):\n \"\"\" Checking line 6 for vowels.\"\"\"\n self.assertEqual(['ZH', 'U', 'R0', 'I0'], self.__g2p.phrase_to_phonemes('жюри+'))\n self.assertEqual(['TS', 'E0', 'N', 'T', 'R'], self.__g2p.phrase_to_phonemes('це+нтр'))\n self.assertEqual(['L', 'U', 'TS', 'Y', 'K0', 'I0'], self.__g2p.phrase_to_phonemes('Луцяки+'))\n self.assertEqual(['SH', 'A', 'SH', 'L', 'Y0', 'K'], self.__g2p.phrase_to_phonemes('шашлы+к'))\n self.assertEqual(['SH', 'A', 'K0', 'I0', 'R', 'A', 'V', 'A', 'T0'], self.__g2p.phrase_to_phonemes('шоки+ровать'))\n self.assertEqual(['SH', 'Y', 'P', 'T', 'A0', 'T0'], self.__g2p.phrase_to_phonemes('шепта+ть'))\n self.assertEqual(['ZH', 'Y', 'V', 'O0', 'J0'], self.__g2p.phrase_to_phonemes('живо+й'))\n\n def test_phrase_to_phonemes_positive_tlp7_007(self):\n \"\"\" Checking line 7 for vowels.\"\"\"\n self.assertEqual(['V', 'A0', 'S0', 'A'], self.__g2p.phrase_to_phonemes('Ва+ся'))\n self.assertEqual(['V', 'A0', 'S0', 'I'], self.__g2p.phrase_to_phonemes('Ва+се'))\n self.assertEqual(['V', 'A0', 'S0', 'I'], self.__g2p.phrase_to_phonemes('Ва+си'))\n\n def test_phrase_to_phonemes_positive_tlp7_008(self):\n \"\"\" Checking line 8 for vowels.\"\"\"\n self.assertEqual(['L0', 'I', 'G', 'U0', 'SH', 'K', 'A'], self.__g2p.phrase_to_phonemes('лягу+шка'))\n self.assertEqual(['M', 'A', 'R', 'O0', 'S'], self.__g2p.phrase_to_phonemes('моро+з'))\n\n def test_phrase_to_phonemes_positive_tlp8_001(self):\n \"\"\" Checking line 1 for consonants in the middle\"\"\"\n self.assertEqual(['M0', 'I0', 'T0', 'K', 'A'], self.__g2p.phrase_to_phonemes('Ми+тька'))\n\n def test_phrase_to_phonemes_positive_tlp8_002(self):\n \"\"\" Checking line 2 for consonants in the middle\"\"\"\n self.assertEqual(['D0', 'J0', 'A0', 'K', 'A', 'N'], self.__g2p.phrase_to_phonemes('дья+кон'))\n self.assertEqual(['S', 'A', 'N0', 'T0', 'J0', 'A0', 'G', 'A'], self.__g2p.phrase_to_phonemes('Сантья+го'))\n\n def test_phrase_to_phonemes_positive_tlp8_003(self):\n \"\"\" Checking line 3 for consonants in the middle\"\"\"\n self.assertEqual(['S', 'V', 'A0', 'D0', 'B', 'A'], self.__g2p.phrase_to_phonemes('сва+дьба'))\n self.assertEqual(['ZH', 'Y', 'N0', 'I0', 'D0', 'B', 'A'], self.__g2p.phrase_to_phonemes('жени+тьба'))\n\n def test_phrase_to_phonemes_positive_tlp8_004(self):\n \"\"\" Checking line 4 for consonants in the middle\"\"\"\n self.assertEqual(['D0', 'E0', 'T'], self.__g2p.phrase_to_phonemes('де+д'))\n self.assertEqual(['T0', 'E0', 'R0', 'I', 'M'], self.__g2p.phrase_to_phonemes('те+рем'))\n\n def test_phrase_to_phonemes_positive_tlp8_005(self):\n \"\"\" Checking line 5 for consonants in the middle\"\"\"\n self.assertEqual(['N', 'A', 'K', 'T0', 'O0', 'M'], self.__g2p.phrase_to_phonemes('ногтё+м'))\n self.assertEqual(['L', 'A', 'K', 'T0', 'O0', 'M'], self.__g2p.phrase_to_phonemes('локтё+м'))\n\n def test_phrase_to_phonemes_positive_tlp8_006(self):\n \"\"\" Checking line 6 for consonants in the middle\"\"\"\n self.assertEqual(['G', 'R', 'U0', 'S'], self.__g2p.phrase_to_phonemes('гру+з'))\n self.assertEqual(['K', 'R', 'U0', 'K'], self.__g2p.phrase_to_phonemes('кру+г'))\n\n def test_phrase_to_phonemes_positive_tlp8_007(self):\n \"\"\" Checking line 7 for consonants in the middle\"\"\"\n self.assertEqual(['G', 'D0', 'E0'], self.__g2p.phrase_to_phonemes('где+'))\n self.assertEqual(['V', 'A', 'G', 'Z', 'A0', 'L'], self.__g2p.phrase_to_phonemes('вокза+л'))\n\n def test_phrase_to_phonemes_positive_tlp8_008(self):\n \"\"\" Checking line 8 for consonants in the middle\"\"\"\n self.assertEqual(['G', 'O0', 'L0', 'F'], self.__g2p.phrase_to_phonemes('го+льф'))\n self.assertEqual(['K', 'O0', 'M0', 'I', 'K'], self.__g2p.phrase_to_phonemes('ко+мик'))\n\n def test_phrase_to_phonemes_positive_tlp8_009(self):\n \"\"\" Checking line 1 for consonants in the end\"\"\"\n self.assertEqual(['G', 'R0', 'I0', 'P'], self.__g2p.phrase_to_phonemes('гри+б'))\n self.assertEqual(['T', 'R', 'U0', 'P'], self.__g2p.phrase_to_phonemes('тру+п'))\n\n def test_phrase_to_phonemes_positive_tlp8_010(self):\n \"\"\" Checking line 2 for consonants in the end\"\"\"\n self.assertEqual(['S', 'K', 'O0', 'R', 'P0', 'S', 'T', 'A0', 'R', 'A', 'J0', 'A'], self.__g2p.phrase_to_phonemes('ско+рбь ста+рая'))\n self.assertEqual(['G', 'R', 'U0', 'S0', 'T0', 'P', 'R0', 'I', 'SH', 'L', 'A0'], self.__g2p.phrase_to_phonemes('гру+сть пришла+'))\n\n def test_phrase_to_phonemes_positive_tlp8_011(self):\n \"\"\" Checking line 3 for consonants in the end\"\"\"\n self.assertEqual(['S', 'K', 'O0', 'R', 'P0', 'V0', 'E0', 'TSH0', 'N', 'A', 'J0', 'A'], self.__g2p.phrase_to_phonemes('ско+рбь ве+чная'))\n self.assertEqual(['G', 'R', 'U0', 'S0', 'T0', 'V0', 'E0', 'TSH0', 'N', 'A', 'J0', 'A'], self.__g2p.phrase_to_phonemes('гру+сть ве+чная'))\n\n def test_phrase_to_phonemes_positive_tlp8_012(self):\n \"\"\" Checking line 4 for consonants in the end\"\"\"\n self.assertEqual(['S', 'K', 'O0', 'R', 'B0', 'G', 'O0', 'R0', 'K', 'A', 'J0', 'A'], self.__g2p.phrase_to_phonemes('ско+рбь го+рькая'))\n self.assertEqual(['G', 'R', 'U0', 'Z0', 'D0', 'G', 'O0', 'R0', 'K', 'A', 'J0', 'A'], self.__g2p.phrase_to_phonemes('гру+сть го+рькая'))\n\n def test_phrase_to_phonemes_positive_tlp8_013(self):\n \"\"\" Checking line 5 for consonants in the end\"\"\"\n self.assertEqual(['S', 'K', 'O0', 'R', 'P0', 'U', 'ZH', 'E0'], self.__g2p.phrase_to_phonemes('ско+рбь уже+'))\n self.assertEqual(['G', 'R', 'U0', 'S0', 'T0', 'U', 'ZH', 'E0'], self.__g2p.phrase_to_phonemes('гру+сть уже+'))\n\n def test_phrase_to_phonemes_positive_tlp8_014(self):\n \"\"\" Checking line 6 for consonants in the end\"\"\"\n self.assertEqual(['G', 'R0', 'I0', 'P', 'S', 'V0', 'E0', 'ZH', 'Y', 'J0'], self.__g2p.phrase_to_phonemes('гри+б све+жий'))\n self.assertEqual(['T', 'R', 'U0', 'P', 'S', 'V0', 'E0', 'ZH', 'Y', 'J0'], self.__g2p.phrase_to_phonemes('тру+п све+жий'))\n\n def test_phrase_to_phonemes_positive_tlp8_015(self):\n \"\"\" Checking line 7 for consonants in the end\"\"\"\n self.assertEqual(['G', 'R0', 'I0', 'P', 'V0', 'A0', 'L', 'Y', 'J0'], self.__g2p.phrase_to_phonemes('гри+б вя+лый'))\n self.assertEqual(['T', 'R', 'U0', 'P', 'V0', 'A0', 'L', 'Y', 'J0'], self.__g2p.phrase_to_phonemes('тру+п вя+лый'))\n\n def test_phrase_to_phonemes_positive_tlp8_016(self):\n \"\"\" Checking line 8 for consonants in the end\"\"\"\n self.assertEqual(['G', 'R0', 'I0', 'B', 'G', 'A', 'R0', 'A0', 'TSH0', 'I', 'J0'], self.__g2p.phrase_to_phonemes('гри+б горя+чий'))\n self.assertEqual(['T', 'R', 'U0', 'B', 'G', 'A', 'R0', 'A0', 'TSH0', 'I', 'J0'], self.__g2p.phrase_to_phonemes('тру+п горя+чий'))\n\n def test_phrase_to_phonemes_positive_tlp8_017(self):\n \"\"\" Checking line 9 for consonants in the end\"\"\"\n self.assertEqual(['G', 'R0', 'I0', 'P', 'U', 'ZH', 'E0'], self.__g2p.phrase_to_phonemes('гри+б уже+'))\n self.assertEqual(['T', 'R', 'U0', 'P', 'U', 'ZH', 'E0'], self.__g2p.phrase_to_phonemes('тру+п уже+'))\n\n def test_phrase_to_phonemes_positive001(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Служебное слово - обычная частица. \"\"\"\n self.assertEqual(['N0', 'I', 'D0', 'E0', 'L', 'A', 'T0'], self.__g2p.phrase_to_phonemes('не де+лать'))\n\n def test_phrase_to_phonemes_positive002(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Служебное слово - частица, присоединяемая дефисом. \"\"\"\n self.assertEqual(['P', 'A', 'SH', 'O0', 'L', 'T', 'A', 'K0', 'I'], self.__g2p.phrase_to_phonemes('пошё+л-таки'))\n\n def test_phrase_to_phonemes_positive003(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Внутри служебного слова дефис. \"\"\"\n self.assertEqual(['I', 'Z', 'A', 'T', 'U0', 'TSH0'], self.__g2p.phrase_to_phonemes('из-за ту+ч'))\n\n def test_phrase_to_phonemes_positive004(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Для первого слова: первое слово заканчивается гласной. \"\"\"\n self.assertEqual(['P', 'A', 'D', 'A', 'R', 'O0', 'G0', 'I'], self.__g2p.phrase_to_phonemes('по доро+ге'))\n self.assertEqual(['N', 'A', 'S', 'T', 'A', 'L0', 'E0'], self.__g2p.phrase_to_phonemes('на столе+'))\n\n def test_phrase_to_phonemes_positive005(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Для первого слова: первое слово заканчивается согласной, проверка ассимиляции по глухости-звонкости. \"\"\"\n self.assertEqual(['F', 'S', 'A', 'D', 'U0'], self.__g2p.phrase_to_phonemes('в саду+'))\n self.assertEqual(['V', 'L0', 'I', 'S', 'U0'], self.__g2p.phrase_to_phonemes('в лесу+'))\n self.assertEqual(['Z', 'D', 'A', 'R', 'O0', 'G0', 'I'], self.__g2p.phrase_to_phonemes('с доро+ги'))\n self.assertEqual(['S', 'V', 'A0', 'S0', 'I', 'J0'], self.__g2p.phrase_to_phonemes('с Ва+сей'))\n\n def test_phrase_to_phonemes_positive006(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Для первого слова: первое слово заканчивается твёрдой согласной, которая не должна переходить в мягкую фонему\n перед гласными Я, Ё, Ю, Е, И. \"\"\"\n self.assertEqual(['P', 'A', 'D', 'J0', 'O0', 'L', 'K', 'A', 'J0'], self.__g2p.phrase_to_phonemes('под ё+лкой'))\n\n def test_phrase_to_phonemes_positive007(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Для первого слова: первое слово заканчивается согласной, и она ассимилируется с последующей мягкой\n согласной, одинаковой по месту образования. \"\"\"\n self.assertEqual(['B0', 'I', 'Z0', 'D0', 'E0', 'D', 'A'], self.__g2p.phrase_to_phonemes('без де+да'))\n\n def test_phrase_to_phonemes_positive008(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Для второго слова: первое слово заканчивается мягким знаком, а второе слово начинается с гласной О или с\n гласной И, и эти гласные ни в коем случае не должны переходить в сочетания фонем [J O] или [J I]\n ([J I0], если под ударением) соответственно. \"\"\"\n self.assertEqual(['I', 'L0', 'O0', 'S0', 'I', 'N0'], self.__g2p.phrase_to_phonemes('иль о+сень'))\n self.assertEqual(['I', 'L0', 'I0', 'V', 'A', 'L', 'G', 'A'], self.__g2p.phrase_to_phonemes('иль и+волга'))\n\n def test_phrase_to_phonemes_positive009(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке служебного и знаменательного слова.\n Для второго слова: второе слово начинается с гласной И, которая должна переходить в фонему [Y]\n (или [Y0], если под ударением) после всех согласных, кроме Й. \"\"\"\n self.assertEqual(['P', 'A', 'D', 'Y0', 'V', 'A', 'J0'], self.__g2p.phrase_to_phonemes('под и+вой'))\n self.assertEqual(['S', 'Y', 'V', 'A0', 'N', 'A', 'M'], self.__g2p.phrase_to_phonemes('с Ива+ном'))\n self.assertEqual(['V0', 'I', 'T0', 'I', 'V', 'A0', 'N'], self.__g2p.phrase_to_phonemes('ведь Ива+н'))\n\n def test_phrase_to_phonemes_positive010(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке двух знаменательных слов.\n Для первого слова: если последняя буква первого слова - глухая согласная П, Т, К, Ф, С, Ш, Щ, Ц, Ч (либо\n предпоследняя буква, а последняя - мягкий знак), то эта глухая согласная должна озвончаться, если первой буквой\n второго слова является Б, Д, Г, З или Ж. При этом появляются \"неканонические\", вспомогательные фонемы, которых\n нет при обычном внутрисловном преобразовании: Щ -> [ZH0], Ц -> [DZ], Ч -> [DZH0] \"\"\"\n self.assertEqual(['B', 'O0', 'R', 'ZH0', 'G', 'A', 'R0', 'A0', 'TSH0', 'I', 'J0'], self.__g2p.phrase_to_phonemes('бо+рщ горя+чий'))\n self.assertEqual(['Z', 'A0', 'J0', 'I', 'DZ', 'B0', 'I', 'L0', 'A0', 'K'], self.__g2p.phrase_to_phonemes('за+яц беля+к'))\n self.assertEqual(['D', 'O0', 'DZH0', 'G', 'U', 'L0', 'A0', 'J0', 'I', 'T'], self.__g2p.phrase_to_phonemes('до+чь гуля+ет'))\n\n def test_phrase_to_phonemes_positive011(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке двух знаменательных слов.\n Для первого слова: если последняя буква первого слова - звонкая согласная Б, В, Г, Д, Ж или З (либо\n предпоследняя буква, а последняя - мягкий знак), то она не оглушается тогда и только тогда, когда первой буквой\n второго слова являются Б, Д, Г, З или Ж \"\"\"\n self.assertEqual(['D', 'U0', 'B', 'Z0', 'I', 'L0', 'O0', 'N', 'Y', 'J0'], self.__g2p.phrase_to_phonemes('ду+б зелё+ный'))\n self.assertEqual(['B', 'R', 'O0', 'V0', 'Z', 'O0', 'I'], self.__g2p.phrase_to_phonemes('бро+вь Зо+и'))\n self.assertEqual(['B', 'R', 'O0', 'F0', 'N0', 'I0', 'N', 'Y'], self.__g2p.phrase_to_phonemes('бро+вь Ни+ны'))\n\n def test_phrase_to_phonemes_positive012(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке двух знаменательных слов.\n Для первого слова: если последняя буква первого слова - твёрдая согласная, то она не должна переходить в мягкую\n фонему перед гласными Я, Ё, Ю, Е, И \"\"\"\n self.assertEqual(['S', 'A0', 'T', 'J0', 'O0', 'L', 'A', 'K'], self.__g2p.phrase_to_phonemes('са+д ё+лок'))\n self.assertEqual(['G', 'O0', 'R', 'A', 'T', 'J0', 'I', 'R0', 'I', 'V', 'A0', 'N'], self.__g2p.phrase_to_phonemes('го+род Ерева+н'))\n\n def test_phrase_to_phonemes_positive013(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке двух знаменательных слов.\n Для первого слова: если последняя буква первого слова - согласная, то она не ассимилилуется с последующей мягкой\n согласной, одинаковой по месту образования. \"\"\"\n self.assertEqual(['G', 'O0', 'R', 'A', 'T', 'S0', 'I', 'M', 'B0', 'I0', 'R', 'S', 'K'], self.__g2p.phrase_to_phonemes('го+род Симби+рск'))\n\n def test_phrase_to_phonemes_positive014(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке двух знаменательных слов.\n Для второго слова: второе слово начинается с гласной И, которая должна переходить в фонему [Y]\n (или [Y0], если под ударением) после всех согласных, кроме Й \"\"\"\n self.assertEqual(['L0', 'I0', 'S', 'T', 'Y0', 'V', 'Y'], self.__g2p.phrase_to_phonemes('ли+ст и+вы'))\n self.assertEqual(['N', 'O0', 'S', 'Y', 'V', 'A0', 'N', 'A'], self.__g2p.phrase_to_phonemes('но+с Ива+на'))\n self.assertEqual(['M', 'A0', 'T0', 'I', 'V', 'A0', 'N', 'A'], self.__g2p.phrase_to_phonemes('ма+ть Ива+на'))\n\n def test_phrase_to_phonemes_positive015(self):\n \"\"\" Проверка корректной работы правил межсловного преобразования на стыке двух знаменательных слов.\n Два знаменательных слова объединены в одно через дефис. \"\"\"\n self.assertEqual(['K', 'A', 'Z', 'A', 'K0', 'I0', 'R', 'A', 'Z', 'B', 'O0', 'J0', 'N0', 'I', 'K0', 'I'], self.__g2p.phrase_to_phonemes('казаки+-разбо+йники'))\n self.assertEqual(['J0', 'I', 'D', 'R0', 'I0', 'T0', 'K', 'A', 'L', 'A', 'T0', 'I0', 'T0'], self.__g2p.phrase_to_phonemes('едри+ть-колоти+ть'))\n\n def test_phrase_to_phonemes_positive016(self):\n \"\"\" Проверка корректного транскрибирования некоторых междометий. \"\"\"\n self.assertEqual(['O0', 'KH', 'O0', 'KH', 'O0', 'KH'], self.__g2p.phrase_to_phonemes('о+х-о+х-о+х'))\n self.assertEqual(['B', 'A0', 'J0', 'U', 'SH', 'K0', 'I', 'B', 'A', 'J0', 'U0'], self.__g2p.phrase_to_phonemes('ба+юшки-баю+'))\n self.assertEqual(['T', 'R', 'A0', 'KH', 'T', 'A0', 'KH', 'T', 'A0', 'KH'], self.__g2p.phrase_to_phonemes('тра+х-та+х-та+х'))\n self.assertEqual(['T', 'R0', 'E0', 'N0', 'B', 'R0', 'E0', 'N0'], self.__g2p.phrase_to_phonemes('тре+нь-бре+нь'))\n\n def test_phrase_to_phonemes_positive017(self):\n \"\"\" Проверка корректности транскрибирования целых фраз, состоящих более чем из двух слов.\n Простое предложение. \"\"\"\n self.assertEqual(['J0', 'O0', 'L', 'K', 'A', 'S', 'T', 'A', 'J0', 'A0', 'L', 'A', 'U', 'A', 'K', 'N', 'A0'], self.__g2p.phrase_to_phonemes('ё+лка стоя+ла у окна+'))\n self.assertEqual(['SH', 'A', 'F0', 'O0', 'R', 'V0', 'I', 'D0', 'O0', 'T', 'M', 'A', 'SH', 'Y0', 'N', 'U'], self.__g2p.phrase_to_phonemes('шофё+р ведё+т маши+ну'))\n self.assertEqual(['A', 'M', 'A', 'SH', 'Y0', 'N', 'A', 'N0', 'I', 'V', 'Y0', 'D0', 'I', 'R', 'ZH', 'A', 'L', 'A', 'P0', 'I', 'R0', 'I', 'G', 'R', 'U0', 'S', 'K0', 'I'], self.__g2p.phrase_to_phonemes('а маши+на не вы+держала перегру+зки'))\n self.assertEqual(['M', 'O0', 'S', 'T', 'TSH0', 'E0', 'R0', 'I', 'Z', 'N', 'A', 'V', 'A', 'S0', 'I', 'B0', 'I0', 'R', 'S', 'K'], self.__g2p.phrase_to_phonemes('мо+ст че+рез новосиби+рск'))\n\n def test_phrase_to_phonemes_positive018(self):\n \"\"\" Проверка корректности транскрибирования целых фраз, состоящих более чем из двух слов.\n Простое предложение с двумя словами-фонетическими исключениями (\"мужчины\" и \"декольте\"). \"\"\"\n self.assertEqual(['P', 'A', 'TS', 'Y', 'L', 'U0', 'J0', 'M', 'U', 'SH0', 'I0', 'N', 'Y', 'F', 'SH0', 'E0', 'D', 'R', 'A', 'T', 'K', 'R', 'Y0', 'T', 'A', 'J0', 'I', 'ZH', 'E0', 'N', 'S', 'K', 'A', 'J0', 'I', 'D', 'Y', 'K', 'A', 'L0', 'T', 'E0', 'V', 'O0', 'F', 'S0', 'I', 'N0', 'I', 'SH0', 'I', 'T', 'A0', 'L', 'S0', 'A', 'N0', 'I', 'P', 'R0', 'I', 'L0', 'I0', 'TSH0', 'N', 'Y', 'M'], self.__g2p.phrase_to_phonemes('поцелу+й мужчи+ны в ще+дро откры+тое же+нское декольте+ во+все не счита+лся неприли+чным'))\n\n def test_phrase_to_phonemes_positive019(self):\n \"\"\" Проверка стыка знаменательного и служебного слов в ситуации, когда служебное слово идёт вторым. \"\"\"\n self.assertEqual(['J0', 'E0', 'S', 'L0', 'I', 'B', 'Y', 'N0', 'I', 'T', 'Y0'], self.__g2p.phrase_to_phonemes('е+сли бы не ты+'))\n self.assertEqual(['J0', 'E0', 'S', 'L0', 'I', 'P', 'N0', 'E0', 'B', 'Y', 'L', 'A', 'T0', 'I', 'B0', 'A0'], self.__g2p.phrase_to_phonemes('е+сли б не+ было тебя+'))\n\n def test_phrase_to_phonemes_positive020(self):\n \"\"\" Проверка стыка знаменательного и служебного слов в ситуации, когда служебное слово - частица с дефисом. \"\"\"\n self.assertEqual(['D', 'A', 'V', 'A0', 'J0', 'K', 'A', 'R', 'A', 'Z', 'B0', 'I', 'R0', 'O0', 'M', 'S0', 'A'], self.__g2p.phrase_to_phonemes('дава+й-ка разберё+мся'))\n\n def test_phrase_to_phonemes_negative001(self):\n \"\"\" Генерация исключения, если аргумент - пустая строка. \"\"\"\n source_phrase = ''\n target_error_message = 'Checked phrase is empty string!'\n with self.assertRaisesRegex(AssertionError, re.escape(target_error_message)):\n self.__g2p.phrase_to_phonemes(source_phrase)\n", "method_code": " def phrase_to_phonemes(self, source_phrase: str) -> list:\n error_message = f'`{source_phrase}`: this phrase is incorrect!'\n source_phrase = source_phrase.lower().replace('-', ' ')\n source_phrase = re.sub('[^a-zйцукенгшщзхъфывапролджэячсмитьбюё+ ]', '', source_phrase)\n self.check_phrase(source_phrase)\n words_in_phrase = source_phrase.split()\n l = len(words_in_phrase)\n for i in range(l):\n if words_in_phrase[i] in self.__exclusions_dictionary:\n words_in_phrase[i] = self.__exclusions_dictionary[words_in_phrase[i]]\n words_in_phrase[i] = self.__prepare_word(words_in_phrase[i])\n new_words = list()\n cur_word = ''\n last_letter = ''\n for i in range(0, l):\n clear_word = words_in_phrase[i].replace('+', '')\n to_append = i == l - 1 or clear_word not in self.__function_words_1\n if words_in_phrase[i][0] == 'и':\n if last_letter not in self.mode.vocals | {'ь', ''} | self.mode.soft_consonants:\n words_in_phrase[i] = 'ы' + words_in_phrase[i][1:]\n if words_in_phrase[i][0] in self.mode.double_vocals:\n words_in_phrase[i] = 'ъ' + words_in_phrase[i]\n cur_word += words_in_phrase[i]\n if to_append:\n new_words.append(cur_word)\n cur_word = ''\n last_letter = clear_word[-1]\n next_phoneme = 'sil'\n phrase_transcription = []\n for i in range(len(new_words) - 1, -1, -1):\n new_transcription = self.word_to_phonemes(new_words[i], next_phoneme)\n new_transcription = self.__remove_repeats_from_transcription(new_transcription)\n new_transcription = self.__remove_long_phonemes(new_transcription)\n phrase_transcription = [new_transcription] + phrase_transcription\n next_phoneme = new_transcription[0]\n final_transcription = list()\n for word_transcription in phrase_transcription:\n final_transcription += word_transcription\n final_transcription = self.__remove_repeats_from_transcription(final_transcription, full=False)\n final_transcription = self.__remove_long_phonemes(final_transcription)\n return final_transcription\n ", "context": "class Grapheme2Phoneme(RulesForGraphemes):\n def phrase_to_phonemes(self, source_phrase: str) -> list: ...\n def __init__(self, users_mode='Modern', exception_for_nonaccented=False): ...\n def russian_letters(self) -> list: ...\n def russian_phonemes(self) -> list: ...\n def silence_name(self) -> str: ...\n def load_exclusions_dictionary(self, file_name: str) -> dict: ...\n def check_word(self, checked_word: str): ...\n def check_phrase(self, checked_phrase: str): ...\n def word_to_phonemes(self, source_word: str, next_phoneme: str='sil') -> list: ...\n def in_function_words_1(self, source_word: str) -> bool: ...\n def in_function_words_2(self, source_word: str) -> bool: ...\n def __remove_character(self, source_word: str, removed_char: str) -> str: ...\n def __prepare_word(self, cur_word: str) -> str: ...\n def __word_to_letters_list(self, cur_word: str) -> list: ...\n def __remove_repeats_from_transcription(self, source_transcription: list, full: bool=True) -> list: ...\n def __remove_long_phonemes(self, source_transcription: list) -> list: ...\n\n self.exception_for_nonaccented = exception_for_nonaccented\n self.__re_for_phrase_split = None\n self.__silence_name = 'sil'\n self.__function_words_1 = {'без', 'близ', 'в', 'из', 'меж', 'над', 'об', 'под', 'пред', 'перед', 'чрез', 'через', 'из-под', 'по-над'}\n self.__function_words_2 = {'бы', 'б', 'де', 'ли', 'же', '-то', '-ка', '-либо', '-нибудь', '-таки'}\n self.__exclusions_dictionary = None\n self.__exclusions_dictionary = self.load_exclusions_dictionary(exclusions_dictionary_name)\n self.__re_for_phrase_split = re.compile('[\\\\s\\\\-]+', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_phrase_to_phonemes_positive_tlp7_001", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000282.py"} {"focal_file": "russian_g2p/Grapheme2Phoneme.py", "focal_class": null, "focal_method": "word_to_phonemes", "tests": "import unittest\n\nclass Test_word_to_phonemes(unittest.TestCase):\n def test_word_to_phonemes_positive029(self):\n \"\"\" Проверка корректности обработки прописных букв. \"\"\"\n self.assertEqual(self.__g2p.word_to_phonemes('ё+жик'), self.__g2p.word_to_phonemes('Ё+жик'))\n\n @unittest.skip\n def test_word_to_phonemes_positive030(self):\n \"\"\" Проверка корректности обработки ударения для буквы `ё` -- устарел. \"\"\"\n self.assertEqual(self.__g2p.word_to_phonemes('ё+жик'), self.__g2p.word_to_phonemes('ёжик'))\n self.assertEqual(self.__g2p.word_to_phonemes('ё+жик'), self.__g2p.word_to_phonemes('Ёжик'))\n\n def test_word_to_phonemes_positive031(self):\n \"\"\" Баг https://github.com/nsu-ai/russian_g2p/issues/8 \"\"\"\n self.assertEqual(['SH', 'A', 'F0', 'O0', 'R'], self.__g2p.word_to_phonemes('шофё+р'))\n\n def test_word_to_phonemes_positive032(self):\n \"\"\" Баг https://github.com/nsu-ai/russian_g2p/issues/8 \"\"\"\n self.assertEqual(['J0', 'I0', 'TSH0', 'N0', 'I', 'TS', 'U'], self.__g2p.word_to_phonemes('яи+чницу'))\n\n def test_word_to_phonemes_positive033(self):\n \"\"\" Проверка, что костыль для удаления длинных фонем работает \"\"\"\n self.assertEqual(['A', 'B0', 'I', 'S0', 'I0', 'N0', 'I'], self.__g2p.word_to_phonemes('абисси+нии'))\n\n def test_word_to_phonemes_negative001(self):\n \"\"\" Генерация исключения, если аргумент - пустая строка. \"\"\"\n source_word = ''\n target_error_message = 'Checked word is empty string!'\n with self.assertRaisesRegex(AssertionError, re.escape(target_error_message)):\n self.__g2p.word_to_phonemes(source_word)\n\n def test_word_to_phonemes_negative002(self):\n \"\"\" Генерация исключения, если слово содержит недопустимые символы. \"\"\"\n source_word = 'интерде+вочка!'\n target_error_message = '`интерде+вочка!`: this word contains inadmissible characters!'\n with self.assertRaisesRegex(AssertionError, re.escape(target_error_message)):\n self.__g2p.word_to_phonemes(source_word)\n\n def test_word_to_phonemes_negative003(self):\n \"\"\" Генерация исключения, если слово содержит только неалфавитные символы, хоть и допустимые. \"\"\"\n source_word = '+-'\n target_error_message = '`+-`: this word is incorrect!'\n with self.assertRaisesRegex(AssertionError, re.escape(target_error_message)):\n self.__g2p.word_to_phonemes(source_word)\n\n def test_word_to_phonemes_negative004(self):\n \"\"\" Генерация предупреждения, если слово указано без ударения и содержит более одной гласной. \"\"\"\n source_word = 'через'\n target_warning_message = '`через`: the accent for this word is unknown!'\n with self.assertWarnsRegex(UserWarning, re.escape(target_warning_message)):\n self.__g2p.word_to_phonemes(source_word)\n\n def test_word_to_phonemes_negative005(self):\n \"\"\" Генерация исключения, если exception_for_nonaccented, а слово - без ударения и содержит более 1 гласной. \"\"\"\n g2p = Grapheme2Phoneme(exception_for_nonaccented=True)\n source_word = 'через'\n target_warning_message = '`через`: the accent for this word is unknown!'\n with self.assertRaisesRegex(ValueError, re.escape(target_warning_message)):\n g2p.word_to_phonemes(source_word)\n", "method_code": " def word_to_phonemes(self, source_word: str, next_phoneme: str='sil') -> list:\n self.check_word(source_word)\n error_message = f'`{source_word}`: this word is incorrect!'\n prepared_word = source_word.lower()\n if prepared_word in self.__exclusions_dictionary:\n prepared_word = self.__exclusions_dictionary[prepared_word]\n if '+' not in prepared_word:\n counter = len(prepared_word) - len(re.sub('[аоуэыияёею]', '', prepared_word))\n if counter > 1:\n if self.exception_for_nonaccented:\n raise ValueError(f'`{source_word}`: the accent for this word is unknown!')\n warnings.warn(f'`{source_word}`: the accent for this word is unknown!')\n if prepared_word in self.__exclusions_dictionary:\n prepared_word = self.__exclusions_dictionary[prepared_word]\n prepared_word = prepared_word.replace(\"'\", '')\n if '-' in prepared_word:\n if not self.in_function_words_1(prepared_word) and (not self.in_function_words_2(prepared_word)):\n word_parts = list(filter(lambda a: len(a) > 0, map(lambda b: b.strip(), prepared_word.split('-'))))\n assert len(word_parts) > 0, error_message\n prepared_word_parts = [word_parts[0]]\n for cur_part in word_parts[1:]:\n if self.in_function_words_1('-' + cur_part) or self.in_function_words_2('-' + cur_part):\n prepared_word_parts.append('-' + cur_part)\n else:\n prepared_word_parts.append(cur_part)\n return self.phrase_to_phonemes(' '.join(prepared_word_parts))\n prepared_word = self.__remove_character(prepared_word, '-')\n letters_list = self.__word_to_letters_list(self.__prepare_word(prepared_word))\n n = len(letters_list)\n assert n > 0, error_message\n ind = n - 1\n transcription = list()\n while ind >= 0:\n if ind >= 0 and letters_list[ind] in self.mode.hard_and_soft_signs:\n ind -= 1\n continue\n if letters_list[ind] in self.mode.vocals:\n new_phonemes = self.apply_rule_for_vocals(letters_list, ind)\n else:\n assert letters_list[ind] in self.mode.consonants, error_message\n new_phonemes = self.apply_rule_for_consonants(letters_list, next_phoneme, ind)\n ind -= 1\n transcription = new_phonemes + transcription\n next_phoneme = new_phonemes[0]\n assert len(transcription) > 0, f'`{source_word}`: this word cannot be transcribed!'\n return self.__remove_long_phonemes(self.__remove_repeats_from_transcription(transcription))\n ", "context": "class Grapheme2Phoneme(RulesForGraphemes):\n def word_to_phonemes(self, source_word: str, next_phoneme: str='sil') -> list: ...\n def __init__(self, users_mode='Modern', exception_for_nonaccented=False): ...\n def russian_letters(self) -> list: ...\n def russian_phonemes(self) -> list: ...\n def silence_name(self) -> str: ...\n def load_exclusions_dictionary(self, file_name: str) -> dict: ...\n def check_word(self, checked_word: str): ...\n def check_phrase(self, checked_phrase: str): ...\n def phrase_to_phonemes(self, source_phrase: str) -> list: ...\n def in_function_words_1(self, source_word: str) -> bool: ...\n def in_function_words_2(self, source_word: str) -> bool: ...\n def __remove_character(self, source_word: str, removed_char: str) -> str: ...\n def __prepare_word(self, cur_word: str) -> str: ...\n def __word_to_letters_list(self, cur_word: str) -> list: ...\n def __remove_repeats_from_transcription(self, source_transcription: list, full: bool=True) -> list: ...\n def __remove_long_phonemes(self, source_transcription: list) -> list: ...\n\n self.exception_for_nonaccented = exception_for_nonaccented\n self.__re_for_phrase_split = None\n self.__silence_name = 'sil'\n self.__function_words_1 = {'без', 'близ', 'в', 'из', 'меж', 'над', 'об', 'под', 'пред', 'перед', 'чрез', 'через', 'из-под', 'по-над'}\n self.__function_words_2 = {'бы', 'б', 'де', 'ли', 'же', '-то', '-ка', '-либо', '-нибудь', '-таки'}\n self.__exclusions_dictionary = None\n self.__exclusions_dictionary = self.load_exclusions_dictionary(exclusions_dictionary_name)\n self.__re_for_phrase_split = re.compile('[\\\\s\\\\-]+', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_word_to_phonemes_positive029", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000283.py"} {"focal_file": "russian_g2p/Grapheme2Phoneme.py", "focal_class": null, "focal_method": "in_function_words_1", "tests": "import unittest\n\nclass Test_in_function_words_1(unittest.TestCase):\n def test_in_function_words_1_positive001(self):\n \"\"\" Проверить корректность определения функциональных слов первого рода. \"\"\"\n self.assertFalse(self.__g2p.in_function_words_1('ма+ма'))\n self.assertFalse(self.__g2p.in_function_words_1('мама'))\n self.assertFalse(self.__g2p.in_function_words_1('Ма+ма'))\n self.assertTrue(self.__g2p.in_function_words_1('через'))\n self.assertTrue(self.__g2p.in_function_words_1('че+рез'))\n self.assertTrue(self.__g2p.in_function_words_1('Через'))\n", "method_code": " def in_function_words_1(self, source_word: str) -> bool:\n return self.__remove_character(source_word, '+').lower() in self.__function_words_1\n ", "context": "class Grapheme2Phoneme(RulesForGraphemes):\n def in_function_words_1(self, source_word: str) -> bool: ...\n def __init__(self, users_mode='Modern', exception_for_nonaccented=False): ...\n def russian_letters(self) -> list: ...\n def russian_phonemes(self) -> list: ...\n def silence_name(self) -> str: ...\n def load_exclusions_dictionary(self, file_name: str) -> dict: ...\n def check_word(self, checked_word: str): ...\n def check_phrase(self, checked_phrase: str): ...\n def word_to_phonemes(self, source_word: str, next_phoneme: str='sil') -> list: ...\n def phrase_to_phonemes(self, source_phrase: str) -> list: ...\n def in_function_words_2(self, source_word: str) -> bool: ...\n def __remove_character(self, source_word: str, removed_char: str) -> str: ...\n def __prepare_word(self, cur_word: str) -> str: ...\n def __word_to_letters_list(self, cur_word: str) -> list: ...\n def __remove_repeats_from_transcription(self, source_transcription: list, full: bool=True) -> list: ...\n def __remove_long_phonemes(self, source_transcription: list) -> list: ...\n\n self.exception_for_nonaccented = exception_for_nonaccented\n self.__re_for_phrase_split = None\n self.__silence_name = 'sil'\n self.__function_words_1 = {'без', 'близ', 'в', 'из', 'меж', 'над', 'об', 'под', 'пред', 'перед', 'чрез', 'через', 'из-под', 'по-над'}\n self.__function_words_2 = {'бы', 'б', 'де', 'ли', 'же', '-то', '-ка', '-либо', '-нибудь', '-таки'}\n self.__exclusions_dictionary = None\n self.__exclusions_dictionary = self.load_exclusions_dictionary(exclusions_dictionary_name)\n self.__re_for_phrase_split = re.compile('[\\\\s\\\\-]+', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_in_function_words_1_positive001", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000284.py"} {"focal_file": "russian_g2p/Grapheme2Phoneme.py", "focal_class": null, "focal_method": "in_function_words_2", "tests": "import unittest\n\nclass Test_in_function_words_2(unittest.TestCase):\n def test_in_function_words_2_positive001(self):\n \"\"\" Проверить корректность определения функциональных слов второго рода. \"\"\"\n self.assertFalse(self.__g2p.in_function_words_2('ма+ма'))\n self.assertFalse(self.__g2p.in_function_words_2('мама'))\n self.assertFalse(self.__g2p.in_function_words_2('Ма+ма'))\n self.assertTrue(self.__g2p.in_function_words_2('-нибудь'))\n self.assertTrue(self.__g2p.in_function_words_2('-нибу+дь'))\n self.assertFalse(self.__g2p.in_function_words_2('нибудь'))\n self.assertFalse(self.__g2p.in_function_words_2('нибу+дь'))\n", "method_code": " def in_function_words_2(self, source_word: str) -> bool:\n return self.__remove_character(source_word, '+').lower() in self.__function_words_2\n ", "context": "class Grapheme2Phoneme(RulesForGraphemes):\n def in_function_words_2(self, source_word: str) -> bool: ...\n def __init__(self, users_mode='Modern', exception_for_nonaccented=False): ...\n def russian_letters(self) -> list: ...\n def russian_phonemes(self) -> list: ...\n def silence_name(self) -> str: ...\n def load_exclusions_dictionary(self, file_name: str) -> dict: ...\n def check_word(self, checked_word: str): ...\n def check_phrase(self, checked_phrase: str): ...\n def word_to_phonemes(self, source_word: str, next_phoneme: str='sil') -> list: ...\n def phrase_to_phonemes(self, source_phrase: str) -> list: ...\n def in_function_words_1(self, source_word: str) -> bool: ...\n def __remove_character(self, source_word: str, removed_char: str) -> str: ...\n def __prepare_word(self, cur_word: str) -> str: ...\n def __word_to_letters_list(self, cur_word: str) -> list: ...\n def __remove_repeats_from_transcription(self, source_transcription: list, full: bool=True) -> list: ...\n def __remove_long_phonemes(self, source_transcription: list) -> list: ...\n\n self.exception_for_nonaccented = exception_for_nonaccented\n self.__re_for_phrase_split = None\n self.__silence_name = 'sil'\n self.__function_words_1 = {'без', 'близ', 'в', 'из', 'меж', 'над', 'об', 'под', 'пред', 'перед', 'чрез', 'через', 'из-под', 'по-над'}\n self.__function_words_2 = {'бы', 'б', 'де', 'ли', 'же', '-то', '-ка', '-либо', '-нибудь', '-таки'}\n self.__exclusions_dictionary = None\n self.__exclusions_dictionary = self.load_exclusions_dictionary(exclusions_dictionary_name)\n self.__re_for_phrase_split = re.compile('[\\\\s\\\\-]+', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_in_function_words_2_positive001", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000285.py"} {"focal_file": "russian_g2p/Accentor.py", "focal_class": null, "focal_method": "do_accents", "tests": "import unittest\n\nclass Test_do_accents(unittest.TestCase):\n def test_do_accents_positive08(self):\n accentor = Accentor(exception_for_unknown=True)\n source_phrase = [['хракозябр'], ['впулил'], ['куздру']]\n with self.assertRaises(ValueError):\n _ = accentor.do_accents(source_phrase)\n\n def test_do_accents_positive11(self):\n accentor = Accentor(exception_for_unknown=True)\n source_phrase = [['зеленого'], ['камня']]\n target_variants = [['зелё+ного', 'ка+мня']]\n real_variants = accentor.do_accents(source_phrase)\n self.assertEqual(target_variants, real_variants)\n\n def test_do_accents_negative04(self):\n source_phrase = [['а-зе']]\n target_err_msg = re.escape('Word `а-зе` is unknown!')\n accentor = Accentor(exception_for_unknown=True, use_wiki=False)\n with self.assertRaisesRegex(ValueError, target_err_msg):\n accentor.do_accents(source_phrase)\n", "method_code": " def do_accents(self, source_phrase_and_morphotags: list) -> list:\n self.logger.debug('Checking the source phrase...')\n error_message = f'`{source_phrase_and_morphotags}`: the phrase should be of a \"list of lists\" format!\\nExample: [[\"word1\",\"morphotag1\"], [\"word2\",\"morphotag2\"]] or [[\"word1\"], [\"word2\"]]'\n assert isinstance(source_phrase_and_morphotags, list), error_message\n try:\n assert isinstance(source_phrase_and_morphotags[0], list), error_message\n except IndexError:\n assert len(source_phrase_and_morphotags) > 0, 'Source phrase is empty!'\n try:\n source_phrase, morphotags_of_phrase = list(zip(*source_phrase_and_morphotags))\n except (ValueError, TypeError):\n source_phrase = list(zip(*source_phrase_and_morphotags))[0]\n morphotags_of_phrase = None\n for pair in source_phrase_and_morphotags:\n assert len(pair) == len(source_phrase_and_morphotags[0]), f'`{' '.join(source_phrase)}`: morphotags do not correspond to words!'\n prepared_phrase = []\n for cur_word in source_phrase:\n assert len(cur_word.strip()) > 0, f'`{source_phrase}`: this phrase is wrong!'\n prepared_phrase.append(cur_word.strip().lower())\n if morphotags_of_phrase is not None:\n assert len(prepared_phrase) == len(morphotags_of_phrase), f'`{' '.join(source_phrase)}`: morphotags do not correspond to words!'\n assert len(prepared_phrase) > 0, 'Source phrase is empty!'\n try:\n res = self.__do_accents(prepared_phrase, morphotags_of_phrase)\n except Exception as e:\n err_msg = str(e)\n ok = False\n res = []\n for modified_phrase in self.__generate_phrases_with_jo(prepared_phrase, []):\n try:\n res = self.__do_accents(modified_phrase, morphotags_of_phrase)\n ok = True\n except Exception as e:\n ok = False\n err_msg = str(e)\n if ok:\n break\n if not ok:\n raise ValueError(err_msg)\n return res\n ", "context": "class Accentor():\n def do_accents(self, source_phrase_and_morphotags: list) -> list: ...\n def __init__(self, mode='one', debug='no', exception_for_unknown=False, use_wiki=True): ...\n def __del__(self): ...\n def get_correct_omograph_wiki(self, root_text, cur_word, morphotag='X'): ...\n def get_simple_form_wiki(self, root_text, form): ...\n def load_wiki_page(self, cur_form): ...\n def check_source_wordform(self, checked: str) -> bool: ...\n def check_accented_wordform(self, checked: str) -> bool: ...\n def check_morphotag(self, morphotag: str) -> bool: ...\n def calculate_morpho_similarity(self, morphotags_1: str, morphotags_2: str) -> float: ...\n def prepare_morphotag(self, source_morphotag: str) -> str: ...\n def get_new_dics(self): ...\n def get_bad_words(self): ...\n def __generate_phrases_with_jo(self, old_phrase, new_phrase): ...\n def __do_accents(self, words_list: list, morphotags_list: list=None) -> list: ...\n\n self.logger = logging.getLogger()\n self.mode = mode\n self.__all_russian_letters = {'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'}\n self.__russian_vowels = {'а', 'о', 'у', 'э', 'ы', 'и', 'я', 'ё', 'ю', 'е'}\n self.exception_for_unknown = exception_for_unknown\n self.use_wiki = use_wiki\n self.__homonyms = None\n self.__simple_words_dawg = None\n self.__function_words = None\n self.__new_homonyms = {}\n self.__new_simple_words = set()\n self.__bad_words = []\n self.__re_for_morphosplit = re.compile('[\\\\,\\\\s\\\\|]+', re.U)\n self.__re_for_morphotag = re.compile('^(\\\\w+|\\\\w+[\\\\-\\\\=]\\\\w+)$', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_do_accents_positive08", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000286.py"} {"focal_file": "russian_g2p/Accentor.py", "focal_class": null, "focal_method": "check_source_wordform", "tests": "import unittest\n\nclass Test_check_source_wordform(unittest.TestCase):\n def test_check_source_wordform_positive01(self):\n self.assertTrue(self.__accentor.check_source_wordform('абвг'))\n self.assertTrue(self.__accentor.check_source_wordform('аб-вг'))\n self.assertFalse(self.__accentor.check_source_wordform('-'))\n self.assertFalse(self.__accentor.check_source_wordform(''))\n self.assertFalse(self.__accentor.check_source_wordform('-абвг'))\n self.assertFalse(self.__accentor.check_source_wordform('аб--вг'))\n self.assertFalse(self.__accentor.check_source_wordform('abcабвг'))\n self.assertFalse(self.__accentor.check_source_wordform('abc'))\n self.assertFalse(self.__accentor.check_source_wordform('abcабвг123'))\n", "method_code": " def check_source_wordform(self, checked: str) -> bool:\n if len(checked.strip()) == 0:\n return False\n res = len(self.__all_russian_letters | {'-'}) == len(self.__all_russian_letters | {'-'} | set(checked.lower()))\n if not res:\n return False\n if '-' not in checked:\n return True\n for cur_part in checked.split('-'):\n if len(cur_part) == 0:\n res = False\n break\n return res\n ", "context": "class Accentor():\n def check_source_wordform(self, checked: str) -> bool: ...\n def __init__(self, mode='one', debug='no', exception_for_unknown=False, use_wiki=True): ...\n def __del__(self): ...\n def get_correct_omograph_wiki(self, root_text, cur_word, morphotag='X'): ...\n def get_simple_form_wiki(self, root_text, form): ...\n def load_wiki_page(self, cur_form): ...\n def do_accents(self, source_phrase_and_morphotags: list) -> list: ...\n def check_accented_wordform(self, checked: str) -> bool: ...\n def check_morphotag(self, morphotag: str) -> bool: ...\n def calculate_morpho_similarity(self, morphotags_1: str, morphotags_2: str) -> float: ...\n def prepare_morphotag(self, source_morphotag: str) -> str: ...\n def get_new_dics(self): ...\n def get_bad_words(self): ...\n def __generate_phrases_with_jo(self, old_phrase, new_phrase): ...\n def __do_accents(self, words_list: list, morphotags_list: list=None) -> list: ...\n\n self.logger = logging.getLogger()\n self.mode = mode\n self.__all_russian_letters = {'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'}\n self.__russian_vowels = {'а', 'о', 'у', 'э', 'ы', 'и', 'я', 'ё', 'ю', 'е'}\n self.exception_for_unknown = exception_for_unknown\n self.use_wiki = use_wiki\n self.__homonyms = None\n self.__simple_words_dawg = None\n self.__function_words = None\n self.__new_homonyms = {}\n self.__new_simple_words = set()\n self.__bad_words = []\n self.__re_for_morphosplit = re.compile('[\\\\,\\\\s\\\\|]+', re.U)\n self.__re_for_morphotag = re.compile('^(\\\\w+|\\\\w+[\\\\-\\\\=]\\\\w+)$', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_check_source_wordform_positive01", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000287.py"} {"focal_file": "russian_g2p/Accentor.py", "focal_class": null, "focal_method": "check_accented_wordform", "tests": "import unittest\n\nclass Test_check_accented_wordform(unittest.TestCase):\n def test_check_accented_wordform_positive01(self):\n self.assertTrue(self.__accentor.check_accented_wordform('абвг'))\n self.assertTrue(self.__accentor.check_accented_wordform('аб-вг'))\n self.assertFalse(self.__accentor.check_accented_wordform('-'))\n self.assertFalse(self.__accentor.check_accented_wordform(''))\n self.assertFalse(self.__accentor.check_accented_wordform('-абвг'))\n self.assertFalse(self.__accentor.check_accented_wordform('аб--вг'))\n self.assertFalse(self.__accentor.check_accented_wordform('abcабвг'))\n self.assertFalse(self.__accentor.check_accented_wordform('abc'))\n self.assertFalse(self.__accentor.check_accented_wordform('abcабвг123'))\n self.assertTrue(self.__accentor.check_accented_wordform('а+бвг'))\n self.assertTrue(self.__accentor.check_accented_wordform('а+бвгде+жз'))\n self.assertTrue(self.__accentor.check_accented_wordform('а+б-вг'))\n self.assertFalse(self.__accentor.check_accented_wordform('-'))\n self.assertFalse(self.__accentor.check_accented_wordform('+-'))\n self.assertFalse(self.__accentor.check_accented_wordform('+'))\n self.assertFalse(self.__accentor.check_accented_wordform(''))\n self.assertFalse(self.__accentor.check_accented_wordform('-а+бвг'))\n self.assertFalse(self.__accentor.check_accented_wordform('а+б--вг'))\n self.assertFalse(self.__accentor.check_accented_wordform('a+bcа+бвг'))\n self.assertFalse(self.__accentor.check_accented_wordform('a+bc'))\n self.assertFalse(self.__accentor.check_accented_wordform('a+bcа+бвг123'))\n", "method_code": " def check_accented_wordform(self, checked: str) -> bool:\n if len(checked.strip()) == 0:\n return False\n res = len(self.__all_russian_letters | {'-', '+'}) == len(self.__all_russian_letters | {'-', '+'} | set(checked.lower()))\n if not res:\n return False\n if '-' in checked:\n parts = list()\n for cur_part in checked.split('-'):\n parts.append(cur_part.lower().strip())\n else:\n parts = [checked.lower().strip()]\n for cur_part in parts:\n filtered_part = ''.join(list(filter(lambda c: c != '+', cur_part)))\n if len(filtered_part) == 0:\n res = False\n break\n return res\n ", "context": "class Accentor():\n def check_accented_wordform(self, checked: str) -> bool: ...\n def __init__(self, mode='one', debug='no', exception_for_unknown=False, use_wiki=True): ...\n def __del__(self): ...\n def get_correct_omograph_wiki(self, root_text, cur_word, morphotag='X'): ...\n def get_simple_form_wiki(self, root_text, form): ...\n def load_wiki_page(self, cur_form): ...\n def do_accents(self, source_phrase_and_morphotags: list) -> list: ...\n def check_source_wordform(self, checked: str) -> bool: ...\n def check_morphotag(self, morphotag: str) -> bool: ...\n def calculate_morpho_similarity(self, morphotags_1: str, morphotags_2: str) -> float: ...\n def prepare_morphotag(self, source_morphotag: str) -> str: ...\n def get_new_dics(self): ...\n def get_bad_words(self): ...\n def __generate_phrases_with_jo(self, old_phrase, new_phrase): ...\n def __do_accents(self, words_list: list, morphotags_list: list=None) -> list: ...\n\n self.logger = logging.getLogger()\n self.mode = mode\n self.__all_russian_letters = {'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'}\n self.__russian_vowels = {'а', 'о', 'у', 'э', 'ы', 'и', 'я', 'ё', 'ю', 'е'}\n self.exception_for_unknown = exception_for_unknown\n self.use_wiki = use_wiki\n self.__homonyms = None\n self.__simple_words_dawg = None\n self.__function_words = None\n self.__new_homonyms = {}\n self.__new_simple_words = set()\n self.__bad_words = []\n self.__re_for_morphosplit = re.compile('[\\\\,\\\\s\\\\|]+', re.U)\n self.__re_for_morphotag = re.compile('^(\\\\w+|\\\\w+[\\\\-\\\\=]\\\\w+)$', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_check_accented_wordform_positive01", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000288.py"} {"focal_file": "russian_g2p/Accentor.py", "focal_class": null, "focal_method": "check_morphotag", "tests": "import unittest\n\nclass Test_check_morphotag(unittest.TestCase):\n def test_check_morphotag_positive01(self):\n self.assertTrue(self.__accentor.check_morphotag('a,b c,d,e'))\n self.assertTrue(self.__accentor.check_morphotag('12'))\n self.assertTrue(self.__accentor.check_morphotag('a,b c,d,e(2)'))\n self.assertFalse(self.__accentor.check_morphotag('a,b c,d,e()'))\n self.assertFalse(self.__accentor.check_morphotag('a,b(1) c,d,e(2)'))\n self.assertFalse(self.__accentor.check_morphotag('a,1,b c,d,e'))\n self.assertFalse(self.__accentor.check_morphotag('a,&,b c,d,e'))\n self.assertTrue(self.__accentor.check_morphotag('a|b c|d|e'))\n self.assertTrue(self.__accentor.check_morphotag('a|b c|d|e(2)'))\n self.assertFalse(self.__accentor.check_morphotag('a|b c|d|e()'))\n self.assertFalse(self.__accentor.check_morphotag('a|b(1) c|d|e(2)'))\n self.assertFalse(self.__accentor.check_morphotag('a|1|b c|d|e'))\n self.assertFalse(self.__accentor.check_morphotag('a|&|b c|d|e'))\n self.assertTrue(self.__accentor.check_morphotag('VERB Aspect=Perf|Mood=Ind|Number=Sing|Person=3|Tense=Fut|VerbForm=Fin'))\n", "method_code": " def check_morphotag(self, morphotag: str) -> bool:\n if len(morphotag.strip()) == 0:\n return False\n if morphotag.isdigit():\n return True\n ind1 = morphotag.find('(')\n ind2 = morphotag.find(')')\n if ind1 < 0 and ind2 < 0:\n ok = len(morphotag.strip()) > 0\n elif ind1 >= 0 and ind1 >= ind2:\n ok = False\n elif len(morphotag[:ind1].strip()) == 0:\n ok = False\n elif len(morphotag[ind1 + 1:ind2].strip()) == 0:\n ok = False\n elif not morphotag[ind1 + 1:ind2].strip().isdigit():\n ok = False\n else:\n ok = len(morphotag[ind2 + 1:].strip()) == 0\n if ok:\n if ind1 < 0:\n ind1 = len(morphotag)\n for cur_part in self.__re_for_morphosplit.split(morphotag[:ind1].strip()):\n if len(cur_part.strip()) == 0:\n ok = False\n break\n if cur_part.strip().isdigit():\n ok = False\n break\n search_res = self.__re_for_morphotag.search(cur_part.strip())\n if search_res is None:\n ok = False\n break\n if search_res.start() < 0 or search_res.end() < 0:\n ok = False\n break\n return ok\n ", "context": "class Accentor():\n def check_morphotag(self, morphotag: str) -> bool: ...\n def __init__(self, mode='one', debug='no', exception_for_unknown=False, use_wiki=True): ...\n def __del__(self): ...\n def get_correct_omograph_wiki(self, root_text, cur_word, morphotag='X'): ...\n def get_simple_form_wiki(self, root_text, form): ...\n def load_wiki_page(self, cur_form): ...\n def do_accents(self, source_phrase_and_morphotags: list) -> list: ...\n def check_source_wordform(self, checked: str) -> bool: ...\n def check_accented_wordform(self, checked: str) -> bool: ...\n def calculate_morpho_similarity(self, morphotags_1: str, morphotags_2: str) -> float: ...\n def prepare_morphotag(self, source_morphotag: str) -> str: ...\n def get_new_dics(self): ...\n def get_bad_words(self): ...\n def __generate_phrases_with_jo(self, old_phrase, new_phrase): ...\n def __do_accents(self, words_list: list, morphotags_list: list=None) -> list: ...\n\n self.logger = logging.getLogger()\n self.mode = mode\n self.__all_russian_letters = {'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'}\n self.__russian_vowels = {'а', 'о', 'у', 'э', 'ы', 'и', 'я', 'ё', 'ю', 'е'}\n self.exception_for_unknown = exception_for_unknown\n self.use_wiki = use_wiki\n self.__homonyms = None\n self.__simple_words_dawg = None\n self.__function_words = None\n self.__new_homonyms = {}\n self.__new_simple_words = set()\n self.__bad_words = []\n self.__re_for_morphosplit = re.compile('[\\\\,\\\\s\\\\|]+', re.U)\n self.__re_for_morphotag = re.compile('^(\\\\w+|\\\\w+[\\\\-\\\\=]\\\\w+)$', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_check_morphotag_positive01", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000289.py"} {"focal_file": "russian_g2p/Accentor.py", "focal_class": null, "focal_method": "prepare_morphotag", "tests": "import unittest\n\nclass Test_prepare_morphotag(unittest.TestCase):\n def test_prepare_morphotag_positive01(self):\n self.assertEqual('a,b c,d,e', self.__accentor.prepare_morphotag('a,b c,d,e(2)'))\n self.assertEqual('a,b c,d,e', self.__accentor.prepare_morphotag('a,b c,d,e'))\n self.assertNotEqual('a,b c,d,e', self.__accentor.prepare_morphotag('a,b c,d(2)'))\n self.assertNotEqual('a c,d,e', self.__accentor.prepare_morphotag('a,b c,d,e(2)'))\n", "method_code": " def prepare_morphotag(self, source_morphotag: str) -> str:\n ind1 = source_morphotag.find('(')\n ind2 = source_morphotag.find(')')\n if ind1 < 0:\n if ind2 >= 0:\n res = source_morphotag[:ind2].strip()\n else:\n res = source_morphotag.strip()\n elif ind2 >= 0:\n res = source_morphotag[:ind2 if ind2 < ind1 else ind1].strip()\n else:\n res = source_morphotag[:ind1].strip()\n return res\n ", "context": "class Accentor():\n def prepare_morphotag(self, source_morphotag: str) -> str: ...\n def __init__(self, mode='one', debug='no', exception_for_unknown=False, use_wiki=True): ...\n def __del__(self): ...\n def get_correct_omograph_wiki(self, root_text, cur_word, morphotag='X'): ...\n def get_simple_form_wiki(self, root_text, form): ...\n def load_wiki_page(self, cur_form): ...\n def do_accents(self, source_phrase_and_morphotags: list) -> list: ...\n def check_source_wordform(self, checked: str) -> bool: ...\n def check_accented_wordform(self, checked: str) -> bool: ...\n def check_morphotag(self, morphotag: str) -> bool: ...\n def calculate_morpho_similarity(self, morphotags_1: str, morphotags_2: str) -> float: ...\n def get_new_dics(self): ...\n def get_bad_words(self): ...\n def __generate_phrases_with_jo(self, old_phrase, new_phrase): ...\n def __do_accents(self, words_list: list, morphotags_list: list=None) -> list: ...\n\n self.logger = logging.getLogger()\n self.mode = mode\n self.__all_russian_letters = {'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'}\n self.__russian_vowels = {'а', 'о', 'у', 'э', 'ы', 'и', 'я', 'ё', 'ю', 'е'}\n self.exception_for_unknown = exception_for_unknown\n self.use_wiki = use_wiki\n self.__homonyms = None\n self.__simple_words_dawg = None\n self.__function_words = None\n self.__new_homonyms = {}\n self.__new_simple_words = set()\n self.__bad_words = []\n self.__re_for_morphosplit = re.compile('[\\\\,\\\\s\\\\|]+', re.U)\n self.__re_for_morphotag = re.compile('^(\\\\w+|\\\\w+[\\\\-\\\\=]\\\\w+)$', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_prepare_morphotag_positive01", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000290.py"} {"focal_file": "russian_g2p/Accentor.py", "focal_class": null, "focal_method": "calculate_morpho_similarity", "tests": "import unittest\n\nclass Test_calculate_morpho_similarity(unittest.TestCase):\n def test_calculate_morpho_similarity_positive01(self):\n self.assertAlmostEqual(self.__accentor.calculate_morpho_similarity('1', 'a,b'), 0.0, places=7)\n self.assertAlmostEqual(self.__accentor.calculate_morpho_similarity('a,b c,d,e', 'a,b c,d,e'), 1.0, places=7)\n self.assertAlmostEqual(self.__accentor.calculate_morpho_similarity('a,b c,d,e', 'f,g h,i,j'), 0.0, places=7)\n self.assertAlmostEqual(self.__accentor.calculate_morpho_similarity('a,b c,d,e', 'f,b h,d,j'), 0.25, places=7)\n self.assertAlmostEqual(self.__accentor.calculate_morpho_similarity('1', 'a|b'), 0.0, places=7)\n self.assertAlmostEqual(self.__accentor.calculate_morpho_similarity('a|b c|d|e', 'a|b c|d|e'), 1.0, places=7)\n self.assertAlmostEqual(self.__accentor.calculate_morpho_similarity('a|b c|d|e', 'f|g h|i|j'), 0.0, places=7)\n self.assertAlmostEqual(self.__accentor.calculate_morpho_similarity('a|b c|d|e', 'f|b h|d|j'), 0.25, places=7)\n", "method_code": " def calculate_morpho_similarity(self, morphotags_1: str, morphotags_2: str) -> float:\n if morphotags_1.isdigit() or morphotags_2.isdigit():\n return 0.0\n prepared_morpotags_1 = set(filter(lambda a: len(a) > 0, map(lambda b: b.strip(), self.__re_for_morphosplit.split(morphotags_1))))\n prepared_morpotags_2 = set(filter(lambda a: len(a) > 0, map(lambda b: b.strip(), self.__re_for_morphosplit.split(morphotags_2))))\n if len(prepared_morpotags_1) == 0 and len(prepared_morpotags_2) == 0:\n return 0.0\n return len(prepared_morpotags_1 & prepared_morpotags_2) / len(prepared_morpotags_1 | prepared_morpotags_2)\n ", "context": "class Accentor():\n def calculate_morpho_similarity(self, morphotags_1: str, morphotags_2: str) -> float: ...\n def __init__(self, mode='one', debug='no', exception_for_unknown=False, use_wiki=True): ...\n def __del__(self): ...\n def get_correct_omograph_wiki(self, root_text, cur_word, morphotag='X'): ...\n def get_simple_form_wiki(self, root_text, form): ...\n def load_wiki_page(self, cur_form): ...\n def do_accents(self, source_phrase_and_morphotags: list) -> list: ...\n def check_source_wordform(self, checked: str) -> bool: ...\n def check_accented_wordform(self, checked: str) -> bool: ...\n def check_morphotag(self, morphotag: str) -> bool: ...\n def prepare_morphotag(self, source_morphotag: str) -> str: ...\n def get_new_dics(self): ...\n def get_bad_words(self): ...\n def __generate_phrases_with_jo(self, old_phrase, new_phrase): ...\n def __do_accents(self, words_list: list, morphotags_list: list=None) -> list: ...\n\n self.logger = logging.getLogger()\n self.mode = mode\n self.__all_russian_letters = {'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'}\n self.__russian_vowels = {'а', 'о', 'у', 'э', 'ы', 'и', 'я', 'ё', 'ю', 'е'}\n self.exception_for_unknown = exception_for_unknown\n self.use_wiki = use_wiki\n self.__homonyms = None\n self.__simple_words_dawg = None\n self.__function_words = None\n self.__new_homonyms = {}\n self.__new_simple_words = set()\n self.__bad_words = []\n self.__re_for_morphosplit = re.compile('[\\\\,\\\\s\\\\|]+', re.U)\n self.__re_for_morphotag = re.compile('^(\\\\w+|\\\\w+[\\\\-\\\\=]\\\\w+)$', re.U)\n", "repository": "nsu-ai/russian_g2p", "test_name": "test_calculate_morpho_similarity_positive01", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000291.py"} {"focal_file": "colemak/keyboard.py", "focal_class": null, "focal_method": "distance", "tests": "import unittest\n\nclass Test_distance(unittest.TestCase):\n def test_zero_distance(self):\n self.assertEqual(distance('arstneio', self.movements), 0)\n self.assertEqual(distance('aasstrstneo', self.movements), 0)\n self.assertEqual(distance('', self.movements), 0)\n\n def test_regular_distance(self):\n self.assertEqual(distance('word', self.movements), 2)\n self.assertEqual(distance('qwerty', self.movements), 3)\n\n def test_corner_distance(self):\n self.assertEqual(distance('great', self.movements), 2)\n self.assertEqual(distance('kbdhgj', self.movements), 10)\n\n def test_same_letter_distance(self):\n self.assertEqual(distance('qq', self.movements), 1)\n self.assertEqual(distance('apps', self.movements), 1)\n self.assertEqual(distance('fppffwfww', self.movements), 6)\n self.assertEqual(distance('kkbbddhhggjj', self.movements), 10)\n", "method_code": "def distance(word, movements):\n \"\"\"\n This method takes a word and movement mapping (see get_movements())\n as input and returns the 'cost' of moving your fingers in order to type\n the word\n \"\"\"\n dist = 0\n prev_letter = None\n for letter in word:\n letter = letter.upper()\n if prev_letter is None or not prev_letter == letter:\n try:\n dist += movements[letter]\n except KeyError:\n continue\n prev_letter = letter\n return dist", "context": "def distance(word, movements): ...\ndef get_movements(keyboard): ...\ndef distance(word, movements): ...\ndef distances(words, movements): ...\ndef dic_to_words(filename): ...\ndef calculate_avg_moving(words, keyboard): ...\ndef show_movings(words): ...\ndef main(): ...\n", "repository": "RensOliemans/randomshit", "test_name": "test_zero_distance", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000292.py"} {"focal_file": "colemak/keyboard.py", "focal_class": null, "focal_method": "distances", "tests": "import unittest\n\nclass Test_distances(unittest.TestCase):\n def test_general_distances(self):\n expected = {'great': 2}\n self.assertEqual(distances(['great'], self.movements), expected)\n expected = {'kbdhgj': 10, 'great': 2}\n self.assertEqual(distances(['kbdhgj', 'great'], self.movements), expected)\n", "method_code": "def distances(words, movements):\n \"\"\"\n This method takes a list of words as input and a movement mapping\n (see get_movements()) and returns a dictionary distances, with key, value:\n\n { word: movement_cost }\n \"\"\"\n dists = {word: distance(word, movements) for word in words}\n return dists", "context": "def distances(words, movements): ...\ndef get_movements(keyboard): ...\ndef distance(word, movements): ...\ndef distances(words, movements): ...\ndef dic_to_words(filename): ...\ndef calculate_avg_moving(words, keyboard): ...\ndef show_movings(words): ...\ndef main(): ...\n", "repository": "RensOliemans/randomshit", "test_name": "test_general_distances", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000293.py"} {"focal_file": "zenmap/zenmapCore/NmapOptions.py", "focal_class": null, "focal_method": "clear", "tests": "import unittest\n\nclass Test_clear(unittest.TestCase):\n def test_clear(self):\n \"\"\"Test that a new object starts without defining any options, that the\n clear method removes all options, and that parsing the empty string or\n an empty list removes all options.\"\"\"\n TEST = 'nmap -T4 -A -v localhost --webxml'\n ops = NmapOptions()\n self.assertTrue(len(ops.render()) == 1)\n ops.parse_string(TEST)\n self.assertFalse(len(ops.render()) == 1)\n ops.clear()\n self.assertTrue(len(ops.render()) == 1)\n ops.parse_string(TEST)\n ops.parse_string('')\n self.assertEqual(ops.render_string(), 'nmap')\n ops.parse_string(TEST)\n ops.parse([])\n self.assertEqual(ops.render_string(), 'nmap')\n\n def test_clear(self):\n \"\"\"Test that a new object starts without defining any options, that the\n clear method removes all options, and that parsing the empty string or\n an empty list removes all options.\"\"\"\n TEST = 'nmap -T4 -A -v localhost --webxml'\n ops = NmapOptions()\n self.assertTrue(len(ops.render()) == 1)\n ops.parse_string(TEST)\n self.assertFalse(len(ops.render()) == 1)\n ops.clear()\n self.assertTrue(len(ops.render()) == 1)\n ops.parse_string(TEST)\n ops.parse_string('')\n self.assertEqual(ops.render_string(), 'nmap')\n ops.parse_string(TEST)\n ops.parse([])\n self.assertEqual(ops.render_string(), 'nmap')\n", "method_code": " def clear(self):\n self._executable = None\n self.target_specs = []\n self.extras = []\n self.d = {}\n ", "context": "class NmapOptions(object):\n def clear(self): ...\n def __init__(self): ...\n def _set_executable(self, executable): ...\n def canonicalize_name(self, name): ...\n def __getitem__(self, key): ...\n def __setitem__(self, key, value): ...\n def setdefault(self, key, default): ...\n def handle_result(self, result): ...\n def parse(self, opt_list): ...\n def parse_string(self, opt_string): ...\n def render(self): ...\n def render_string(self): ...\n\n self.options = make_options(self.SHORT_OPTIONS, self.LONG_OPTIONS)\n\n SHORT_OPTIONS = '6Ab:D:d::e:Ffg:hi:M:m:nO::o:P:p:RrS:s:T:v::V'\n LONG_OPTIONS = (('allports', option.NO_ARGUMENT), ('append-output', option.NO_ARGUMENT), ('badsum', option.NO_ARGUMENT), ('data-length', option.REQUIRED_ARGUMENT), ('datadir', option.REQUIRED_ARGUMENT), ('debug', option.OPTIONAL_ARGUMENT), ('defeat-rst-ratelimit', option.NO_ARGUMENT), ('dns-servers', option.REQUIRED_ARGUMENT), ('exclude', option.REQUIRED_ARGUMENT), ('excludefile', option.REQUIRED_ARGUMENT), ('fuzzy', option.NO_ARGUMENT), ('help', option.NO_ARGUMENT), ('host-timeout', option.REQUIRED_ARGUMENT), ('iL', option.REQUIRED_ARGUMENT), ('iR', option.REQUIRED_ARGUMENT), ('iflist', option.NO_ARGUMENT), ('initial-rtt-timeout', option.REQUIRED_ARGUMENT), ('ip-options', option.REQUIRED_ARGUMENT), ('log-errors', option.NO_ARGUMENT), ('max-hostgroup', option.REQUIRED_ARGUMENT), ('max-os-tries', option.REQUIRED_ARGUMENT), ('max-parallelism', option.REQUIRED_ARGUMENT), ('max-rate', option.REQUIRED_ARGUMENT), ('max-retries', option.REQUIRED_ARGUMENT), ('max-rtt-timeout', option.REQUIRED_ARGUMENT), ('max-scan-delay', option.REQUIRED_ARGUMENT), ('min-hostgroup', option.REQUIRED_ARGUMENT), ('min-parallelism', option.REQUIRED_ARGUMENT), ('min-rate', option.REQUIRED_ARGUMENT), ('min-retries', option.REQUIRED_ARGUMENT), ('min-rtt-timeout', option.REQUIRED_ARGUMENT), ('mtu', option.REQUIRED_ARGUMENT), ('no-stylesheet', option.NO_ARGUMENT), ('oA', option.REQUIRED_ARGUMENT), ('oG', option.REQUIRED_ARGUMENT), ('oM', option.REQUIRED_ARGUMENT), ('oN', option.REQUIRED_ARGUMENT), ('oS', option.REQUIRED_ARGUMENT), ('oX', option.REQUIRED_ARGUMENT), ('open', option.NO_ARGUMENT), ('osscan-guess', option.NO_ARGUMENT), ('osscan-limit', option.NO_ARGUMENT), ('packet-trace', option.NO_ARGUMENT), ('port-ratio', option.REQUIRED_ARGUMENT), ('privileged', option.NO_ARGUMENT), ('randomize-hosts', option.NO_ARGUMENT), ('reason', option.NO_ARGUMENT), ('release-memory', option.NO_ARGUMENT), ('scan-delay', option.REQUIRED_ARGUMENT), ('scanflags', option.REQUIRED_ARGUMENT), ('sI', option.REQUIRED_ARGUMENT), ('script', option.REQUIRED_ARGUMENT), ('script-args', option.REQUIRED_ARGUMENT), ('script-trace', option.NO_ARGUMENT), ('script-updatedb', option.NO_ARGUMENT), ('script-help', option.REQUIRED_ARGUMENT), ('send-eth', option.NO_ARGUMENT), ('send-ip', option.NO_ARGUMENT), ('servicedb', option.REQUIRED_ARGUMENT), ('source-port', option.REQUIRED_ARGUMENT), ('spoof-mac', option.REQUIRED_ARGUMENT), ('stylesheet', option.REQUIRED_ARGUMENT), ('system-dns', option.NO_ARGUMENT), ('timing', option.REQUIRED_ARGUMENT), ('top-ports', option.REQUIRED_ARGUMENT), ('traceroute', option.NO_ARGUMENT), ('ttl', option.REQUIRED_ARGUMENT), ('unprivileged', option.NO_ARGUMENT), ('verbose', option.OPTIONAL_ARGUMENT), ('version', option.NO_ARGUMENT), ('version-all', option.NO_ARGUMENT), ('version-intensity', option.REQUIRED_ARGUMENT), ('version-light', option.NO_ARGUMENT), ('version-trace', option.NO_ARGUMENT), ('versiondb', option.REQUIRED_ARGUMENT), ('webxml', option.NO_ARGUMENT))\n EQUIVALENT_OPTIONS = (('debug', 'd'), ('help', 'h'), ('iL', 'i'), ('max-parallelism', 'M'), ('osscan-guess', 'fuzzy'), ('oG', 'oM', 'm'), ('oN', 'o'), ('sP', 'sn'), ('P', 'PE', 'PI'), ('PA', 'PT'), ('P0', 'PD', 'PN', 'Pn'), ('rH', 'randomize-hosts'), ('source-port', 'g'), ('timing', 'T'), ('verbose', 'v'), ('version', 'V'))\n EQUIVALENCE_MAP = {}\n TIMING_PROFILE_NAMES = {'paranoid': 0, 'sneaky': 1, 'polite': 2, 'normal': 3, 'aggressive': 4, 'insane': 5}\n executable = property(lambda self: self._executable or 'nmap', _set_executable)\n", "repository": "robison/nmap", "test_name": "test_clear", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000294.py"} {"focal_file": "zenmap/zenmapCore/NmapOptions.py", "focal_class": null, "focal_method": "render", "tests": "import unittest\n\nclass Test_render(unittest.TestCase):\n def test_render(self):\n \"\"\"Test that the render method returns a list.\"\"\"\n TEST = 'nmap -T4 -A -v localhost --webxml'\n ops = NmapOptions()\n ops.parse_string(TEST)\n self.assertTrue(type(ops.render()) == list, 'type == %s' % type(ops.render))\n\n def test_render(self):\n \"\"\"Test that the render method returns a list.\"\"\"\n TEST = 'nmap -T4 -A -v localhost --webxml'\n ops = NmapOptions()\n ops.parse_string(TEST)\n self.assertTrue(type(ops.render()) == list, 'type == %s' % type(ops.render))\n", "method_code": " def render(self):\n opt_list = []\n for opt in ('-sA', '-sC', '-sF', '-sL', '-sM', '-sN', '-sO', '-sn', '-sR', '-sS', '-sT', '-sU', '-sV', '-sW', '-sX', '-sY', '-sZ'):\n if self[opt]:\n opt_list.append(opt)\n if self['-sI'] is not None:\n opt_list.extend(('-sI', self['-sI']))\n for opt in ('-6',):\n if self[opt]:\n opt_list.append(opt)\n if self['-p'] is not None:\n opt_list.extend(('-p', self['-p']))\n if self['-T'] is not None:\n opt_list.append('-T%s' % str(self['-T']))\n if self['-O'] is not None:\n if isinstance(self['-O'], basestring):\n opt_list.append('-O%s' % self['-O'])\n elif self['-O']:\n opt_list.append('-O')\n if self['-A']:\n opt_list.append('-A')\n if self['-d']:\n if self['-d'] == 1:\n opt_list.append('-d')\n elif self['-d'] > 1:\n opt_list.append('-d%s' % self['-d'])\n if self['-f']:\n opt_list.extend(['-f'] * self['-f'])\n if self['-v']:\n opt_list.extend(['-v'] * self['-v'])\n if self['-F']:\n opt_list.append('-F')\n if self['-n']:\n opt_list.append('-n')\n if self['-iL'] is not None:\n opt_list.extend(('-iL', self['-iL']))\n if self['-iR'] is not None:\n opt_list.extend(('-iR', str(self['-iR'])))\n for opt in ('-oA', '-oG', '-oN', '-oS', '-oX'):\n if self[opt] is not None:\n opt_list.extend((opt, self[opt]))\n for opt in ('--min-hostgroup', '--max-hostgroup', '--min-parallelism', '--max-parallelism', '--min-rtt-timeout', '--max-rtt-timeout', '--initial-rtt-timeout', '--scan-delay', '--max-scan-delay', '--min-rate', '--max-rate', '--max-retries', '--max-os-tries', '--host-timeout'):\n if self[opt] is not None:\n opt_list.extend((opt, self[opt]))\n for ping_option in ('-Pn', '-PE', '-PM', '-PP', '-PR'):\n if self[ping_option]:\n opt_list.append(ping_option)\n for ping_option in ('-PS', '-PA', '-PU', '-PO', '-PY'):\n if self[ping_option] is not None:\n opt_list.append(ping_option + self[ping_option])\n if self['-PB'] is not None:\n if isinstance(self['-PB'], basestring):\n opt_list.append('-PB' + self['-PB'])\n elif self['-PB']:\n opt_list.append('-PB')\n for opt in ('--allports', '--append-output', '--badsum', '--defeat-rst-ratelimit', '--fuzzy', '--help', '--iflist', '--log-errors', '--no-stylesheet', '--open', '--osscan-guess', '--osscan-limit', '--packet-trace', '--privileged', '-r', '-R', '--randomize-hosts', '--reason', '--release-memory', '--script-trace', '--script-updatedb', '--send-eth', '--send-ip', '--system-dns', '--traceroute', '--unprivileged', '--version', '--version-all', '--version-light', '--version-trace', '--webxml'):\n if self[opt]:\n opt_list.append(opt)\n for opt in ('-b', '-D', '--datadir', '--data-length', '--dns-servers', '-e', '--exclude', '--excludefile', '-g', '--ip-options', '--mtu', '--port-ratio', '-S', '--scanflags', '--script', '--script-args', '--script-help', '--servicedb', '--spoof-mac', '--stylesheet', '--top-ports', '--ttl', '--versiondb', '--version-intensity'):\n if self[opt] is not None:\n opt_list.extend((opt, self[opt]))\n opt_list.extend(self.target_specs)\n opt_list.extend(self.extras)\n return [self.executable] + opt_list\n ", "context": "class NmapOptions(object):\n def render(self): ...\n def __init__(self): ...\n def clear(self): ...\n def _set_executable(self, executable): ...\n def canonicalize_name(self, name): ...\n def __getitem__(self, key): ...\n def __setitem__(self, key, value): ...\n def setdefault(self, key, default): ...\n def handle_result(self, result): ...\n def parse(self, opt_list): ...\n def parse_string(self, opt_string): ...\n def render_string(self): ...\n\n self.options = make_options(self.SHORT_OPTIONS, self.LONG_OPTIONS)\n\n SHORT_OPTIONS = '6Ab:D:d::e:Ffg:hi:M:m:nO::o:P:p:RrS:s:T:v::V'\n LONG_OPTIONS = (('allports', option.NO_ARGUMENT), ('append-output', option.NO_ARGUMENT), ('badsum', option.NO_ARGUMENT), ('data-length', option.REQUIRED_ARGUMENT), ('datadir', option.REQUIRED_ARGUMENT), ('debug', option.OPTIONAL_ARGUMENT), ('defeat-rst-ratelimit', option.NO_ARGUMENT), ('dns-servers', option.REQUIRED_ARGUMENT), ('exclude', option.REQUIRED_ARGUMENT), ('excludefile', option.REQUIRED_ARGUMENT), ('fuzzy', option.NO_ARGUMENT), ('help', option.NO_ARGUMENT), ('host-timeout', option.REQUIRED_ARGUMENT), ('iL', option.REQUIRED_ARGUMENT), ('iR', option.REQUIRED_ARGUMENT), ('iflist', option.NO_ARGUMENT), ('initial-rtt-timeout', option.REQUIRED_ARGUMENT), ('ip-options', option.REQUIRED_ARGUMENT), ('log-errors', option.NO_ARGUMENT), ('max-hostgroup', option.REQUIRED_ARGUMENT), ('max-os-tries', option.REQUIRED_ARGUMENT), ('max-parallelism', option.REQUIRED_ARGUMENT), ('max-rate', option.REQUIRED_ARGUMENT), ('max-retries', option.REQUIRED_ARGUMENT), ('max-rtt-timeout', option.REQUIRED_ARGUMENT), ('max-scan-delay', option.REQUIRED_ARGUMENT), ('min-hostgroup', option.REQUIRED_ARGUMENT), ('min-parallelism', option.REQUIRED_ARGUMENT), ('min-rate', option.REQUIRED_ARGUMENT), ('min-retries', option.REQUIRED_ARGUMENT), ('min-rtt-timeout', option.REQUIRED_ARGUMENT), ('mtu', option.REQUIRED_ARGUMENT), ('no-stylesheet', option.NO_ARGUMENT), ('oA', option.REQUIRED_ARGUMENT), ('oG', option.REQUIRED_ARGUMENT), ('oM', option.REQUIRED_ARGUMENT), ('oN', option.REQUIRED_ARGUMENT), ('oS', option.REQUIRED_ARGUMENT), ('oX', option.REQUIRED_ARGUMENT), ('open', option.NO_ARGUMENT), ('osscan-guess', option.NO_ARGUMENT), ('osscan-limit', option.NO_ARGUMENT), ('packet-trace', option.NO_ARGUMENT), ('port-ratio', option.REQUIRED_ARGUMENT), ('privileged', option.NO_ARGUMENT), ('randomize-hosts', option.NO_ARGUMENT), ('reason', option.NO_ARGUMENT), ('release-memory', option.NO_ARGUMENT), ('scan-delay', option.REQUIRED_ARGUMENT), ('scanflags', option.REQUIRED_ARGUMENT), ('sI', option.REQUIRED_ARGUMENT), ('script', option.REQUIRED_ARGUMENT), ('script-args', option.REQUIRED_ARGUMENT), ('script-trace', option.NO_ARGUMENT), ('script-updatedb', option.NO_ARGUMENT), ('script-help', option.REQUIRED_ARGUMENT), ('send-eth', option.NO_ARGUMENT), ('send-ip', option.NO_ARGUMENT), ('servicedb', option.REQUIRED_ARGUMENT), ('source-port', option.REQUIRED_ARGUMENT), ('spoof-mac', option.REQUIRED_ARGUMENT), ('stylesheet', option.REQUIRED_ARGUMENT), ('system-dns', option.NO_ARGUMENT), ('timing', option.REQUIRED_ARGUMENT), ('top-ports', option.REQUIRED_ARGUMENT), ('traceroute', option.NO_ARGUMENT), ('ttl', option.REQUIRED_ARGUMENT), ('unprivileged', option.NO_ARGUMENT), ('verbose', option.OPTIONAL_ARGUMENT), ('version', option.NO_ARGUMENT), ('version-all', option.NO_ARGUMENT), ('version-intensity', option.REQUIRED_ARGUMENT), ('version-light', option.NO_ARGUMENT), ('version-trace', option.NO_ARGUMENT), ('versiondb', option.REQUIRED_ARGUMENT), ('webxml', option.NO_ARGUMENT))\n EQUIVALENT_OPTIONS = (('debug', 'd'), ('help', 'h'), ('iL', 'i'), ('max-parallelism', 'M'), ('osscan-guess', 'fuzzy'), ('oG', 'oM', 'm'), ('oN', 'o'), ('sP', 'sn'), ('P', 'PE', 'PI'), ('PA', 'PT'), ('P0', 'PD', 'PN', 'Pn'), ('rH', 'randomize-hosts'), ('source-port', 'g'), ('timing', 'T'), ('verbose', 'v'), ('version', 'V'))\n EQUIVALENCE_MAP = {}\n TIMING_PROFILE_NAMES = {'paranoid': 0, 'sneaky': 1, 'polite': 2, 'normal': 3, 'aggressive': 4, 'insane': 5}\n executable = property(lambda self: self._executable or 'nmap', _set_executable)\n", "repository": "robison/nmap", "test_name": "test_render", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000295.py"} {"focal_file": "zenmap/zenmapCore/NmapOptions.py", "focal_class": null, "focal_method": "render_string", "tests": "import unittest\n\nclass Test_render_string(unittest.TestCase):\n def test_render_quoted(self):\n \"\"\"Test that strings that need to be quoted are quoted.\"\"\"\n ops = NmapOptions()\n ops.parse_string('\"/path/ /nmap\" --script \"test one two three\"')\n self.assertEqual(ops.executable, '/path/ /nmap')\n self.assertEqual(ops['--script'], 'test one two three')\n self.assertEqual(ops.target_specs, [])\n s = ops.render_string()\n ops.parse_string(s)\n self.assertEqual(ops.executable, '/path/ /nmap')\n self.assertEqual(ops['--script'], 'test one two three')\n self.assertEqual(ops.target_specs, [])\n\n def test_render_quoted(self):\n \"\"\"Test that strings that need to be quoted are quoted.\"\"\"\n ops = NmapOptions()\n ops.parse_string('\"/path/ /nmap\" --script \"test one two three\"')\n self.assertEqual(ops.executable, '/path/ /nmap')\n self.assertEqual(ops['--script'], 'test one two three')\n self.assertEqual(ops.target_specs, [])\n s = ops.render_string()\n ops.parse_string(s)\n self.assertEqual(ops.executable, '/path/ /nmap')\n self.assertEqual(ops['--script'], 'test one two three')\n self.assertEqual(ops.target_specs, [])\n", "method_code": " def render_string(self):\n return join_quoted(self.render())\n ", "context": "class NmapOptions(object):\n def render_string(self): ...\n def __init__(self): ...\n def clear(self): ...\n def _set_executable(self, executable): ...\n def canonicalize_name(self, name): ...\n def __getitem__(self, key): ...\n def __setitem__(self, key, value): ...\n def setdefault(self, key, default): ...\n def handle_result(self, result): ...\n def parse(self, opt_list): ...\n def parse_string(self, opt_string): ...\n def render(self): ...\n\n self.options = make_options(self.SHORT_OPTIONS, self.LONG_OPTIONS)\n\n SHORT_OPTIONS = '6Ab:D:d::e:Ffg:hi:M:m:nO::o:P:p:RrS:s:T:v::V'\n LONG_OPTIONS = (('allports', option.NO_ARGUMENT), ('append-output', option.NO_ARGUMENT), ('badsum', option.NO_ARGUMENT), ('data-length', option.REQUIRED_ARGUMENT), ('datadir', option.REQUIRED_ARGUMENT), ('debug', option.OPTIONAL_ARGUMENT), ('defeat-rst-ratelimit', option.NO_ARGUMENT), ('dns-servers', option.REQUIRED_ARGUMENT), ('exclude', option.REQUIRED_ARGUMENT), ('excludefile', option.REQUIRED_ARGUMENT), ('fuzzy', option.NO_ARGUMENT), ('help', option.NO_ARGUMENT), ('host-timeout', option.REQUIRED_ARGUMENT), ('iL', option.REQUIRED_ARGUMENT), ('iR', option.REQUIRED_ARGUMENT), ('iflist', option.NO_ARGUMENT), ('initial-rtt-timeout', option.REQUIRED_ARGUMENT), ('ip-options', option.REQUIRED_ARGUMENT), ('log-errors', option.NO_ARGUMENT), ('max-hostgroup', option.REQUIRED_ARGUMENT), ('max-os-tries', option.REQUIRED_ARGUMENT), ('max-parallelism', option.REQUIRED_ARGUMENT), ('max-rate', option.REQUIRED_ARGUMENT), ('max-retries', option.REQUIRED_ARGUMENT), ('max-rtt-timeout', option.REQUIRED_ARGUMENT), ('max-scan-delay', option.REQUIRED_ARGUMENT), ('min-hostgroup', option.REQUIRED_ARGUMENT), ('min-parallelism', option.REQUIRED_ARGUMENT), ('min-rate', option.REQUIRED_ARGUMENT), ('min-retries', option.REQUIRED_ARGUMENT), ('min-rtt-timeout', option.REQUIRED_ARGUMENT), ('mtu', option.REQUIRED_ARGUMENT), ('no-stylesheet', option.NO_ARGUMENT), ('oA', option.REQUIRED_ARGUMENT), ('oG', option.REQUIRED_ARGUMENT), ('oM', option.REQUIRED_ARGUMENT), ('oN', option.REQUIRED_ARGUMENT), ('oS', option.REQUIRED_ARGUMENT), ('oX', option.REQUIRED_ARGUMENT), ('open', option.NO_ARGUMENT), ('osscan-guess', option.NO_ARGUMENT), ('osscan-limit', option.NO_ARGUMENT), ('packet-trace', option.NO_ARGUMENT), ('port-ratio', option.REQUIRED_ARGUMENT), ('privileged', option.NO_ARGUMENT), ('randomize-hosts', option.NO_ARGUMENT), ('reason', option.NO_ARGUMENT), ('release-memory', option.NO_ARGUMENT), ('scan-delay', option.REQUIRED_ARGUMENT), ('scanflags', option.REQUIRED_ARGUMENT), ('sI', option.REQUIRED_ARGUMENT), ('script', option.REQUIRED_ARGUMENT), ('script-args', option.REQUIRED_ARGUMENT), ('script-trace', option.NO_ARGUMENT), ('script-updatedb', option.NO_ARGUMENT), ('script-help', option.REQUIRED_ARGUMENT), ('send-eth', option.NO_ARGUMENT), ('send-ip', option.NO_ARGUMENT), ('servicedb', option.REQUIRED_ARGUMENT), ('source-port', option.REQUIRED_ARGUMENT), ('spoof-mac', option.REQUIRED_ARGUMENT), ('stylesheet', option.REQUIRED_ARGUMENT), ('system-dns', option.NO_ARGUMENT), ('timing', option.REQUIRED_ARGUMENT), ('top-ports', option.REQUIRED_ARGUMENT), ('traceroute', option.NO_ARGUMENT), ('ttl', option.REQUIRED_ARGUMENT), ('unprivileged', option.NO_ARGUMENT), ('verbose', option.OPTIONAL_ARGUMENT), ('version', option.NO_ARGUMENT), ('version-all', option.NO_ARGUMENT), ('version-intensity', option.REQUIRED_ARGUMENT), ('version-light', option.NO_ARGUMENT), ('version-trace', option.NO_ARGUMENT), ('versiondb', option.REQUIRED_ARGUMENT), ('webxml', option.NO_ARGUMENT))\n EQUIVALENT_OPTIONS = (('debug', 'd'), ('help', 'h'), ('iL', 'i'), ('max-parallelism', 'M'), ('osscan-guess', 'fuzzy'), ('oG', 'oM', 'm'), ('oN', 'o'), ('sP', 'sn'), ('P', 'PE', 'PI'), ('PA', 'PT'), ('P0', 'PD', 'PN', 'Pn'), ('rH', 'randomize-hosts'), ('source-port', 'g'), ('timing', 'T'), ('verbose', 'v'), ('version', 'V'))\n EQUIVALENCE_MAP = {}\n TIMING_PROFILE_NAMES = {'paranoid': 0, 'sneaky': 1, 'polite': 2, 'normal': 3, 'aggressive': 4, 'insane': 5}\n executable = property(lambda self: self._executable or 'nmap', _set_executable)\n", "repository": "robison/nmap", "test_name": "test_render_quoted", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000296.py"} {"focal_file": "zenmap/zenmapCore/NmapOptions.py", "focal_class": null, "focal_method": "split_quoted", "tests": "import unittest\n\nclass Test_split_quoted(unittest.TestCase):\n def test_quotes(self):\n self.assertEqual(split_quoted('a \"b\" c'), ['a', 'b', 'c'])\n self.assertEqual(split_quoted('a \"b c\"'), ['a', 'b c'])\n self.assertEqual(split_quoted('a \"b c\"\"d e\"'), ['a', 'b cd e'])\n self.assertEqual(split_quoted('a \"b c\"z\"d e\"'), ['a', 'b czd e'])\n\n def test_quotes(self):\n self.assertEqual(split_quoted('a \"b\" c'), ['a', 'b', 'c'])\n self.assertEqual(split_quoted('a \"b c\"'), ['a', 'b c'])\n self.assertEqual(split_quoted('a \"b c\"\"d e\"'), ['a', 'b cd e'])\n self.assertEqual(split_quoted('a \"b c\"z\"d e\"'), ['a', 'b czd e'])\n", "method_code": "def split_quoted(s):\n \"\"\"Like str.split, except that no splits occur inside quoted strings, and\n quoted strings are unquoted.\"\"\"\n r = []\n i = 0\n while i < len(s) and s[i].isspace():\n i += 1\n while i < len(s):\n part = []\n while i < len(s) and (not s[i].isspace()):\n c = s[i]\n if c == '\"' or c == \"'\":\n begin = c\n i += 1\n while i < len(s):\n c = s[i]\n if c == begin:\n i += 1\n break\n elif c == '\\\\':\n i += 1\n if i < len(s):\n c = s[i]\n part.append(c)\n i += 1\n else:\n part.append(c)\n i += 1\n r.append(''.join(part))\n while i < len(s) and s[i].isspace():\n i += 1\n return r", "context": "def split_quoted(s): ...\ndef split_quoted(s): ...\ndef maybe_quote(s): ...\ndef join_quoted(l): ...\ndef make_options(short_opts, long_opts): ...\ndef lookup_option(name, options): ...\ndef split_option(cmd_arg, options): ...\ndef get_option(cmd_args, options): ...\ndef sync(a, b, options): ...\ndef getopt_long_only_extras(cmd_args, short_opts, long_opts): ...\n", "repository": "robison/nmap", "test_name": "test_quotes", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000297.py"} {"focal_file": "python-crash-course-2nd-end/chapter11/name_function.py", "focal_class": null, "focal_method": "get_formatted_name", "tests": "import unittest\n\nclass Test_get_formatted_name(unittest.TestCase):\n def test_first_last_middle_name(self):\n \"\"\"\n Do names like 'Wolfgang Amadeus Mozar' work?\n \"\"\"\n formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')\n self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')\n", "method_code": "def get_formatted_name(first, last, middle=''):\n \"\"\"\n Generate a neatly formatted full name.\n \"\"\"\n if middle:\n full_name = f'{first} {middle} {last}'\n else:\n full_name = f'{first} {last}'\n return full_name.title()", "context": "def get_formatted_name(first, last, middle=''): ...\ndef get_formatted_name(first, last, middle=''): ...\n", "repository": "jerrison/learn-python", "test_name": "test_first_last_middle_name", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000298.py"} {"focal_file": "python-crash-course-2nd-end/chapter11/survey.py", "focal_class": null, "focal_method": "store_response", "tests": "import unittest\n\nclass Test_store_response(unittest.TestCase):\n def test_store_three_responses(self):\n \"\"\"\n Test that three individual responses are stored properly.\n \"\"\"\n for response in self.responses:\n self.my_survey.store_response(response)\n for response in self.responses:\n self.assertIn(response, self.my_survey.responses)\n", "method_code": " def store_response(self, new_response):\n \"\"\"\n Store a single response to the survey\n \"\"\"\n self.responses.append(new_response)\n ", "context": "class AnonymousSurvey(object):\n def store_response(self, new_response): ...\n def __init__(self, question): ...\n def show_question(self): ...\n def show_results(self): ...\n\n self.question = question\n self.responses = []\n", "repository": "jerrison/learn-python", "test_name": "test_store_three_responses", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000299.py"} {"focal_file": "maat/validations.py", "focal_class": null, "focal_method": "str_validation", "tests": "import unittest\n\nclass Test_str_validation(unittest.TestCase):\n def test_validation(self):\n \"\"\"Happy path test\"\"\"\n expected = Foo()\n result = str_validation(val=expected)\n self.assertEqual(result, expected)\n\n def test_validation_with_cast(self):\n with self.assertRaisesRegex(Invalid, 'key: \"None\" contains invalid item \"Foo\": unable to convert from type to str'):\n str_validation(val=Foo(), cast=True)\n", "method_code": "def str_validation(val, key=None, min_length=None, max_length=None, regex=None, choices=None, cast=None, *args, **kwargs):\n if cast:\n try:\n val = str(val)\n except (ValueError, TypeError):\n raise Invalid(f'key: \"{key}\" contains invalid item \"{type(val).__name__}\": unable to convert from type to str')\n if not isinstance(val, str):\n raise Invalid(f'key: \"{key}\" contains invalid item \"{val}\" with type \"{type(val).__name__}\": not of type string')\n if min_length is not None and len(val) < min_length:\n raise Invalid(f'key: \"{key}\" contains invalid item \"{val}\": less then minimal length of {min_length}')\n if max_length is not None and len(val) > max_length:\n raise Invalid(f'key: \"{key}\" contains invalid item \"{val}\": more then maximal length of {max_length}')\n if regex is not None and (not bool(re.match(regex, val))):\n raise Invalid(f'key: \"{key}\" contains invalid item \"{val}\": does not adhere to regex rules {regex}')\n if choices is not None and val not in choices:\n raise Invalid(f'key: \"{key}\" contains invalid item \"{val}\": not in valid choices {choices}')\n return val", "context": "def str_validation(val, key=None, min_length=None, max_length=None, regex=None, choices=None, cast=None, *args, **kwargs): ...\ndef str_validation(val, key=None, min_length=None, max_length=None, regex=None, choices=None, cast=None, *args, **kwargs): ...\ndef int_validation(val, key=None, min_amount=None, max_amount=None, cast=None, *args, **kwargs): ...\ndef float_validation(val, key=None, min_amount=None, max_amount=None, cast=None, *args, **kwargs): ...\ndef list_validation(val, key=None, min_amount=None, max_amount=None, *args, **kwargs): ...\ndef dict_validation(val, key=None, min_amount=None, max_amount=None, key_min=None, key_max=None, key_regex=None, *args, **kwargs): ...\ndef uuid_validation(val, key=None, *args, **kwargs): ...\n", "repository": "Attumm/Maat", "test_name": "test_validation", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000300.py"} {"focal_file": "simplejson/simplejson/tests/test_encode_basestring_ascii.py", "focal_class": null, "focal_method": "_test_encode_basestring_ascii", "tests": "import unittest\n\nclass Test_test_encode_basestring_ascii(unittest.TestCase):\n def test_py_encode_basestring_ascii(self):\n self._test_encode_basestring_ascii(simplejson.encoder.py_encode_basestring_ascii)\n\n def test_c_encode_basestring_ascii(self):\n if not simplejson.encoder.c_encode_basestring_ascii:\n return\n self._test_encode_basestring_ascii(simplejson.encoder.c_encode_basestring_ascii)\n", "method_code": " def _test_encode_basestring_ascii(self, encode_basestring_ascii):\n fname = encode_basestring_ascii.__name__\n for input_string, expect in CASES:\n result = encode_basestring_ascii(input_string)\n self.assertEquals(result, expect, '%r != %r for %s(%r)' % (result, expect, fname, input_string))\n ", "context": "class TestEncodeBaseStringAscii(TestCase):\n def _test_encode_basestring_ascii(self, encode_basestring_ascii): ...\n def test_py_encode_basestring_ascii(self): ...\n def test_c_encode_basestring_ascii(self): ...\n", "repository": "jverkoey/12tweet", "test_name": "test_py_encode_basestring_ascii", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000301.py"} {"focal_file": "lint4jsondb.py", "focal_class": null, "focal_method": "matches", "tests": "import unittest\n\nclass Test_matches(unittest.TestCase):\n def test_04_ensure_BaseVisitor_never_matches(self):\n b = BaseVisitor()\n with self.assertRaises(NotImplementedError) as cm:\n b.matches('')\n self.assertIn('BaseVisitor can not match', str(cm.exception))\n", "method_code": " def matches(self, command):\n raise NotImplementedError('BaseVisitor can not match')\n ", "context": "class BaseVisitor():\n def matches(self, command): ...\n def __init__(self): ...\n def start_invocation(self): ...\n def end_invocation(self): ...\n def derive_invocation_from(self, param): ...\n\n self._invocation = None\n self._store_next_param_in = None\n", "repository": "ssproessig/PC-lint-json-compilation-database", "test_name": "test_04_ensure_BaseVisitor_never_matches", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000302.py"} {"focal_file": "pydmfet/libcpp/oep_hess.py", "focal_class": null, "focal_method": "oep_hess", "tests": "import unittest\n\nclass Test_oep_hess(unittest.TestCase):\n def test_hess(self):\n np.random.seed(0)\n NOrb = 10\n size = NOrb * (NOrb + 1) // 2\n jCa = np.random.rand(NOrb, NOrb)\n orb_Ea = np.random.rand(NOrb, 1)\n NAlpha = 4\n hess = oep_hess(jCa, orb_Ea, size, NOrb, NAlpha=NAlpha, mo_occ=None, smear=0.0, sym_tab=None)\n self.assertAlmostEqual(fingerprint(hess), 1231.816324996269, 8)\n\n def test_hess_smear(self):\n np.random.seed(0)\n NOrb = 10\n size = NOrb * (NOrb + 1) // 2\n jCa = np.random.rand(NOrb, NOrb)\n orb_Ea = np.random.rand(NOrb, 1)\n mo_occ = np.asarray([2.0, 2.0, 2.0, 1.85, 0.12, 0.03, 0.0, 0.0, 0.0, 0.0])\n hess = oep_hess(jCa, orb_Ea, size, NOrb, NAlpha=None, mo_occ=mo_occ, smear=0.05, sym_tab=None)\n self.assertAlmostEqual(fingerprint(hess), 1128.2042486908058, 8)\n", "method_code": "def oep_hess(jCa, orb_Ea, size, NOrb, NAlpha=None, mo_occ=None, smear=0.0, sym_tab=None):\n mo_coeff = np.reshape(jCa, NOrb * NOrb, 'F')\n hess = np.ndarray((size, size), dtype=float, order='F')\n nthread = lib.num_threads()\n e_tol = 0.0001\n occ_tol = 1e-08\n t0 = tools.time0()\n if smear < 1e-08:\n if NAlpha is None:\n raise ValueError('NAlpha has to be set')\n libhess.calc_hess_dm_fast(hess.ctypes.data_as(ctypes.c_void_p), mo_coeff.ctypes.data_as(ctypes.c_void_p), orb_Ea.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(size), ctypes.c_int(NOrb), ctypes.c_int(NAlpha), ctypes.c_int(nthread))\n else:\n if mo_occ is None:\n raise ValueError('mo_occ has to be set')\n libhess.calc_hess_dm_fast_frac(hess.ctypes.data_as(ctypes.c_void_p), mo_coeff.ctypes.data_as(ctypes.c_void_p), orb_Ea.ctypes.data_as(ctypes.c_void_p), mo_occ.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(size), ctypes.c_int(NOrb), ctypes.c_int(nthread), ctypes.c_double(smear), ctypes.c_double(e_tol), ctypes.c_double(occ_tol))\n t1 = tools.timer('hessian construction', t0)\n return hess", "context": "def oep_hess(jCa, orb_Ea, size, NOrb, NAlpha=None, mo_occ=None, smear=0.0, sym_tab=None): ...\ndef symmtrize_hess(hess, sym_tab, size): ...\ndef oep_hess(jCa, orb_Ea, size, NOrb, NAlpha=None, mo_occ=None, smear=0.0, sym_tab=None): ...\ndef oep_hess_old(jCa, orb_Ea, size, NOrb, NOcc): ...\n", "repository": "fishjojo/pydmfet", "test_name": "test_hess", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000303.py"} {"focal_file": "create_layout.py", "focal_class": null, "focal_method": "changes_between_snapshots", "tests": "import unittest\n\nclass Test_changes_between_snapshots(unittest.TestCase):\n def test_same_filesystem_snapshot(self):\n after = {'one.tgz': '1234567890abcdef', 'foo/two.tgz': '0000001111112222', 'three.txt': '1111222233334444', 'bar/bat/four.tgz': '6677889900112233'}\n unchanged, modified, added, deleted = create_layout.changes_between_snapshots(self.before, after)\n self.assertEqual(unchanged, {'one.tgz', 'foo/two.tgz', 'three.txt', 'bar/bat/four.tgz'})\n self.assertSetEqual(modified, self.empty_set)\n self.assertSetEqual(added, self.empty_set)\n self.assertSetEqual(deleted, self.empty_set)\n\n def test_removed_files_filesystem_snapshot(self):\n after = {}\n unchanged, modified, added, deleted = create_layout.changes_between_snapshots(self.before, after)\n self.assertSetEqual(unchanged, self.empty_set)\n self.assertSetEqual(modified, self.empty_set)\n self.assertSetEqual(added, self.empty_set)\n self.assertSetEqual(deleted, {'bar/bat/four.tgz', 'foo/two.tgz', 'one.tgz', 'three.txt'})\n\n def test_new_filesystem_snapshot(self):\n after = {'five.tgz': '1234567890defghi', 'foo/bar/six.tgz': '0000001111112234', 'foofoo/seven.txt': '1111222233334555'}\n unchanged, modified, added, deleted = create_layout.changes_between_snapshots(self.before, after)\n self.assertSetEqual(unchanged, self.empty_set)\n self.assertSetEqual(modified, self.empty_set)\n self.assertSetEqual(added, {'five.tgz', 'foo/bar/six.tgz', 'foofoo/seven.txt'})\n self.assertSetEqual(deleted, {'bar/bat/four.tgz', 'foo/two.tgz', 'one.tgz', 'three.txt'})\n\n def test_fully_modified_filesystem_snapshot(self):\n after = {'one.tgz': '1234567890aabbcc', 'foo/two.tgz': '0000001111112233', 'three.txt': '1111222233334455', 'bar/bat/four.tgz': '6677889900123456'}\n unchanged, modified, added, deleted = create_layout.changes_between_snapshots(self.before, after)\n self.assertSetEqual(unchanged, self.empty_set)\n self.assertSetEqual(modified, {'bar/bat/four.tgz', 'foo/two.tgz', 'one.tgz', 'three.txt'})\n self.assertSetEqual(added, self.empty_set)\n self.assertSetEqual(deleted, self.empty_set)\n", "method_code": "def changes_between_snapshots(before_dict, after_dict):\n \"\"\"Given two 'snapshots' of an artifacts structure -- 'before' and 'after' --\n return a tuple specifying which artifacts have been added, which have been\n removed, which have been modified, and which have remained unchanged. Both\n these dictionaries have artifact names as the keys and their hashes as the\n values.\"\"\"\n before_set = set(before_dict.keys())\n after_set = set(after_dict.keys())\n removed_artifacts = before_set.difference(after_set)\n added_artifacts = after_set.difference(before_set)\n unchanged_artifacts = set()\n modified_artifacts = set()\n for key in before_set.intersection(after_set):\n if before_dict[key] == after_dict[key]:\n unchanged_artifacts.add(key)\n else:\n modified_artifacts.add(key)\n return (unchanged_artifacts, modified_artifacts, added_artifacts, removed_artifacts)", "context": "def changes_between_snapshots(before_dict, after_dict): ...\ndef changes_between_snapshots(before_dict, after_dict): ...\ndef create_material_rules(previous_link, current_link): ...\ndef create_product_rules(current_link): ...\ndef create_layout_from_ordered_links(links): ...\n", "repository": "in-toto/layout-web-tool", "test_name": "test_same_filesystem_snapshot", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000304.py"} {"focal_file": "create_layout.py", "focal_class": null, "focal_method": "create_material_rules", "tests": "import unittest\n\nclass Test_create_material_rules(unittest.TestCase):\n def test_create_material_rules_of_initial_step(self):\n second_link = in_toto.models.link.Link.read(self.second_step_link_str)\n links = [second_link]\n expected_materials = [['DELETE', 'three.txt'], ['ALLOW', 'bar/bat/four.tgz'], ['ALLOW', 'foo/two.tgz'], ['ALLOW', 'one.tgz'], ['DISALLOW', '*']]\n self.assertEqual(expected_materials, create_layout.create_material_rules(None, second_link))\n\n def test_create_material_rules_of_not_initial_step(self):\n first_link = in_toto.models.link.Link.read(self.first_step_link_str)\n second_link = in_toto.models.link.Link.read(self.second_step_link_str)\n links = [first_link, second_link]\n expected_materials = [['MATCH', 'bar/bat/four.tgz', 'WITH', 'PRODUCTS', 'FROM', 'first_step'], ['MATCH', 'foo/two.tgz', 'WITH', 'PRODUCTS', 'FROM', 'first_step'], ['MATCH', 'one.tgz', 'WITH', 'PRODUCTS', 'FROM', 'first_step'], ['MATCH', 'three.txt', 'WITH', 'PRODUCTS', 'FROM', 'first_step'], ['DELETE', 'three.txt'], ['DISALLOW', '*']]\n self.assertEqual(expected_materials, create_layout.create_material_rules(first_link, second_link))\n", "method_code": "def create_material_rules(previous_link, current_link):\n \"\"\"Create generic material rules\n\n - MATCH available materials with products from previous step (links must be\n an ordered list) and\n - ALLOW available materials if it is the first step in the list\n - DELETE removed materials\n\n Args:\n previous_link: a link of previous step, including previous step's materials\n and products\n current link: a link of current step, including current step's materials\n and products\n\n Returns:\n a list of material rules\n \"\"\"\n expected_materials_rules = []\n unchanged_artifacts, modified_artifacts, _, deleted_artifacts = changes_between_snapshots(current_link.materials, current_link.products)\n previous_link_products = previous_link.products if previous_link else []\n for artifact in sorted(set(current_link.materials).intersection(previous_link_products)):\n expected_materials_rules.append(['MATCH', artifact, 'WITH', 'PRODUCTS', 'FROM', previous_link.name])\n for artifact in sorted(deleted_artifacts):\n expected_materials_rules.append(['DELETE', artifact])\n if deleted_artifacts.intersection(previous_link_products):\n warnings.warn('DELETE rule is moot because of the previous MATCH rule. Only the first rule for a given artifact has an effect')\n for artifact in sorted(set(current_link.materials).difference(previous_link_products).difference(deleted_artifacts)):\n expected_materials_rules.append(['ALLOW', artifact])\n expected_materials_rules.append(['DISALLOW', '*'])\n return expected_materials_rules", "context": "def create_material_rules(previous_link, current_link): ...\ndef changes_between_snapshots(before_dict, after_dict): ...\ndef create_material_rules(previous_link, current_link): ...\ndef create_product_rules(current_link): ...\ndef create_layout_from_ordered_links(links): ...\n", "repository": "in-toto/layout-web-tool", "test_name": "test_create_material_rules_of_initial_step", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000305.py"} {"focal_file": "create_layout.py", "focal_class": null, "focal_method": "create_product_rules", "tests": "import unittest\n\nclass Test_create_product_rules(unittest.TestCase):\n def test_create_product_rules(self):\n second_link = in_toto.models.link.Link.read(self.second_step_link_str)\n expected_products = [['ALLOW', 'bar/bat/four.tgz'], ['ALLOW', 'one.tgz'], ['MODIFY', 'foo/two.tgz'], ['CREATE', 'baz/six.tgz'], ['CREATE', 'five.txt'], ['DISALLOW', '*']]\n self.assertTrue(expected_products, create_layout.create_product_rules(second_link))\n", "method_code": "def create_product_rules(current_link):\n \"\"\"Create generic product rules\n\n - ALLOW available products\n - MODIFY changed products\n - CREATE added products\n - DISALLOW everything else\n\n Args:\n current_link: a link of current step, including current step's materials\n and products\n\n Returns:\n a list of product rules\n \"\"\"\n expected_products_rules = []\n unchanged_artifacts, modified_artifacts, added_artifacts, _ = changes_between_snapshots(current_link.materials, current_link.products)\n for artifact in sorted(unchanged_artifacts):\n expected_products_rules.append(['ALLOW', artifact])\n for artifact in sorted(modified_artifacts):\n expected_products_rules.append(['MODIFY', artifact])\n for artifact in sorted(added_artifacts):\n expected_products_rules.append(['CREATE', artifact])\n expected_products_rules.append(['DISALLOW', '*'])\n return expected_products_rules", "context": "def create_product_rules(current_link): ...\ndef changes_between_snapshots(before_dict, after_dict): ...\ndef create_material_rules(previous_link, current_link): ...\ndef create_product_rules(current_link): ...\ndef create_layout_from_ordered_links(links): ...\n", "repository": "in-toto/layout-web-tool", "test_name": "test_create_product_rules", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000306.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "list_of_all_customers", "tests": "import unittest\n\nclass Test_list_of_all_customers(unittest.TestCase):\n @patch('src.bank.list_of_all_customers')\n def test_list_of_all_customers(self, mock):\n mb.list_of_all_customers()\n self.assertTrue(mock.called)\n", "method_code": "def list_of_all_customers():\n models.list_of_bank_customers()", "context": "def list_of_all_customers(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000307.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "find_customer", "tests": "import unittest\n\nclass Test_find_customer(unittest.TestCase):\n @patch('builtins.input', return_value=1234567890)\n @patch('src.bank.models.find_customer')\n def test_find_customer_not_found(self, mock_models_find, input):\n mock_models_find.return_value = None\n mb.find_customer()\n mock_models_find.assert_called_with(1234567890)\n\n @patch('builtins.input', return_value=1234567890)\n @patch('sys.stdout', new_callable=io.StringIO)\n @patch('src.bank.models.find_customer')\n def test_find_customer(self, mock_models_find, mock_stdout, mock_input):\n customer = get_customer()\n mock_models_find.return_value = customer\n mb.find_customer()\n self.assertEqual(mock_stdout.getvalue(), '\\nInfo for customer ' + customer.name + ' is below: \\n' + tabulate([[\"Customer's Id \", customer.Id], [\"Customer's name \", customer.name], [\"Customer's Address \", customer.address], [\"Customer's Date of Birth \", customer.dob], [\"Customer's SSN \", customer.ssn], [\"Customer's phone Number \", customer.phone_number], [\"Customer's email \", customer.email]], tablefmt='fancy_grid') + '\\n')\n", "method_code": "def find_customer():\n ssn = input(\"Please enter Customer's SSN: \")\n existing_customer = models.find_customer(ssn)\n if existing_customer is not None:\n print('\\nInfo for customer ' + existing_customer.name + ' is below: ')\n print(tabulate([[\"Customer's Id \", existing_customer.Id], [\"Customer's name \", existing_customer.name], [\"Customer's Address \", existing_customer.address], [\"Customer's Date of Birth \", existing_customer.dob], [\"Customer's SSN \", existing_customer.ssn], [\"Customer's phone Number \", existing_customer.phone_number], [\"Customer's email \", existing_customer.email]], tablefmt='fancy_grid'))", "context": "def find_customer(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000308.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "update_customer", "tests": "import unittest\n\nclass Test_update_customer(unittest.TestCase):\n @patch('builtins.input', return_value=1234567890)\n @patch('src.bank.models.find_customer')\n def test_update_customer_not_found(self, mock_models_find, input):\n mock_models_find.return_value = None\n mb.update_customer()\n mock_models_find.assert_called_with(1234567890)\n\n @patch('builtins.input', side_effect=[1234567890, 'Klaudius1', 'Ave Street 1', '1985-01-01', 1234567890, '1876543210', 'mail@mail.ua', 1234567890, 'Savings'])\n @patch('sys.stdout', new_callable=io.StringIO)\n @patch('src.bank.models.update_customer_info')\n @patch('src.bank.models.find_customer')\n def test_update_customer_found(self, mock_models_find, mock_models_update, mock_stdout, input):\n customer = get_customer()\n mock_models_find.return_value = customer\n mb.update_customer()\n mock_models_find.assert_called_with(1234567890)\n mock_models_find.update_customer_info(customer)\n self.assertEqual(mock_stdout.getvalue(), \"Existing Customer Current Name: Klaudius\\n\\nCustomer's profile has been updated\\n\", msg='Not Equal')\n self.assertEqual(customer.name, 'Klaudius1')\n self.assertEqual(customer.address, 'Ave Street 1')\n", "method_code": "def update_customer():\n ssn = input(\"Please enter customer's SSN: \")\n existing_customer = models.find_customer(ssn)\n if existing_customer is None:\n return\n print('Existing Customer Current Name: ' + existing_customer.name)\n new_customer_name = str(input(\"Please enter customer's new name, otherwise hit 'Enter': \"))\n if new_customer_name:\n existing_customer.name = new_customer_name\n new_customer_address = str(input(\"Please enter customer's new address, otherwise hit 'Enter': \"))\n if new_customer_address:\n existing_customer.address = new_customer_address\n new_customer_dob = input(\"Please enter customer's new Date of Birth (YYYY-MM-DD), otherwise hit 'Enter': \")\n if new_customer_dob:\n existing_customer.dob = new_customer_dob\n new_customer_ssn = input(\"Please enter customer's new SSN, otherwise hit 'Enter': \")\n if new_customer_ssn:\n existing_customer.SSN = new_customer_ssn\n new_customer_phone_no = str(input(\"Please enter customer's new phone number, otherwise hit 'Enter': \"))\n if new_customer_phone_no:\n existing_customer.phone_number = new_customer_phone_no\n new_customer_email = str(input(\"Please enter customer's new email, otherwise hit 'Enter': \"))\n if new_customer_email:\n existing_customer.email = new_customer_email\n models.update_customer_info(existing_customer)\n print(\"\\nCustomer's profile has been updated\")", "context": "def update_customer(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000309.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "remove_customer", "tests": "import unittest\n\nclass Test_remove_customer(unittest.TestCase):\n @patch('builtins.input', return_value=1234567890)\n @patch('src.bank.models.find_customer')\n def test_remove_customer_not_found(self, mock_models_find, input):\n mock_models_find.return_value = None\n mb.remove_customer()\n mock_models_find.assert_called_with(1234567890)\n\n @patch('builtins.input', return_value=1234567890)\n @patch('sys.stdout', new_callable=io.StringIO)\n @patch('src.bank.models.find_customer')\n @patch('src.bank.models.delete_customer')\n def test_remove_customer_found(self, models_mock_delete, models_mock_find, mock_stdout, mock_input):\n customer = get_customer()\n models_mock_find.return_value = customer\n models_mock_delete.return_value = customer\n mb.remove_customer()\n models_mock_find.assert_called_with(1234567890)\n models_mock_delete.assert_called_with(customer)\n self.assertEqual(mock_stdout.getvalue(), 'Customer Klaudius is deleted\\n', msg='Not Equal')\n", "method_code": "def remove_customer():\n ssn = input(\"Please enter customer's SSN: \")\n existing_customer = models.find_customer(ssn)\n if existing_customer is not None:\n models.delete_customer(existing_customer)\n print('Customer ' + existing_customer.name + ' is deleted')", "context": "def remove_customer(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000310.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "add_new_customer", "tests": "import unittest\n\nclass Test_add_new_customer(unittest.TestCase):\n @patch('builtins.input', side_effect=['Klaudius', 'Ave Street', '1985-01-01', 1234567890, '1876543210', 'mail@mail.ua', 1234567890, 'Savings'])\n @patch('sys.stdout', new_callable=io.StringIO)\n @patch('src.bank.models.insert_customer')\n def test_add_new_customer(self, mock_models, mock_stdout, mock_input):\n mb.add_new_customer()\n self.assertEqual(mock_stdout.getvalue(), '\\nNew customer Klaudius has been added. Please verify the following info: \\n' + tabulate([['Name ', 'Klaudius'], ['Address ', 'Ave Street'], ['Date of Birth ', '1985-01-01'], ['SSN ', 1234567890], ['Phone Number ', 1876543210], ['Email ', 'mail@mail.ua'], ['Account number ', 1234567890], ['Type ', 'Savings']], tablefmt='fancy_grid') + '\\n')\n mock_models.assert_called_with(name_param='Klaudius', address_param='Ave Street', dob_param='1985-01-01', ssn_param=1234567890, phone_number_param='1876543210', email_param='mail@mail.ua', account_no_param=1234567890, account_type_param='Savings')\n", "method_code": "def add_new_customer():\n new_customer_name = str(input(\"Please enter customer's name (First name Last name), then hit 'Enter': \"))\n new_customer_address = str(input(\"Please enter customer's address, then hit 'Enter': \"))\n new_customer_dob = input(\"Please enter customer's Date of Birth (YYYY-MM-DD), then hit 'Enter': \")\n new_customer_ssn = input(\"Please enter customer's SSN, then hit 'Enter': \")\n new_customer_phone_no = str(input(\"Please enter customer's phone number, then hit 'Enter': \"))\n new_customer_email = str(input(\"Please enter customer's email, then hit 'Enter': \"))\n new_customer_no = input(\"Please enter customer's 10-digit account number, then hit 'Enter': \")\n new_customer_type = str(input(\"Please enter type of account (Checking, Savings, Loan), then hit 'Enter': \"))\n if acct_type_validation(new_customer_type):\n models.insert_customer(name_param=new_customer_name, address_param=new_customer_address, dob_param=new_customer_dob, ssn_param=new_customer_ssn, phone_number_param=new_customer_phone_no, email_param=new_customer_email, account_no_param=new_customer_no, account_type_param=new_customer_type)\n print('\\nNew customer ' + new_customer_name + ' has been added. Please verify the following info: ')\n print(tabulate([['Name ', new_customer_name], ['Address ', new_customer_address], ['Date of Birth ', new_customer_dob], ['SSN ', new_customer_ssn], ['Phone Number ', new_customer_phone_no], ['Email ', new_customer_email], ['Account number ', new_customer_no], ['Type ', new_customer_type]], tablefmt='fancy_grid'))", "context": "def add_new_customer(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000311.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "get_balance", "tests": "import unittest\n\nclass Test_get_balance(unittest.TestCase):\n @patch('builtins.input', return_value=1234567890)\n @patch('sys.stdout', new_callable=io.StringIO)\n @patch('src.bank.models.check_balance')\n def test_check_balance_found(self, models_mock_check, mock_stdout, mock_input):\n models_mock_check.return_value = 123\n mb.get_balance()\n self.assertEqual(mock_stdout.getvalue(), '\\nAccount balance: $123\\n', msg='Not Equal')\n", "method_code": "def get_balance():\n account_no = input(\"Please enter customer's 10-digit account number, then hit 'Enter': \")\n existing_acct_balance = models.check_balance(account_no)\n if existing_acct_balance is not None:\n print('\\nAccount balance: $' + str(existing_acct_balance))", "context": "def get_balance(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000312.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "open_new_account", "tests": "import unittest\n\nclass Test_open_new_account(unittest.TestCase):\n @patch('builtins.input', return_value=1234567890)\n @patch('src.bank.models.find_customer')\n def test_open_new_account_customer_not_found(self, mock_models_find, input):\n mock_models_find.return_value = None\n mb.open_new_account()\n mock_models_find.assert_called_with(1234567890)\n\n @patch('builtins.input', side_effect=[1234567890, 1876543210, 'bla'])\n @patch('sys.stdout', new_callable=io.StringIO)\n @patch('src.bank.models.find_customer')\n def test_open_new_account_customer_found(self, models_mock_find, mock_stdout, mock_input):\n customer = get_customer()\n models_mock_find.return_value = customer\n mb.open_new_account()\n models_mock_find.assert_called_with(1234567890)\n self.assertEqual(mock_stdout.getvalue(), 'Invalid entry. Please enter valid account type\\n', msg='Not Equal')\n", "method_code": "def open_new_account():\n ssn = input(\"Please enter customer's SSN: \")\n existing_customer = models.find_customer(ssn)\n if existing_customer is not None:\n new_account_no = input(\"Please enter new 10-digit account number, then hit 'Enter': \")\n new_account_type = str(input(\"Please enter type of account (Checking, Savings, Loan), then hit 'Enter': \"))\n if acct_type_validation(new_account_type):\n models.open_new_account(existing_customer, account_no_param=new_account_no, account_type_param=new_account_type)\n print('\\nNew account number ' + str(new_account_no) + \" has been added to customer's profile\")", "context": "def open_new_account(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000313.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "close_account", "tests": "import unittest\n\nclass Test_close_account(unittest.TestCase):\n @patch('builtins.input', return_value=1234567890)\n @patch('src.bank.models.close_existing_account')\n def test_close_account(self, mock_models, input):\n mb.close_account()\n mock_models.assert_called_with(account_num_param=1234567890)\n", "method_code": "def close_account():\n account_no = input(\"Please enter customer's 10-digit account number that you wish to delete, then hit 'Enter': \")\n models.close_existing_account(account_num_param=account_no)", "context": "def close_account(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000314.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "add_new_transaction", "tests": "import unittest\n\nclass Test_add_new_transaction(unittest.TestCase):\n @patch('builtins.input', return_value=1234567890)\n @patch('src.bank.models.get_account')\n def test_add_new_transaction_account_not_found(self, mock_models_get_account, input):\n mock_models_get_account.return_value = None\n mb.add_new_transaction()\n mock_models_get_account.assert_called_with(1234567890)\n\n @patch('builtins.input', side_effect=[1234567890, 'Deposit', 1234])\n @patch('sys.stdout', new_callable=io.StringIO)\n @patch('src.bank.models.get_account')\n @patch('src.bank.models.add_new_transaction')\n def test_add_new_transaction(self, mock_models_new_trans, mock_models_get_account, mock_stdout, input):\n mock_models_get_account.return_value = models.Account()\n mb.add_new_transaction()\n mock_models_get_account.assert_called_with(1234567890)\n mock_models_new_trans.assert_called_with(account_no_param=1234567890, transaction_type_param='Deposit', transaction_amount_param=1234)\n self.assertEqual(mock_stdout.getvalue(), '\\nDeposit transaction for $1234 has been added. Please verify transaction details below: \\n' + tabulate([['Account Number ', 1234567890], ['Type ', 'Deposit'], ['Amount ', 1234]], tablefmt='fancy_grid') + '\\n', msg='Not Equal')\n", "method_code": "def add_new_transaction():\n account_no = input(\"Please enter customer's 10-digit account number, then hit 'Enter': \")\n existing_account = models.get_account(account_no)\n if existing_account is None:\n return\n transaction_type = str(input('Please enter type of transaction (Deposit, Withdrawal, Interest, Payment): '))\n transaction_amount = input(\"Please enter transaction amount ('+' or '-'): \")\n models.add_new_transaction(account_no_param=account_no, transaction_type_param=transaction_type, transaction_amount_param=transaction_amount)\n print('\\n' + transaction_type + ' transaction for $' + str(transaction_amount) + ' has been added. Please verify transaction details below: ')\n print(tabulate([['Account Number ', account_no], ['Type ', transaction_type], ['Amount ', transaction_amount]], tablefmt='fancy_grid'))", "context": "def add_new_transaction(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000315.py"} {"focal_file": "src/bank.py", "focal_class": null, "focal_method": "transaction_history", "tests": "import unittest\n\nclass Test_transaction_history(unittest.TestCase):\n @patch('builtins.input', return_value=1234567890)\n @patch('src.bank.models.show_transactions')\n def test_transaction_history(self, mock_models, input):\n mb.transaction_history()\n mock_models.show_transactions(account_no=1234567890)\n", "method_code": "def transaction_history():\n account_no = input(\"Please enter customer's 10-digit account number, then hit 'Enter': \")\n models.show_transactions(account_no=account_no)", "context": "def transaction_history(): ...\ndef list_of_all_customers(): ...\ndef find_customer(): ...\ndef update_customer(): ...\ndef remove_customer(): ...\ndef add_new_customer(): ...\ndef get_balance(): ...\ndef open_new_account(): ...\ndef acct_type_validation(new_account_type): ...\ndef close_account(): ...\ndef add_new_transaction(): ...\ndef transaction_history(): ...\n", "repository": "Len-X/Pet_Project-Virtual_Bank", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000316.py"} {"focal_file": "ctypeslib/ctypeslib/util/byref_at.py", "focal_class": null, "focal_method": "byref_at", "tests": "import unittest\n\nclass Test_byref_at(unittest.TestCase):\n def test_byref_at(self):\n array = (c_int * 8)()\n self.failUnlessEqual(addressof(array) + 0, testfunc(byref_at(array, 0)))\n self.failUnlessEqual(addressof(array) + 1, testfunc(byref_at(array, 1)))\n for ofs in range(8 * sizeof(c_int)):\n self.failUnlessEqual(addressof(array) + ofs, testfunc(byref_at(array, ofs)))\n", "method_code": "def byref_at(obj, offset):\n \"\"\"byref_at(cobj, offset) behaves similar this C code:\n\n (((char *)&obj) + offset)\n\n In other words, the returned 'reference' points to the address\n of 'cobj' + 'offset'. 'offset' is in units of bytes.\n \"\"\"\n ref = byref(obj)\n c_void_p.from_address(id(ref) + _byref_pointer_offset).value += offset\n return ref", "context": "def byref_at(obj, offset): ...\ndef _calc_offset(): ...\ndef byref_at(obj, offset): ...\n", "repository": "shanewholloway/ctypes-old", "test_name": "test_byref_at", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000317.py"} {"focal_file": "software/glasgow/gateware/lfsr.py", "focal_class": null, "focal_method": "generate", "tests": "import unittest\n\nclass Test_generate(unittest.TestCase):\n @simulation_test\n def test_generate(self, tb):\n soft_values = list(self.tb.dut.generate())\n hard_values = []\n for _ in range(len(soft_values)):\n hard_values.append((yield self.tb.dut.value))\n yield\n self.assertEqual(len(soft_values), 65535)\n self.assertEqual(hard_values, soft_values)\n", "method_code": " def generate(self):\n \"\"\"Generate every distinct value the LFSR will take.\"\"\"\n value = self.reset\n mask = (1 << self.degree) - 1\n while True:\n yield value\n feedback = 0\n for tap in self.taps:\n feedback ^= value >> tap - 1 & 1\n value = value << 1 & mask | feedback\n if value == self.reset:\n break\n ", "context": "class LinearFeedbackShiftRegister(Elaboratable):\n def generate(self): ...\n def __init__(self, degree, taps, reset=1): ...\n def elaborate(self, platform): ...\n\n self.degree = degree\n self.taps = taps\n self.reset = reset\n self.value = Signal(degree, reset=reset)\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000318.py"} {"focal_file": "software/glasgow/gateware/mpsse.py", "focal_class": null, "focal_method": "read", "tests": "import unittest\n\nclass Test_read(unittest.TestCase):\n @simulation_test\n def test_gpio_read(self, tb):\n yield tb.i.eq(43605)\n yield\n yield from tb.write(129)\n self.assertEqual((yield from tb.read()), 85)\n yield from tb.write(131)\n self.assertEqual((yield from tb.read()), 170)\n self.assertEqual((yield from tb.dut_state()), 'IDLE')\n\n @simulation_test\n def test_bits_read(self, tb):\n yield from tb.write(34)\n yield from tb.write(5)\n self.assertEqual((yield tb.dut.rposition.bit), 5)\n self.assertEqual((yield from tb.read()), 0)\n", "method_code": " def read(self):\n yield self.dut.tx_ack.eq(1)\n for _ in range(32 * self.clkdiv):\n yield\n if (yield self.dut.tx_rdy) == 1:\n byte = (yield self.dut.tx_data)\n yield self.dut.tx_ack.eq(0)\n yield\n return byte\n raise Exception('DUT stuck while reading')\n ", "context": "class MPSSETestbench(Module):\n def read(self): ...\n def __init__(self): ...\n def do_finalize(self): ...\n def dut_state(self): ...\n def write(self, byte): ...\n def _wait_for_tck(self, at_setup=None): ...\n def recv_tdi(self, nbits, pos): ...\n def recv_tms(self, nbits, pos): ...\n def xfer(self, nbits, out_bits, in_bits, out_pos, in_pos): ...\n def out_xfer(self, nbits, bits, pos): ...\n def in_xfer(self, nbits, bits, pos): ...\n\n self.tck = TSTriple()\n self.tdi = TSTriple()\n self.tdo = TSTriple()\n self.tms = TSTriple()\n self.gpiol = [TSTriple() for _ in range(4)]\n self.gpioh = [TSTriple() for _ in range(8)]\n self.pads = [self.tck, self.tdi, self.tdo, self.tms, *self.gpiol, *self.gpioh]\n self.i = Cat([pad.i for pad in self.pads])\n self.o = Cat([pad.o for pad in self.pads])\n self.oe = Cat([pad.oe for pad in self.pads])\n self.submodules.dut = MPSSE(self.pads)\n self.clkdiv = 5\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000319.py"} {"focal_file": "software/glasgow/gateware/mpsse.py", "focal_class": null, "focal_method": "write", "tests": "import unittest\n\nclass Test_write(unittest.TestCase):\n @simulation_test\n def test_gpio_write(self, tb):\n yield from tb.write(128)\n yield from tb.write(161)\n yield from tb.write(82)\n self.assertEqual((yield tb.o), 161)\n self.assertEqual((yield tb.oe), 82)\n yield from tb.write(130)\n yield from tb.write(126)\n yield from tb.write(129)\n self.assertEqual((yield tb.o), 32417)\n self.assertEqual((yield tb.oe), 33106)\n self.assertEqual((yield from tb.dut_state()), 'IDLE')\n\n @simulation_test\n def test_bits_write(self, tb):\n yield from tb.write(18)\n yield from tb.write(5)\n self.assertEqual((yield tb.dut.rposition.bit), 5)\n yield from tb.write(85)\n self.assertEqual((yield from tb.recv_tdi(5, pos=True)), 10)\n\n @simulation_test\n def test_bits_read_write(self, tb):\n yield from tb.write(132)\n yield from tb.write(51)\n yield from tb.write(5)\n self.assertEqual((yield tb.dut.rposition.bit), 5)\n yield from tb.write(85)\n self.assertEqual((yield from tb.recv_tdi(5, pos=True)), 10)\n self.assertEqual((yield from tb.read()), 21)\n\n @simulation_test\n def test_tms_write(self, tb):\n yield from tb.write(74)\n yield from tb.write(5)\n self.assertEqual((yield tb.dut.rposition.bit), 5)\n yield from tb.write(85)\n self.assertEqual((yield from tb.recv_tms(5, pos=True)), 21)\n\n @simulation_test\n def test_hibyte_lobyte_write(self, tb):\n yield from tb.write(16)\n yield from tb.write(5)\n self.assertEqual((yield tb.dut.rposition.lobyte), 5)\n yield from tb.write(17)\n self.assertEqual((yield tb.dut.rposition.hibyte), 17)\n\n @simulation_test\n def test_divisor_write(self, tb):\n yield from tb.write(134)\n yield from tb.write(52)\n yield from tb.write(18)\n self.assertEqual((yield tb.dut.divisor), 4660)\n self.assertEqual((yield from tb.dut_state()), 'IDLE')\n", "method_code": " def write(self, byte):\n yield self.dut.rx_data.eq(byte)\n yield self.dut.rx_rdy.eq(1)\n for _ in range(32 * self.clkdiv):\n yield\n if (yield self.dut.rx_ack) == 1:\n yield self.dut.rx_data.eq(0)\n yield self.dut.rx_rdy.eq(0)\n yield\n return\n raise Exception('DUT stuck while writing')\n ", "context": "class MPSSETestbench(Module):\n def write(self, byte): ...\n def __init__(self): ...\n def do_finalize(self): ...\n def dut_state(self): ...\n def read(self): ...\n def _wait_for_tck(self, at_setup=None): ...\n def recv_tdi(self, nbits, pos): ...\n def recv_tms(self, nbits, pos): ...\n def xfer(self, nbits, out_bits, in_bits, out_pos, in_pos): ...\n def out_xfer(self, nbits, bits, pos): ...\n def in_xfer(self, nbits, bits, pos): ...\n\n self.tck = TSTriple()\n self.tdi = TSTriple()\n self.tdo = TSTriple()\n self.tms = TSTriple()\n self.gpiol = [TSTriple() for _ in range(4)]\n self.gpioh = [TSTriple() for _ in range(8)]\n self.pads = [self.tck, self.tdi, self.tdo, self.tms, *self.gpiol, *self.gpioh]\n self.i = Cat([pad.i for pad in self.pads])\n self.o = Cat([pad.o for pad in self.pads])\n self.oe = Cat([pad.oe for pad in self.pads])\n self.submodules.dut = MPSSE(self.pads)\n self.clkdiv = 5\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000320.py"} {"focal_file": "software/glasgow/gateware/mpsse.py", "focal_class": null, "focal_method": "write_single_byte", "tests": "import unittest\n\nclass Test_write_single_byte(unittest.TestCase):\n @simulation_test\n def test_write_single_byte_clkpos(self, tb):\n yield tb.dut.divisor.eq(1)\n yield from self.write_single_byte(tb, pos=True)\n\n @simulation_test\n def test_write_single_byte_clkneg(self, tb):\n yield tb.dut.divisor.eq(1)\n yield from self.write_single_byte(tb, pos=False)\n\n @simulation_test\n def test_write_single_byte_clkneg_fast(self, tb):\n yield from self.write_single_byte(tb, pos=False)\n", "method_code": " def write_single_byte(self, tb, pos):\n yield from tb.write(128)\n if pos:\n yield from tb.write(1)\n else:\n yield from tb.write(0)\n yield from tb.write(13)\n if pos:\n yield from tb.write(16)\n else:\n yield from tb.write(17)\n yield from tb.write(0)\n yield from tb.write(0)\n yield from tb.write(165)\n self.assertTrue((yield from tb.in_xfer(8, 165, not pos)))\n ", "context": "class MPSSETestCase(unittest.TestCase):\n def write_single_byte(self, tb, pos): ...\n def setUp(self): ...\n def simulationSetUp(self, tb): ...\n def test_error(self, tb): ...\n def test_gpio_read(self, tb): ...\n def test_gpio_write(self, tb): ...\n def test_bits_write(self, tb): ...\n def test_clk_bits(self, tb): ...\n def test_clk_bytes(self, tb): ...\n def test_bits_read(self, tb): ...\n def test_legacy_dividor(self, tb): ...\n def test_bits_read_write(self, tb): ...\n def test_tms_write(self, tb): ...\n def test_invalid_tms_commands(self, tb): ...\n def test_hibyte_lobyte_write(self, tb): ...\n def test_divisor_write(self, tb): ...\n def test_write_single_byte_clkpos(self, tb): ...\n def test_write_single_byte_clkneg(self, tb): ...\n def test_write_single_byte_clkneg_fast(self, tb): ...\n def test_write_single_byte_clkwrong(self, tb): ...\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000321.py"} {"focal_file": "software/glasgow/gateware/uart.py", "focal_class": null, "focal_method": "ack", "tests": "import unittest\n\nclass Test_ack(unittest.TestCase):\n @simulation_test\n def test_rx_back_to_back(self, tb):\n yield from self.byte(tb, [1, 0, 1, 0, 1, 0, 1, 0])\n yield from self.ack(tb, 85)\n yield from self.byte(tb, [0, 1, 0, 1, 0, 1, 0, 1])\n yield from self.ack(tb, 170)\n", "method_code": " def ack(self, tb, data):\n self.assertEqual((yield tb.dut.rx_rdy), 0)\n yield\n yield\n yield\n self.assertEqual((yield tb.dut.rx_rdy), 1)\n self.assertEqual((yield tb.dut.rx_data), data)\n yield tb.dut.rx_ack.eq(1)\n yield\n yield tb.dut.rx_ack.eq(0)\n yield\n yield\n self.assertEqual((yield tb.dut.rx_rdy), 0)\n ", "context": "class UARTRXTestCase(unittest.TestCase):\n def ack(self, tb, data): ...\n def setUp(self): ...\n def cyc(self, tb, err=None): ...\n def bit(self, tb, bit): ...\n def start(self, tb): ...\n def data(self, tb, bit): ...\n def stop(self, tb): ...\n def byte(self, tb, bits): ...\n def test_rx_0x55(self, tb): ...\n def test_rx_0xC3(self, tb): ...\n def test_rx_0x81(self, tb): ...\n def test_rx_0xA5(self, tb): ...\n def test_rx_0xFF(self, tb): ...\n def test_rx_back_to_back(self, tb): ...\n def test_rx_ferr(self, tb): ...\n def test_rx_ovf(self, tb): ...\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000322.py"} {"focal_file": "software/glasgow/gateware/i2c.py", "focal_class": null, "focal_method": "start", "tests": "import unittest\n\nclass Test_start(unittest.TestCase):\n @simulation_test\n def test_start(self, tb):\n yield from tb.start()\n yield from self.assertState(tb, 'START-SDA-L')\n yield from self.assertCondition(tb, lambda: (yield tb.dut.bus.start))\n self.assertEqual((yield tb.dut.busy), 0)\n\n @simulation_test\n def test_repeated_start(self, tb):\n yield tb.dut.bus.sda_o.eq(0)\n yield\n yield\n yield from tb.start()\n yield from self.assertState(tb, 'START-SCL-L')\n yield from self.assertCondition(tb, lambda: (yield tb.dut.bus.start))\n self.assertEqual((yield tb.dut.busy), 0)\n\n @simulation_test\n def test_addr_shift(self, tb):\n yield tb.dut.address.eq(127)\n yield from self.assertState(tb, 'IDLE')\n yield from tb.start()\n yield from self.assertState(tb, 'START')\n for _ in range(8):\n yield from tb.write_bit(1)\n yield from self.assertState(tb, 'ADDR-SHIFT')\n", "method_code": " def start(self):\n yield from self.strobe(self.dut.start)\n ", "context": "class I2CInitiatorTestbench(I2CTestbench):\n def start(self): ...\n def __init__(self): ...\n def strobe(self, signal): ...\n def stop(self): ...\n def read(self, ack): ...\n def write(self, data): ...\n\n self.submodules.dut = I2CInitiator(pads=self, period_cyc=self.period_cyc)\n self.wait_cyc = self.period_cyc * 3\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000323.py"} {"focal_file": "software/glasgow/gateware/i2c.py", "focal_class": null, "focal_method": "stop", "tests": "import unittest\n\nclass Test_stop(unittest.TestCase):\n @simulation_test\n def test_stop(self, tb):\n yield tb.dut.bus.sda_o.eq(0)\n yield\n yield\n yield from tb.stop()\n yield from self.assertState(tb, 'STOP-SDA-H')\n yield from self.assertCondition(tb, lambda: (yield tb.dut.bus.stop))\n self.assertEqual((yield tb.dut.busy), 0)\n\n @simulation_test\n def test_addr_stop(self, tb):\n yield from tb.start()\n yield from tb.write_bit(0)\n yield from tb.write_bit(1)\n yield from tb.stop()\n yield from self.assertState(tb, 'IDLE')\n\n @simulation_test\n def test_write_stop(self, tb):\n yield from self.start_addr(tb, read=False)\n yield from tb.write_bit(0)\n yield from tb.write_bit(1)\n yield from tb.stop()\n yield from self.assertState(tb, 'IDLE')\n\n @simulation_test\n def test_read_stop(self, tb):\n yield tb.dut.data_o.eq(255)\n yield from self.start_addr(tb, read=True)\n yield from tb.read_bit()\n yield from tb.read_bit()\n yield from tb.stop()\n yield from self.assertState(tb, 'IDLE')\n", "method_code": " def stop(self):\n yield from self.strobe(self.dut.stop)\n ", "context": "class I2CInitiatorTestbench(I2CTestbench):\n def stop(self): ...\n def __init__(self): ...\n def strobe(self, signal): ...\n def start(self): ...\n def read(self, ack): ...\n def write(self, data): ...\n\n self.submodules.dut = I2CInitiator(pads=self, period_cyc=self.period_cyc)\n self.wait_cyc = self.period_cyc * 3\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000324.py"} {"focal_file": "software/glasgow/gateware/i2c.py", "focal_class": null, "focal_method": "write", "tests": "import unittest\n\nclass Test_write(unittest.TestCase):\n @simulation_test\n def test_write_tx(self, tb):\n yield from self.start(tb)\n yield from self.write(tb, 85, [0, 1, 0, 1, 0, 1, 0, 1], 1)\n yield from self.write(tb, 51, [0, 0, 1, 1, 0, 0, 1, 1], 0)\n yield from self.stop(tb)\n yield\n yield\n self.assertEqual((yield tb.sda_i), 1)\n self.assertEqual((yield tb.scl_i), 1)\n", "method_code": " def write(self, data):\n yield self.dut.data_i.eq(data)\n yield from self.strobe(self.dut.write)\n ", "context": "class I2CInitiatorTestbench(I2CTestbench):\n def write(self, data): ...\n def __init__(self): ...\n def strobe(self, signal): ...\n def start(self): ...\n def stop(self): ...\n def read(self, ack): ...\n\n self.submodules.dut = I2CInitiator(pads=self, period_cyc=self.period_cyc)\n self.wait_cyc = self.period_cyc * 3\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000325.py"} {"focal_file": "software/glasgow/gateware/i2c.py", "focal_class": null, "focal_method": "write_octet", "tests": "import unittest\n\nclass Test_write_octet(unittest.TestCase):\n @simulation_test\n def test_write_shift(self, tb):\n yield from self.start_addr(tb, read=False)\n yield from tb.write_octet(165)\n yield tb.scl_o.eq(0)\n yield from self.assertCondition(tb, lambda: (yield tb.dut.write))\n self.assertEqual((yield tb.dut.data_i), 165)\n yield\n yield from self.assertState(tb, 'WRITE-ACK')\n\n @simulation_test\n def test_write_ack(self, tb):\n yield from self.start_addr(tb, read=False)\n yield from tb.write_octet(165)\n yield tb.scl_o.eq(0)\n yield\n yield\n yield\n yield tb.dut.ack_o.eq(1)\n yield\n self.assertEqual((yield tb.dut.write), 1)\n yield tb.dut.ack_o.eq(0)\n yield\n self.assertEqual((yield tb.dut.write), 0)\n yield from tb.half_period()\n yield tb.scl_o.eq(1)\n self.assertEqual((yield tb.sda_i), 0)\n\n @simulation_test\n def test_write_ack_stop(self, tb):\n yield from self.start_addr(tb, read=False)\n yield from tb.write_octet(165)\n self.assertEqual((yield from tb.read_bit()), 1)\n yield tb.scl_o.eq(0)\n yield tb.sda_o.eq(0)\n yield from tb.half_period()\n yield tb.scl_o.eq(1)\n yield from tb.half_period()\n yield tb.sda_o.eq(1)\n yield from self.assertCondition(tb, lambda: (yield tb.dut.stop))\n yield\n yield from self.assertState(tb, 'IDLE')\n", "method_code": " def write_octet(self, octet):\n for bit in range(8)[::-1]:\n yield from self.write_bit(octet >> bit & 1)\n ", "context": "class I2CTargetTestbench(I2CTestbench):\n def write_octet(self, octet): ...\n def __init__(self): ...\n def start(self): ...\n def rep_start(self): ...\n def stop(self): ...\n def write_bit(self, bit): ...\n def read_bit(self): ...\n def read_octet(self): ...\n\n self.submodules.dut = I2CTarget(pads=self)\n self.wait_cyc = self.period_cyc // 4\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000326.py"} {"focal_file": "software/glasgow/gateware/i2c.py", "focal_class": null, "focal_method": "read_octet", "tests": "import unittest\n\nclass Test_read_octet(unittest.TestCase):\n @simulation_test\n def test_read_ack(self, tb):\n yield tb.dut.data_o.eq(170)\n yield from self.start_addr(tb, read=True)\n self.assertEqual((yield from tb.read_octet()), 170)\n yield from tb.write_bit(0)\n yield from self.assertState(tb, 'READ-SHIFT')\n\n @simulation_test\n def test_read_ack_read(self, tb):\n yield tb.dut.data_o.eq(165)\n yield from self.start_addr(tb, read=True)\n self.assertEqual((yield from tb.read_octet()), 165)\n yield tb.dut.data_o.eq(51)\n yield from tb.write_bit(0)\n self.assertEqual((yield from tb.read_octet()), 51)\n yield from tb.write_bit(0)\n yield from self.assertState(tb, 'READ-SHIFT')\n", "method_code": " def read_octet(self):\n octet = 0\n for bit in range(8):\n octet = octet << 1 | (yield from self.read_bit())\n return octet\n ", "context": "class I2CTargetTestbench(I2CTestbench):\n def read_octet(self): ...\n def __init__(self): ...\n def start(self): ...\n def rep_start(self): ...\n def stop(self): ...\n def write_bit(self, bit): ...\n def write_octet(self, octet): ...\n def read_bit(self): ...\n\n self.submodules.dut = I2CTarget(pads=self)\n self.wait_cyc = self.period_cyc // 4\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000327.py"} {"focal_file": "software/glasgow/gateware/pads.py", "focal_class": null, "focal_method": "assertIsTriple", "tests": "import unittest\n\nclass Test_assertIsTriple(unittest.TestCase):\n def test_triple(self):\n tri = TSTriple()\n pads = Pads(sig=tri)\n self.assertIsTriple(pads.sig_t)\n self.assertEqual(pads.sig_t, tri)\n", "method_code": " def assertIsTriple(self, obj):\n self.assertIsInstance(obj, TSTriple)\n ", "context": "class PadsTestCase(unittest.TestCase):\n def assertIsTriple(self, obj): ...\n def assertHasTristate(self, frag, sig): ...\n def test_none(self): ...\n def test_signal(self): ...\n def test_signal_named(self): ...\n def test_triple(self): ...\n def test_triple_unnamed(self): ...\n def test_record(self): ...\n def test_record_named(self): ...\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_triple", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000328.py"} {"focal_file": "software/glasgow/protocol/jtag_svf.py", "focal_class": null, "focal_method": "last_command", "tests": "import unittest\n\nclass Test_last_command(unittest.TestCase):\n def test_last_command(self):\n handler = SVFMockEventHandler()\n parser = SVFParser(' TRST OFF; SIR 8 TDI (aa); ', handler)\n parser.parse_command()\n self.assertEqual(parser.last_command(), ' TRST OFF;')\n parser.parse_command()\n self.assertEqual(parser.last_command(), ' SIR 8 TDI (aa);')\n", "method_code": " def last_command(self):\n return self._lexer.buffer[self._cmd_pos:self._lexer.position]\n ", "context": "class SVFParser():\n def last_command(self): ...\n def __init__(self, buffer, handler): ...\n def _try(self, action, *args): ...\n def _parse_token(self): ...\n def _parse_error(self, error): ...\n def _parse_unexpected(self, expected, valid=()): ...\n def _parse_keyword(self, keyword): ...\n def _parse_keywords(self, keywords): ...\n def _parse_value(self, kind): ...\n def _parse_trst_mode(self): ...\n def _parse_tap_state(self): ...\n def _parse_tap_stable_state(self): ...\n def _parse_scan_data(self, length): ...\n def parse_command(self): ...\n def parse_file(self): ...\n\n self._lexer = SVFLexer(buffer)\n self._handler = handler\n self._position = 0\n self._token = None\n self._cmd_pos = 0\n self._param_tdi = {'HIR': None, 'HDR': None, 'SIR': None, 'SDR': None, 'TIR': None, 'TDR': None}\n self._param_mask = {'HIR': None, 'HDR': None, 'SIR': None, 'SDR': None, 'TIR': None, 'TDR': None}\n self._param_smask = {'HIR': None, 'HDR': None, 'SIR': None, 'SDR': None, 'TIR': None, 'TDR': None}\n self._param_run_state = 'IDLE'\n self._param_end_state = 'IDLE'\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_last_command", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000329.py"} {"focal_file": "software/glasgow/support/bitstruct.py", "focal_class": null, "focal_method": "to_bytes", "tests": "import unittest\n\nclass Test_to_bytes(unittest.TestCase):\n def test_bytes(self):\n bs = bitstruct('bs', 8, [('a', 3), ('b', 5)])\n x = bs(1, 2)\n self.assertIsInstance(x.to_bytes(), bytes)\n self.assertEqual(x.to_bytes(), b'\\x11')\n self.assertEqual(bs.from_bytes(x.to_bytes()), x)\n", "method_code": " def to_bytes(self):\n return bytes(self.to_bits())\n ", "context": "class _bitstruct():\n def to_bytes(self): ...\n def _check_bits_(action, expected_width, value): ...\n def _check_int_(action, expected_width, value): ...\n def _check_bytes_(action, expected_length, value): ...\n def _define_fields_(cls, declared_bits, fields): ...\n def from_bytes(cls, value): ...\n def from_int(cls, value): ...\n def bit_length(cls): ...\n def to_int(self): ...\n def to_bytearray(self): ...\n def copy(self): ...\n def bits_repr(self, omit_zero=False, omit_padding=True): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n\n __slots__ = ()\n from_bytearray = from_bytes\n __int__ = to_int\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_bytes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000330.py"} {"focal_file": "software/glasgow/support/bitstruct.py", "focal_class": null, "focal_method": "to_bytearray", "tests": "import unittest\n\nclass Test_to_bytearray(unittest.TestCase):\n def test_bytearray(self):\n bs = bitstruct('bs', 8, [('a', 3), ('b', 5)])\n x = bs(1, 2)\n self.assertIsInstance(x.to_bytearray(), bytearray)\n self.assertEqual(x.to_bytearray(), bytearray(b'\\x11'))\n self.assertEqual(bs.from_bytearray(x.to_bytearray()), x)\n", "method_code": " def to_bytearray(self):\n return bytearray(bytes(self.to_bits()))\n ", "context": "class _bitstruct():\n def to_bytearray(self): ...\n def _check_bits_(action, expected_width, value): ...\n def _check_int_(action, expected_width, value): ...\n def _check_bytes_(action, expected_length, value): ...\n def _define_fields_(cls, declared_bits, fields): ...\n def from_bytes(cls, value): ...\n def from_int(cls, value): ...\n def bit_length(cls): ...\n def to_int(self): ...\n def to_bytes(self): ...\n def copy(self): ...\n def bits_repr(self, omit_zero=False, omit_padding=True): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n\n __slots__ = ()\n from_bytearray = from_bytes\n __int__ = to_int\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_bytearray", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000331.py"} {"focal_file": "software/glasgow/support/bitstruct.py", "focal_class": null, "focal_method": "to_int", "tests": "import unittest\n\nclass Test_to_int(unittest.TestCase):\n def test_int(self):\n bs = bitstruct('bs', 8, [('a', 3), ('b', 5)])\n x = bs(1, 2)\n self.assertIsInstance(x.to_int(), int)\n self.assertEqual(x.to_int(), 17)\n self.assertEqual(bs.from_int(x.to_int()), x)\n", "method_code": " def to_int(self):\n return int(self.to_bits())\n ", "context": "class _bitstruct():\n def to_int(self): ...\n def _check_bits_(action, expected_width, value): ...\n def _check_int_(action, expected_width, value): ...\n def _check_bytes_(action, expected_length, value): ...\n def _define_fields_(cls, declared_bits, fields): ...\n def from_bytes(cls, value): ...\n def from_int(cls, value): ...\n def bit_length(cls): ...\n def to_bytes(self): ...\n def to_bytearray(self): ...\n def copy(self): ...\n def bits_repr(self, omit_zero=False, omit_padding=True): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n\n __slots__ = ()\n from_bytearray = from_bytes\n __int__ = to_int\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_int", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000332.py"} {"focal_file": "software/glasgow/support/bitstruct.py", "focal_class": null, "focal_method": "copy", "tests": "import unittest\n\nclass Test_copy(unittest.TestCase):\n def test_copy(self):\n bs = bitstruct('bs', 8, [('a', 3), ('b', 5)])\n x1 = bs(1, 2)\n x2 = x1.copy()\n self.assertFalse(x1 is x2)\n self.assertEqual(x1, x2)\n", "method_code": " def copy(self):\n return self.__class__.from_bits(self.to_bits())\n ", "context": "class _bitstruct():\n def copy(self): ...\n def _check_bits_(action, expected_width, value): ...\n def _check_int_(action, expected_width, value): ...\n def _check_bytes_(action, expected_length, value): ...\n def _define_fields_(cls, declared_bits, fields): ...\n def from_bytes(cls, value): ...\n def from_int(cls, value): ...\n def bit_length(cls): ...\n def to_int(self): ...\n def to_bytes(self): ...\n def to_bytearray(self): ...\n def bits_repr(self, omit_zero=False, omit_padding=True): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n\n __slots__ = ()\n from_bytearray = from_bytes\n __int__ = to_int\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_copy", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000333.py"} {"focal_file": "software/glasgow/support/bits.py", "focal_class": null, "focal_method": "from_int", "tests": "import unittest\n\nclass Test_from_int(unittest.TestCase):\n def test_from_int(self):\n self.assertBits(bits.from_int(0), 0, 0)\n self.assertBits(bits.from_int(1), 1, 1)\n self.assertBits(bits.from_int(2), 2, 2)\n self.assertBits(bits.from_int(2, 5), 5, 2)\n self.assertBits(bits.from_int(6, 2), 2, 2)\n self.assertBits(bits.from_int(-1, 16), 16, 65535)\n\n def test_from_int_wrong(self):\n with self.assertRaisesRegex(ValueError, \"invalid negative input for bits\\\\(\\\\): '-1'\"):\n bits.from_int(-1)\n", "method_code": " def from_int(cls, value, length=None):\n value = operator.index(value)\n if length is None:\n if value < 0:\n raise ValueError(\"invalid negative input for bits(): '{}'\".format(value))\n length = value.bit_length()\n else:\n length = operator.index(length)\n value &= ~(-1 << length)\n inst = object.__new__(cls)\n inst._len_ = length\n inst._int_ = value\n return inst\n ", "context": "class bits():\n @classmethod\n def from_int(cls, value, length=None): ...\n def from_str(cls, value): ...\n def from_iter(cls, iterator): ...\n def from_bytes(cls, value, length): ...\n def __new__(cls, value=0, length=None): ...\n def __len__(self): ...\n def __bool__(self): ...\n def to_int(self): ...\n def to_str(self): ...\n def to_bytes(self): ...\n def __repr__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __eq__(self, other): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __mul__(self, other): ...\n def __rmul__(self, other): ...\n def __and__(self, other): ...\n def __rand__(self, other): ...\n def __or__(self, other): ...\n def __ror__(self, other): ...\n def __xor__(self, other): ...\n def __rxor__(self, other): ...\n def reversed(self): ...\n def find(self, sub, start=0, end=-1): ...\n\n __slots__ = ['_len_', '_int_']\n __int__ = to_int\n __str__ = to_str\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_from_int", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000334.py"} {"focal_file": "software/glasgow/support/bits.py", "focal_class": null, "focal_method": "from_str", "tests": "import unittest\n\nclass Test_from_str(unittest.TestCase):\n def test_from_str(self):\n self.assertBits(bits.from_str(''), 0, 0)\n self.assertBits(bits.from_str('0'), 1, 0)\n self.assertBits(bits.from_str('010'), 3, 2)\n self.assertBits(bits.from_str('0 1 011_100'), 8, 92)\n self.assertBits(bits.from_str('+0 1 \\t011_100'), 8, 92)\n\n def test_from_str_wrong(self):\n with self.assertRaisesRegex(ValueError, \"invalid negative input for bits\\\\(\\\\): '-1'\"):\n bits.from_str('-1')\n with self.assertRaisesRegex(ValueError, \"invalid literal for int\\\\(\\\\) with base 2: '23'\"):\n bits.from_str('23')\n", "method_code": " def from_str(cls, value):\n value = re.sub('[\\\\s_]', '', value)\n if value:\n if value[0] == '-':\n raise ValueError(\"invalid negative input for bits(): '{}'\".format(value))\n elif value[0] == '+':\n length = len(value) - 1\n else:\n length = len(value)\n return cls.from_int(int(value, 2), length)\n else:\n return cls.from_int(0)\n ", "context": "class bits():\n @classmethod\n def from_str(cls, value): ...\n def from_int(cls, value, length=None): ...\n def from_iter(cls, iterator): ...\n def from_bytes(cls, value, length): ...\n def __new__(cls, value=0, length=None): ...\n def __len__(self): ...\n def __bool__(self): ...\n def to_int(self): ...\n def to_str(self): ...\n def to_bytes(self): ...\n def __repr__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __eq__(self, other): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __mul__(self, other): ...\n def __rmul__(self, other): ...\n def __and__(self, other): ...\n def __rand__(self, other): ...\n def __or__(self, other): ...\n def __ror__(self, other): ...\n def __xor__(self, other): ...\n def __rxor__(self, other): ...\n def reversed(self): ...\n def find(self, sub, start=0, end=-1): ...\n\n __slots__ = ['_len_', '_int_']\n __int__ = to_int\n __str__ = to_str\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_from_str", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000335.py"} {"focal_file": "software/glasgow/support/bits.py", "focal_class": null, "focal_method": "from_bytes", "tests": "import unittest\n\nclass Test_from_bytes(unittest.TestCase):\n def test_from_bytes(self):\n self.assertBits(bits.from_bytes(b'\\xa5', 8), 8, 165)\n self.assertBits(bits.from_bytes(b'\\xa5\\x01', 9), 9, 421)\n self.assertBits(bits.from_bytes(b'\\xa5\\xff', 9), 9, 421)\n", "method_code": " def from_bytes(cls, value, length):\n return cls.from_int(int.from_bytes(value, 'little'), length)\n ", "context": "class bits():\n @classmethod\n def from_bytes(cls, value, length): ...\n def from_int(cls, value, length=None): ...\n def from_str(cls, value): ...\n def from_iter(cls, iterator): ...\n def __new__(cls, value=0, length=None): ...\n def __len__(self): ...\n def __bool__(self): ...\n def to_int(self): ...\n def to_str(self): ...\n def to_bytes(self): ...\n def __repr__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __eq__(self, other): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __mul__(self, other): ...\n def __rmul__(self, other): ...\n def __and__(self, other): ...\n def __rand__(self, other): ...\n def __or__(self, other): ...\n def __ror__(self, other): ...\n def __xor__(self, other): ...\n def __rxor__(self, other): ...\n def reversed(self): ...\n def find(self, sub, start=0, end=-1): ...\n\n __slots__ = ['_len_', '_int_']\n __int__ = to_int\n __str__ = to_str\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_from_bytes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000336.py"} {"focal_file": "software/glasgow/support/bits.py", "focal_class": null, "focal_method": "from_iter", "tests": "import unittest\n\nclass Test_from_iter(unittest.TestCase):\n def test_from_iter(self):\n self.assertBits(bits.from_iter(iter([])), 0, 0)\n self.assertBits(bits.from_iter(iter([1, 1, 0, 1, 0, 0, 1])), 7, 75)\n", "method_code": " def from_iter(cls, iterator):\n length = -1\n value = 0\n for length, bit in enumerate(iterator):\n value |= bool(bit) << length\n return cls.from_int(value, length + 1)\n ", "context": "class bits():\n @classmethod\n def from_iter(cls, iterator): ...\n def from_int(cls, value, length=None): ...\n def from_str(cls, value): ...\n def from_bytes(cls, value, length): ...\n def __new__(cls, value=0, length=None): ...\n def __len__(self): ...\n def __bool__(self): ...\n def to_int(self): ...\n def to_str(self): ...\n def to_bytes(self): ...\n def __repr__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __eq__(self, other): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __mul__(self, other): ...\n def __rmul__(self, other): ...\n def __and__(self, other): ...\n def __rand__(self, other): ...\n def __or__(self, other): ...\n def __ror__(self, other): ...\n def __xor__(self, other): ...\n def __rxor__(self, other): ...\n def reversed(self): ...\n def find(self, sub, start=0, end=-1): ...\n\n __slots__ = ['_len_', '_int_']\n __int__ = to_int\n __str__ = to_str\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_from_iter", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000337.py"} {"focal_file": "software/glasgow/support/bits.py", "focal_class": "bits", "focal_method": "reversed", "tests": "import unittest\n\nclass Test_bits_reversed(unittest.TestCase):\n def test_reversed(self):\n self.assertBits(bits('1010').reversed(), 4, 5)\n", "method_code": " def reversed(self):\n value = 0\n for bit in range(self._len_):\n value <<= 1\n if self._int_ >> bit & 1:\n value |= 1\n return self.__class__(value, self._len_)\n ", "context": "class bits():\n def reversed(self): ...\n def from_int(cls, value, length=None): ...\n def from_str(cls, value): ...\n def from_iter(cls, iterator): ...\n def from_bytes(cls, value, length): ...\n def __new__(cls, value=0, length=None): ...\n def __len__(self): ...\n def __bool__(self): ...\n def to_int(self): ...\n def to_str(self): ...\n def to_bytes(self): ...\n def __repr__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __eq__(self, other): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __mul__(self, other): ...\n def __rmul__(self, other): ...\n def __and__(self, other): ...\n def __rand__(self, other): ...\n def __or__(self, other): ...\n def __ror__(self, other): ...\n def __xor__(self, other): ...\n def __rxor__(self, other): ...\n def find(self, sub, start=0, end=-1): ...\n\n __slots__ = ['_len_', '_int_']\n __int__ = to_int\n __str__ = to_str\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_reversed", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000338.py"} {"focal_file": "software/glasgow/support/bits.py", "focal_class": "bits", "focal_method": "find", "tests": "import unittest\n\nclass Test_bits_find(unittest.TestCase):\n def test_find(self):\n self.assertEqual(bits('1011').find(bits('11')), 0)\n self.assertEqual(bits('1011').find(bits('10')), 2)\n self.assertEqual(bits('1011').find(bits('01')), 1)\n self.assertEqual(bits('1011').find(bits('00')), -1)\n self.assertEqual(bits('101100101').find(bits('10'), 0), 1)\n self.assertEqual(bits('101100101').find(bits('10'), 2), 4)\n self.assertEqual(bits('101100101').find(bits('10'), 5), 7)\n self.assertEqual(bits('101100101').find(bits('10'), 8), -1)\n self.assertEqual(bits('1011').find(bits((1, 0))), 1)\n", "method_code": " def find(self, sub, start=0, end=-1):\n sub = self.__class__(sub)\n if start < 0:\n start = self._len_ - start\n if end < 0:\n end = self._len_ - end\n for pos in range(start, end):\n if self[pos:pos + len(sub)] == sub:\n return pos\n else:\n return -1\n ", "context": "class bits():\n def find(self, sub, start=0, end=-1): ...\n def from_int(cls, value, length=None): ...\n def from_str(cls, value): ...\n def from_iter(cls, iterator): ...\n def from_bytes(cls, value, length): ...\n def __new__(cls, value=0, length=None): ...\n def __len__(self): ...\n def __bool__(self): ...\n def to_int(self): ...\n def to_str(self): ...\n def to_bytes(self): ...\n def __repr__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __eq__(self, other): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __mul__(self, other): ...\n def __rmul__(self, other): ...\n def __and__(self, other): ...\n def __rand__(self, other): ...\n def __or__(self, other): ...\n def __ror__(self, other): ...\n def __xor__(self, other): ...\n def __rxor__(self, other): ...\n def reversed(self): ...\n\n __slots__ = ['_len_', '_int_']\n __int__ = to_int\n __str__ = to_str\n __bytes__ = to_bytes\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_find", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000339.py"} {"focal_file": "software/glasgow/support/chunked_fifo.py", "focal_class": null, "focal_method": "write", "tests": "import unittest\n\nclass Test_write(unittest.TestCase):\n def test_zero_write(self):\n self.fifo.write(b'')\n with self.assertRaises(IndexError):\n self.fifo.read()\n", "method_code": " def write(self, data):\n \"\"\"Enqueue ``data``.\"\"\"\n try:\n data = memoryview(data)\n except TypeError:\n data = memoryview(bytes(data))\n if not data:\n return\n self._length += len(data)\n self._wtotal += len(data)\n self._queue.append(data)\n ", "context": "class ChunkedFIFO():\n def write(self, data): ...\n def __init__(self): ...\n def clear(self): ...\n def read(self, max_length=None): ...\n def __bool__(self): ...\n def __len__(self): ...\n def total_read_bytes(self): ...\n def total_written_bytes(self): ...\n\n self._queue = deque()\n self._chunk = None\n self._offset = 0\n self._length = 0\n self._rtotal = 0\n self._wtotal = 0\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_zero_write", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000340.py"} {"focal_file": "software/glasgow/support/chunked_fifo.py", "focal_class": null, "focal_method": "read", "tests": "import unittest\n\nclass Test_read(unittest.TestCase):\n def test_zero_read(self):\n self.assertEqual(self.fifo.read(0), b'')\n self.fifo.write(b'A')\n self.assertEqual(self.fifo.read(0), b'')\n self.assertEqual(self.fifo.read(), b'A')\n", "method_code": " def read(self, max_length=None):\n \"\"\"\n Dequeue at most ``max_length`` bytes. If ``max_length`` is not specified, dequeue\n the maximum possible contiguous amount of bytes (at least one).\n \n Regardless of what was written into the FIFO, ``read`` always returns a ``memoryview``\n object.\n \"\"\"\n if max_length is None and self._chunk is None:\n chunk = self._queue.popleft()\n self._length -= len(chunk)\n self._rtotal += len(chunk)\n return chunk\n if max_length == 0:\n return memoryview(b'')\n if self._chunk is None:\n if not self._queue:\n return memoryview(b'')\n self._chunk = self._queue.popleft()\n self._offset = 0\n if max_length is None:\n result = self._chunk[self._offset:]\n else:\n result = self._chunk[self._offset:self._offset + max_length]\n if self._offset + len(result) == len(self._chunk):\n self._chunk = None\n else:\n self._offset += len(result)\n self._length -= len(result)\n self._rtotal += len(result)\n return result\n ", "context": "class ChunkedFIFO():\n def read(self, max_length=None): ...\n def __init__(self): ...\n def clear(self): ...\n def write(self, data): ...\n def __bool__(self): ...\n def __len__(self): ...\n def total_read_bytes(self): ...\n def total_written_bytes(self): ...\n\n self._queue = deque()\n self._chunk = None\n self._offset = 0\n self._length = 0\n self._rtotal = 0\n self._wtotal = 0\n", "repository": "GlasgowEmbedded/glasgow", "test_name": "test_zero_read", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000341.py"} {"focal_file": "src/alpskit/data.py", "focal_class": null, "focal_method": "measu_data_to_jss", "tests": "import unittest\n\nclass Test_measu_data_to_jss(unittest.TestCase):\n def test_measu_data_to_jss(self):\n measu_data1 = self.measu_data1\n measu_data1_jss_gt = self.measu_data1_jss\n measu_data1_jss = data.measu_data_to_jss(measu_data1)\n self.assertEqual(measu_data1_jss, measu_data1_jss_gt)\n", "method_code": "def measu_data_to_jss(data_set):\n \"\"\"Convert MeasuData obj to a json string.\n\n :data_set: MeasuData\n :returns: str\n JSON object string.\n\n \"\"\"\n return json.dumps(data_set, cls=MeasuDataJSONEncoder, indent=2)", "context": "def measu_data_to_jss(data_set): ...\ndef measu_data_to_jss(data_set): ...\ndef jss_to_measu_data(jss): ...\ndef measu_data_to_js(measu_data, js): ...\ndef js_to_measu_data(js): ...\ndef get_props(case_dir): ...\ndef get_chkp_dirs(case_dir): ...\ndef get_h5_files(case_dir): ...\ndef _get_files(case_dir, suffix): ...\n", "repository": "sun-rongyang/alpskit", "test_name": "test_measu_data_to_jss", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000342.py"} {"focal_file": "src/alpskit/data.py", "focal_class": null, "focal_method": "jss_to_measu_data", "tests": "import unittest\n\nclass Test_jss_to_measu_data(unittest.TestCase):\n def test_jss_to_measu_data(self):\n measu_data1_gt = self.measu_data1\n measu_data1_jss = self.measu_data1_jss\n measu_data1 = data.jss_to_measu_data(measu_data1_jss)\n np.testing.assert_array_equal(measu_data1.x, measu_data1_gt.x)\n np.testing.assert_array_equal(measu_data1.y, measu_data1_gt.y)\n self.assertEqual(measu_data1_gt.props, measu_data1.props)\n", "method_code": "def jss_to_measu_data(jss):\n \"\"\"Convert js string to a MeasuData obj.\n\n :jss: str\n JSON formatted string.\n :returns: MeasuData\n\n \"\"\"\n return json.loads(jss, cls=MeasuDataJSONDecoder)", "context": "def jss_to_measu_data(jss): ...\ndef measu_data_to_jss(data_set): ...\ndef jss_to_measu_data(jss): ...\ndef measu_data_to_js(measu_data, js): ...\ndef js_to_measu_data(js): ...\ndef get_props(case_dir): ...\ndef get_chkp_dirs(case_dir): ...\ndef get_h5_files(case_dir): ...\ndef _get_files(case_dir, suffix): ...\n", "repository": "sun-rongyang/alpskit", "test_name": "test_jss_to_measu_data", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000343.py"} {"focal_file": "src/alpskit/data.py", "focal_class": null, "focal_method": "get_props", "tests": "import unittest\n\nclass Test_get_props(unittest.TestCase):\n def test_get_props(self):\n props_dict = data.get_props(self.case1)\n self.assertEqual(props_dict, {'key1': 1, 'key2': 0.3, 'key3': 1e-05, 'key4': 'str', '#0': 'suffix'})\n", "method_code": "def get_props(case_dir):\n \"\"\"Get props dict for given simulation case results.\n\n :case_dir: str\n Simulation case directory.\n :returns: dict\n props dict.\n\n \"\"\"\n try:\n with open(case_dir + '/props.json', 'r') as fp:\n props_dict = json.load(fp)\n return props_dict['props']\n except IOError:\n return basename2dict(os.path.basename(case_dir))", "context": "def get_props(case_dir): ...\ndef measu_data_to_jss(data_set): ...\ndef jss_to_measu_data(jss): ...\ndef measu_data_to_js(measu_data, js): ...\ndef js_to_measu_data(js): ...\ndef get_props(case_dir): ...\ndef get_chkp_dirs(case_dir): ...\ndef get_h5_files(case_dir): ...\ndef _get_files(case_dir, suffix): ...\n", "repository": "sun-rongyang/alpskit", "test_name": "test_get_props", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000344.py"} {"focal_file": "src/alpskit/data.py", "focal_class": null, "focal_method": "get_chkp_dirs", "tests": "import unittest\n\nclass Test_get_chkp_dirs(unittest.TestCase):\n def test_get_chkp_dirs(self):\n chkps = data.get_chkp_dirs(self.case1)\n self.assertEqual(chkps, [self.chkp1])\n chkps = data.get_chkp_dirs(self.case2)\n self.assertEqual(chkps, [self.chkp21, self.chkp22])\n", "method_code": "def get_chkp_dirs(case_dir):\n \"\"\"Get *.chkp diectories from simulation case path.\n\n :case_dir: str\n Simulation case directory.\n :returns: list\n Each item is a chkp directory in the given simulation case.\n\n \"\"\"\n return _get_files(case_dir, '.chkp')", "context": "def get_chkp_dirs(case_dir): ...\ndef measu_data_to_jss(data_set): ...\ndef jss_to_measu_data(jss): ...\ndef measu_data_to_js(measu_data, js): ...\ndef js_to_measu_data(js): ...\ndef get_props(case_dir): ...\ndef get_chkp_dirs(case_dir): ...\ndef get_h5_files(case_dir): ...\ndef _get_files(case_dir, suffix): ...\n", "repository": "sun-rongyang/alpskit", "test_name": "test_get_chkp_dirs", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000345.py"} {"focal_file": "src/alpskit/data.py", "focal_class": null, "focal_method": "get_h5_files", "tests": "import unittest\n\nclass Test_get_h5_files(unittest.TestCase):\n def test_get_h5_files(self):\n h5 = data.get_h5_files(self.case1)\n self.assertEqual(h5, [self.h51])\n", "method_code": "def get_h5_files(case_dir):\n \"\"\"Get *.h5 files from simulation case path.\n\n :case_dir: str\n Simulation case directory.\n :returns: list\n Each item is a h5 file in the given simulation case.\n\n \"\"\"\n return _get_files(case_dir, '.h5')", "context": "def get_h5_files(case_dir): ...\ndef measu_data_to_jss(data_set): ...\ndef jss_to_measu_data(jss): ...\ndef measu_data_to_js(measu_data, js): ...\ndef js_to_measu_data(js): ...\ndef get_props(case_dir): ...\ndef get_chkp_dirs(case_dir): ...\ndef get_h5_files(case_dir): ...\ndef _get_files(case_dir, suffix): ...\n", "repository": "sun-rongyang/alpskit", "test_name": "test_get_h5_files", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000346.py"} {"focal_file": "namebot/normalization.py", "focal_class": null, "focal_method": "remove_odd_sounding_words", "tests": "import unittest\n\nclass Test_remove_odd_sounding_words(unittest.TestCase):\n def test_remove_odd_sounding_words(self):\n \"\"\"Test four nonsense inputs that should get\n captured by the regexes.\"\"\"\n original = ['bking', 'aaaeee', 'flower', 'rabbit']\n original_count = len(original)\n updated = norm.remove_odd_sounding_words(original)\n new_count = len(updated)\n self.assertEqual(new_count, original_count - 2)\n\n def test_no_remove_odd_sounding_words(self):\n \"\"\"Test bad inputs should not get removed.\"\"\"\n original = ['flower', 'rabbit']\n original_count = len(original)\n updated = norm.remove_odd_sounding_words(original)\n new_count = len(updated)\n self.assertEqual(new_count, original_count)\n\n def test_none_remove_odd_sounding_words(self):\n \"\"\"Test that no input is returned without looping\"\"\"\n original = None\n updated = norm.remove_odd_sounding_words(original)\n self.assertEqual(updated, original)\n\n def test_empty_remove_odd_sounding_words(self):\n \"\"\"Test that empty list is returned without looping\"\"\"\n original = []\n updated = norm.remove_odd_sounding_words(original)\n self.assertEqual(len(original), 0)\n self.assertEqual(original, updated)\n", "method_code": "def remove_odd_sounding_words(words):\n \"\"\"Remove random odd sounding word combinations via regular expressions.\n\n Args:\n words (list): The list of words\n\n Returns:\n list: An updated word list with words cleaned.\n \"\"\"\n odd_regexes = [re.compile('^a|e|i|o|u|y{3,6}'), re.compile('\\\\b[^aeiouys]k|zt|ksd|kd|zhr'), re.compile('\\\\bzt|ksd|kd|zhr')]\n cleaned = []\n if words is None or len(words) == 0:\n return words\n [cleaned.append(word) for word in words if not any((re.match(regex, word) for regex in odd_regexes))]\n return cleaned", "context": "def remove_odd_sounding_words(words): ...\ndef flatten(lst): ...\ndef remove_odd_sounding_words(words): ...\ndef stem_words(words): ...\ndef remove_stop_words(words): ...\ndef remove_bad_words(words): ...\ndef filter_words(words): ...\ndef uniquify(words): ...\ndef clean_sort(words): ...\ndef chop_duplicate_ends(word): ...\ndef key_words_by_pos_tag(words): ...\n", "repository": "christabor/namebot", "test_name": "test_remove_odd_sounding_words", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000347.py"} {"focal_file": "namebot/normalization.py", "focal_class": null, "focal_method": "stem_words", "tests": "import unittest\n\nclass Test_stem_words(unittest.TestCase):\n def test_stem_words(self):\n \"\"\"Test stemmer is working\"\"\"\n words = ['running', 'jumping']\n stemmed = norm.stem_words(words)\n self.assertEqual(['run', 'jump'], stemmed)\n\n def test_no_stem_words(self):\n \"\"\"Test stemmer is not stemming root words\"\"\"\n words = ['run', 'jump']\n stemmed = norm.stem_words(words)\n self.assertEqual(words, stemmed)\n", "method_code": "def stem_words(words):\n \"\"\"Stem words to their base linguistic stem to remove redundancy.\n\n Args:\n words (list): The list of words\n\n Returns:\n list: An updated word list with words stemmed.\n \"\"\"\n return [stem(word, stemmer=PORTER) for word in words]", "context": "def stem_words(words): ...\ndef flatten(lst): ...\ndef remove_odd_sounding_words(words): ...\ndef stem_words(words): ...\ndef remove_stop_words(words): ...\ndef remove_bad_words(words): ...\ndef filter_words(words): ...\ndef uniquify(words): ...\ndef clean_sort(words): ...\ndef chop_duplicate_ends(word): ...\ndef key_words_by_pos_tag(words): ...\n", "repository": "christabor/namebot", "test_name": "test_stem_words", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000348.py"} {"focal_file": "namebot/normalization.py", "focal_class": null, "focal_method": "filter_words", "tests": "import unittest\n\nclass Test_filter_words(unittest.TestCase):\n def test_filter_normal_words(self):\n \"\"\"Test that normal words are not filtered out\"\"\"\n long_words = ['notlong', 'short']\n words = long_words + ['normal', 'words']\n filtered = norm.filter_words(words)\n self.assertEqual(words, filtered)\n\n def test_filter_long_words(self):\n \"\"\"Test that very long words are filtered out\"\"\"\n long_words = ['areallyverylongword', 'anextrareallyverylongword']\n words = long_words + ['normal', 'words']\n filtered = norm.filter_words(words)\n for long_word in long_words:\n self.assertFalse(long_word in filtered)\n", "method_code": "def filter_words(words):\n \"\"\"Filter words by default min/max settings in the settings module.\n\n Args:\n words (list): The list of words\n\n Returns:\n list: The filtered words\n \"\"\"\n new_arr = []\n for word in words:\n if not re.search(' ', word):\n lte = len(word) <= namebot_settings.MAX_LENGTH\n gte = len(word) >= namebot_settings.MIN_LENGTH\n if all([lte, gte]):\n new_arr.append(word)\n elif re.search(' ', word):\n split = re.split(' ', word)\n split_join = []\n for chunks in split:\n length = len(chunks)\n lte = length <= namebot_settings.SPACED_MAX_LENGTH\n gte = length >= namebot_settings.MIN_LENGTH\n if all([lte, gte]):\n split_join.append(chunks)\n new_arr.append(' '.join(split_join))\n return new_arr", "context": "def filter_words(words): ...\ndef flatten(lst): ...\ndef remove_odd_sounding_words(words): ...\ndef stem_words(words): ...\ndef remove_stop_words(words): ...\ndef remove_bad_words(words): ...\ndef filter_words(words): ...\ndef uniquify(words): ...\ndef clean_sort(words): ...\ndef chop_duplicate_ends(word): ...\ndef key_words_by_pos_tag(words): ...\n", "repository": "christabor/namebot", "test_name": "test_filter_normal_words", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000349.py"} {"focal_file": "namebot/normalization.py", "focal_class": null, "focal_method": "uniquify", "tests": "import unittest\n\nclass Test_uniquify(unittest.TestCase):\n def test_uniquify(self):\n words = ['cool', 'neat', 'cool', 'cool', 'neat']\n updated = norm.uniquify(words)\n self.assertEqual(len(updated), 2)\n", "method_code": "def uniquify(words):\n \"\"\"Remove duplicates from a list.\n\n Args:\n words (list): The list of words\n\n Returns:\n list: An updated word list with duplicates removed.\n \"\"\"\n return {}.fromkeys(words).keys() if words is not None else words", "context": "def uniquify(words): ...\ndef flatten(lst): ...\ndef remove_odd_sounding_words(words): ...\ndef stem_words(words): ...\ndef remove_stop_words(words): ...\ndef remove_bad_words(words): ...\ndef filter_words(words): ...\ndef uniquify(words): ...\ndef clean_sort(words): ...\ndef chop_duplicate_ends(word): ...\ndef key_words_by_pos_tag(words): ...\n", "repository": "christabor/namebot", "test_name": "test_uniquify", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000350.py"} {"focal_file": "namebot/normalization.py", "focal_class": null, "focal_method": "clean_sort", "tests": "import unittest\n\nclass Test_clean_sort(unittest.TestCase):\n def test_clean_sort(self):\n words = ['!@foobar!#', 'ba3z!@#33_', 'bam!333____#33']\n cleaned = norm.clean_sort(words)\n self.assertEqual(cleaned, ['foobar', 'baz', 'bam'])\n", "method_code": "def clean_sort(words):\n \"\"\"A function for cleaning and prepping words for techniques.\n\n Args:\n words (list): The list of words\n\n Returns:\n list: An updated word list with words cleaned and sorted.\n \"\"\"\n if isinstance(words, basestring):\n return words\n chars = '!\"#$%\\'()*+,._/:;<=>?@[\\\\]^`{|}~01234567890'\n if words is not None:\n try:\n words = [word.strip().lower().translate(string.maketrans('', ''), chars) for word in words if len(word) > 1]\n except TypeError:\n pass\n return words", "context": "def clean_sort(words): ...\ndef flatten(lst): ...\ndef remove_odd_sounding_words(words): ...\ndef stem_words(words): ...\ndef remove_stop_words(words): ...\ndef remove_bad_words(words): ...\ndef filter_words(words): ...\ndef uniquify(words): ...\ndef clean_sort(words): ...\ndef chop_duplicate_ends(word): ...\ndef key_words_by_pos_tag(words): ...\n", "repository": "christabor/namebot", "test_name": "test_clean_sort", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000351.py"} {"focal_file": "namebot/nlp.py", "focal_class": null, "focal_method": "get_synsets", "tests": "import unittest\n\nclass Test_get_synsets(unittest.TestCase):\n def test_create_synset_basic(self):\n res = nlp.get_synsets(['potato'])\n self.assertIsInstance(res, dict)\n for synset, vals in res.iteritems():\n self.assertIsInstance(vals, dict)\n self.assertIsNotNone(synset)\n self.assertIsNotNone(vals)\n", "method_code": "def get_synsets(words, use_definitions=False, clean=False):\n \"\"\"Brute force loop on a synset ring to get all related words.\n\n You are expected to filter or remove any that are not relevant separately,\n if the resultant set is too long.\n The scoring module provides tools to filter based on pronunciation,\n but you can write your own and extend the functionality.\n\n :param words (list): The list of words.\n :param use_definitions (bool, optional): Determine if definition words\n should also be extracted.\n :param clean (bool, optional): Determine if set should be de-duped,\n cleaned, etc...\n :rtype results (dict): The results dictionary.\n \"\"\"\n results = {}\n for word in words:\n synsets = get_word_synsets(word)\n key = {'synset_original': []}\n for synset in synsets:\n if hasattr(synset.lemma_names, '__call__'):\n key['synset_original'].append(synset.lemma_names())\n else:\n key['synset_original'].append(synset.lemma_names)\n key['hyponyms'] = get_hyponyms(synset, use_definitions=use_definitions)\n key['instance_hyponyms'] = get_inst_hyponyms(synset, use_definitions=use_definitions)\n key['member_meronyms'] = get_member_meronyms(synset, use_definitions=use_definitions)\n key['substance_meronyms'] = get_substance_meronyms(synset, use_definitions=use_definitions)\n key['part_meronyms'] = get_part_meronyms(synset, use_definitions=use_definitions)\n key['substance_holonyms'] = get_substance_holoynms(synset, use_definitions=use_definitions)\n key['member_holonyms'] = get_member_holoynms(synset, use_definitions=use_definitions)\n key['part_holonyms'] = get_part_holoynms(synset, use_definitions=use_definitions)\n key['instance_hypernyms'] = get_instance_hypernyms(synset, use_definitions=use_definitions)\n key['hypernyms'] = get_hypernyms(synset, use_definitions=use_definitions)\n key['topic_domains'] = get_topic_domains(synset, use_definitions=use_definitions)\n key['region_domains'] = get_region_domains(synset, use_definitions=use_definitions)\n key['usage_domains'] = get_usage_domains(synset, use_definitions=use_definitions)\n key['attributes'] = get_attributes(synset, use_definitions=use_definitions)\n key['entailments'] = get_entailments(synset, use_definitions=use_definitions)\n key['causes'] = get_causes(synset, use_definitions=use_definitions)\n key['also_sees'] = get_also_sees(synset, use_definitions=use_definitions)\n key['verb_groups'] = get_verb_groups(synset, use_definitions=use_definitions)\n key['similar_tos'] = get_similartos(synset, use_definitions=use_definitions)\n results[word] = key\n for nlp_type in results:\n if clean:\n results[nlp_type] = sorted(normalization.uniquify(normalization.clean_sort(normalization.remove_stop_words(normalization.stem_words(normalization.remove_bad_words(list(itertools.chain(*results[nlp_type]))))))))\n return results", "context": "def get_synsets(words, use_definitions=False, clean=False): ...\ndef _get_synset_words(word): ...\ndef print_all_synset_categories(): ...\ndef _get_lemma_names(sub_synset, use_definitions=False): ...\ndef get_hyponyms(synset, use_definitions=False): ...\ndef get_inst_hyponyms(synset, use_definitions=False): ...\ndef get_member_meronyms(synset, use_definitions=False): ...\ndef get_substance_meronyms(synset, use_definitions=False): ...\ndef get_part_meronyms(synset, use_definitions=False): ...\ndef get_substance_holoynms(synset, use_definitions=False): ...\ndef get_topic_domains(synset, use_definitions=False): ...\ndef get_region_domains(synset, use_definitions=False): ...\ndef get_usage_domains(synset, use_definitions=False): ...\ndef get_attributes(synset, use_definitions=False): ...\ndef get_entailments(synset, use_definitions=False): ...\ndef get_causes(synset, use_definitions=False): ...\ndef get_also_sees(synset, use_definitions=False): ...\ndef get_verb_groups(synset, use_definitions=False): ...\ndef get_similartos(synset, use_definitions=False): ...\ndef get_member_holoynms(synset, use_definitions=False): ...\ndef get_part_holoynms(synset, use_definitions=False): ...\ndef get_instance_hypernyms(synset, use_definitions=False): ...\ndef get_hypernyms(synset, use_definitions=False): ...\ndef get_verb_lemmas(verbs): ...\ndef get_word_synsets(word): ...\ndef get_synset_definitions(word): ...\ndef get_synsets_definitions(words): ...\ndef get_synsets(words, use_definitions=False, clean=False): ...\n", "repository": "christabor/namebot", "test_name": "test_create_synset_basic", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000352.py"} {"focal_file": "namebot/nlp.py", "focal_class": null, "focal_method": "get_synsets_definitions", "tests": "import unittest\n\nclass Test_get_synsets_definitions(unittest.TestCase):\n def test_get_synsets_definitions(self):\n res = nlp.get_synsets_definitions(['potato'])\n self.assertIsInstance(res, list)\n self.assertGreater(len(res), 0)\n", "method_code": "def get_synsets_definitions(words):\n \"\"\"Return all possible definitions for all synsets in the synset ring.\n\n :param words (list): The list of words.\n :rtype sets (list): The synsets.\n \"\"\"\n return [get_synset_definitions(w) for w in words if w]", "context": "def get_synsets_definitions(words): ...\ndef _get_synset_words(word): ...\ndef print_all_synset_categories(): ...\ndef _get_lemma_names(sub_synset, use_definitions=False): ...\ndef get_hyponyms(synset, use_definitions=False): ...\ndef get_inst_hyponyms(synset, use_definitions=False): ...\ndef get_member_meronyms(synset, use_definitions=False): ...\ndef get_substance_meronyms(synset, use_definitions=False): ...\ndef get_part_meronyms(synset, use_definitions=False): ...\ndef get_substance_holoynms(synset, use_definitions=False): ...\ndef get_topic_domains(synset, use_definitions=False): ...\ndef get_region_domains(synset, use_definitions=False): ...\ndef get_usage_domains(synset, use_definitions=False): ...\ndef get_attributes(synset, use_definitions=False): ...\ndef get_entailments(synset, use_definitions=False): ...\ndef get_causes(synset, use_definitions=False): ...\ndef get_also_sees(synset, use_definitions=False): ...\ndef get_verb_groups(synset, use_definitions=False): ...\ndef get_similartos(synset, use_definitions=False): ...\ndef get_member_holoynms(synset, use_definitions=False): ...\ndef get_part_holoynms(synset, use_definitions=False): ...\ndef get_instance_hypernyms(synset, use_definitions=False): ...\ndef get_hypernyms(synset, use_definitions=False): ...\ndef get_verb_lemmas(verbs): ...\ndef get_word_synsets(word): ...\ndef get_synset_definitions(word): ...\ndef get_synsets_definitions(words): ...\ndef get_synsets(words, use_definitions=False, clean=False): ...\n", "repository": "christabor/namebot", "test_name": "test_get_synsets_definitions", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000353.py"} {"focal_file": "namebot/nlp.py", "focal_class": null, "focal_method": "get_verb_lemmas", "tests": "import unittest\n\nclass Test_get_verb_lemmas(unittest.TestCase):\n def test_get_verb_lemmas(self):\n res = nlp.get_verb_lemmas(['flying', 'crying', 'dying'])\n self.assertGreater(len(res), 0)\n for word in res:\n self.assertIsInstance(word, unicode)\n\n def test_get_verb_lemmas_noverbs(self):\n res = nlp.get_verb_lemmas(['cat', 'dog', 'parrot'])\n self.assertEqual(len(res), 0)\n", "method_code": "def get_verb_lemmas(verbs):\n \"\"\"Return verbnet lemmas for the given verbs.\n\n These verbs are stemmed before lookup to prevent empty results.\n\n :param verbs (list) - The list of verbs (verbs) to reference.\n :rtype lemmas (list) - A list of lemmas for all verbs\n - these are not separated by verb.\n \"\"\"\n lemmas = []\n for verb in normalization.stem_words(verbs):\n _lemmas = verbnet.classids(lemma=verb)\n lemmas += [l.split('-')[0] for l in _lemmas]\n return lemmas", "context": "def get_verb_lemmas(verbs): ...\ndef _get_synset_words(word): ...\ndef print_all_synset_categories(): ...\ndef _get_lemma_names(sub_synset, use_definitions=False): ...\ndef get_hyponyms(synset, use_definitions=False): ...\ndef get_inst_hyponyms(synset, use_definitions=False): ...\ndef get_member_meronyms(synset, use_definitions=False): ...\ndef get_substance_meronyms(synset, use_definitions=False): ...\ndef get_part_meronyms(synset, use_definitions=False): ...\ndef get_substance_holoynms(synset, use_definitions=False): ...\ndef get_topic_domains(synset, use_definitions=False): ...\ndef get_region_domains(synset, use_definitions=False): ...\ndef get_usage_domains(synset, use_definitions=False): ...\ndef get_attributes(synset, use_definitions=False): ...\ndef get_entailments(synset, use_definitions=False): ...\ndef get_causes(synset, use_definitions=False): ...\ndef get_also_sees(synset, use_definitions=False): ...\ndef get_verb_groups(synset, use_definitions=False): ...\ndef get_similartos(synset, use_definitions=False): ...\ndef get_member_holoynms(synset, use_definitions=False): ...\ndef get_part_holoynms(synset, use_definitions=False): ...\ndef get_instance_hypernyms(synset, use_definitions=False): ...\ndef get_hypernyms(synset, use_definitions=False): ...\ndef get_verb_lemmas(verbs): ...\ndef get_word_synsets(word): ...\ndef get_synset_definitions(word): ...\ndef get_synsets_definitions(words): ...\ndef get_synsets(words, use_definitions=False, clean=False): ...\n", "repository": "christabor/namebot", "test_name": "test_get_verb_lemmas", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000354.py"} {"focal_file": "namebot/strainer.py", "focal_class": null, "focal_method": "filter_length", "tests": "import unittest\n\nclass Test_filter_length(unittest.TestCase):\n def test_no_filter(self):\n \"\"\"Basic sanity test - no filtering should be done.\"\"\"\n strained = [word for word in self.words if strain.filter_length(word, min_length=0, max_length=99999)]\n self.assertEqual(len(self.words), len(strained))\n\n def test_min_length(self):\n \"\"\"Test filtering function for length\"\"\"\n strained = [word for word in self.words if strain.filter_length(word, min_length=4, max_length=999)]\n self.assertEqual(len(strained), 5)\n\n def test_max_length(self):\n \"\"\"Test filtering function for length\"\"\"\n strained = [word for word in self.words if strain.filter_length(word, min_length=0, max_length=3)]\n self.assertEqual(len(strained), 6)\n", "method_code": "def filter_length(word, min_length=namebot_settings.MIN_LENGTH, max_length=namebot_settings.MAX_LENGTH):\n \"\"\"Filter based on min and max lengths.\n\n :param word (str): The word.\n :param min_length (int, optional): The minimum allowed length.\n :param max_length (int, optional): The maximum allowed length.\n :rtype: bool: The resulting check.\n \"\"\"\n return len(word) >= min_length and len(word) <= max_length", "context": "def filter_length(word, min_length=namebot_settings.MIN_LENGTH, max_length=namebot_settings.MAX_LENGTH): ...\ndef filter_vowel_cons_ratio(word, ratio=0.5): ...\ndef filter_length(word, min_length=namebot_settings.MIN_LENGTH, max_length=namebot_settings.MAX_LENGTH): ...\ndef filter_startswith(word, beginning=None): ...\ndef filter_endswith(word, ending=None): ...\ndef filter_tld(word, tld='.com'): ...\ndef filter_dmetaphone(word, code=None): ...\ndef filter_soundex(word, code=None): ...\ndef filter_nysiis(word, code=None): ...\ndef filter_consonant_ending(word): ...\ndef filter_vowel_ending(word): ...\n", "repository": "christabor/namebot", "test_name": "test_no_filter", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000355.py"} {"focal_file": "namebot/strainer.py", "focal_class": null, "focal_method": "filter_startswith", "tests": "import unittest\n\nclass Test_filter_startswith(unittest.TestCase):\n def test_startswith(self):\n \"\"\"Test if a word starts with a specific letter\"\"\"\n strained = [word for word in self.words if strain.filter_startswith(word, beginning='b')]\n self.assertEqual(len(strained), 3)\n", "method_code": "def filter_startswith(word, beginning=None):\n \"\"\"Filter a word starting with specified string.\n\n :param word (str): The word.\n :param beginning (str, optional): The beginning string to check.\n :rtype: bool: The resulting check.\n \"\"\"\n return word.lower().startswith(beginning)", "context": "def filter_startswith(word, beginning=None): ...\ndef filter_vowel_cons_ratio(word, ratio=0.5): ...\ndef filter_length(word, min_length=namebot_settings.MIN_LENGTH, max_length=namebot_settings.MAX_LENGTH): ...\ndef filter_startswith(word, beginning=None): ...\ndef filter_endswith(word, ending=None): ...\ndef filter_tld(word, tld='.com'): ...\ndef filter_dmetaphone(word, code=None): ...\ndef filter_soundex(word, code=None): ...\ndef filter_nysiis(word, code=None): ...\ndef filter_consonant_ending(word): ...\ndef filter_vowel_ending(word): ...\n", "repository": "christabor/namebot", "test_name": "test_startswith", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000356.py"} {"focal_file": "namebot/strainer.py", "focal_class": null, "focal_method": "filter_endswith", "tests": "import unittest\n\nclass Test_filter_endswith(unittest.TestCase):\n def test_endswith(self):\n \"\"\"Test if a word ends with a specific letter\"\"\"\n strained = [word for word in self.words if strain.filter_endswith(word, ending='e')]\n self.assertEqual(len(strained), 2)\n", "method_code": "def filter_endswith(word, ending=None):\n \"\"\"Filter words ending with a specified suffix.\n\n :param word (str): A word.\n :param ending (str, optional): The optional ending to check.\n :rtype bool: The resulting check.\n \"\"\"\n return word.lower().endswith(ending)", "context": "def filter_endswith(word, ending=None): ...\ndef filter_vowel_cons_ratio(word, ratio=0.5): ...\ndef filter_length(word, min_length=namebot_settings.MIN_LENGTH, max_length=namebot_settings.MAX_LENGTH): ...\ndef filter_startswith(word, beginning=None): ...\ndef filter_endswith(word, ending=None): ...\ndef filter_tld(word, tld='.com'): ...\ndef filter_dmetaphone(word, code=None): ...\ndef filter_soundex(word, code=None): ...\ndef filter_nysiis(word, code=None): ...\ndef filter_consonant_ending(word): ...\ndef filter_vowel_ending(word): ...\n", "repository": "christabor/namebot", "test_name": "test_endswith", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000357.py"} {"focal_file": "namebot/strainer.py", "focal_class": null, "focal_method": "filter_nysiis", "tests": "import unittest\n\nclass Test_filter_nysiis(unittest.TestCase):\n def test_filter_one(self):\n res = [w for w in self.words if strain.filter_nysiis(w, code='INPRABABL')]\n self.assertEqual(res, ['improbable'])\n", "method_code": "def filter_nysiis(word, code=None):\n \"\"\"Get nysiis value, checking score.\n\n :param word (str): The word.\n :param code (str, optional): The nysiis pronunciation code.\n :rtype bool: The resulting check.\n \"\"\"\n if code is None:\n return True\n retcode = scoring.score_nysiis([word])[0].split(':')[1].strip().lower()\n return retcode == code.lower()", "context": "def filter_nysiis(word, code=None): ...\ndef filter_vowel_cons_ratio(word, ratio=0.5): ...\ndef filter_length(word, min_length=namebot_settings.MIN_LENGTH, max_length=namebot_settings.MAX_LENGTH): ...\ndef filter_startswith(word, beginning=None): ...\ndef filter_endswith(word, ending=None): ...\ndef filter_tld(word, tld='.com'): ...\ndef filter_dmetaphone(word, code=None): ...\ndef filter_soundex(word, code=None): ...\ndef filter_nysiis(word, code=None): ...\ndef filter_consonant_ending(word): ...\ndef filter_vowel_ending(word): ...\n", "repository": "christabor/namebot", "test_name": "test_filter_one", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000358.py"} {"focal_file": "namebot/strainer.py", "focal_class": null, "focal_method": "filter_dmetaphone", "tests": "import unittest\n\nclass Test_filter_dmetaphone(unittest.TestCase):\n def test_filter_double(self):\n res = [w for w in self.words + ['improbable'] if strain.filter_dmetaphone(w, code='AMPR')]\n self.assertEqual(res, ['improbable', 'improbable'])\n", "method_code": "def filter_dmetaphone(word, code=None):\n \"\"\"Get double metaphone value, checking score.\n\n Where second key being None, an easy pronunciation is unlikely.\n\n :param word (str): The word.\n :param code (str, optional): The double metaphone pronunciation code.\n\n :rtype bool: The resulting check.\n \"\"\"\n score = scoring.score_dmetaphone([word])[0]\n _, pronunciation, dmcode = score.split(':')\n if code is None:\n return True\n return pronunciation.lower() == code.lower()", "context": "def filter_dmetaphone(word, code=None): ...\ndef filter_vowel_cons_ratio(word, ratio=0.5): ...\ndef filter_length(word, min_length=namebot_settings.MIN_LENGTH, max_length=namebot_settings.MAX_LENGTH): ...\ndef filter_startswith(word, beginning=None): ...\ndef filter_endswith(word, ending=None): ...\ndef filter_tld(word, tld='.com'): ...\ndef filter_dmetaphone(word, code=None): ...\ndef filter_soundex(word, code=None): ...\ndef filter_nysiis(word, code=None): ...\ndef filter_consonant_ending(word): ...\ndef filter_vowel_ending(word): ...\n", "repository": "christabor/namebot", "test_name": "test_filter_double", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000359.py"} {"focal_file": "namebot/strainer.py", "focal_class": null, "focal_method": "filter_consonant_ending", "tests": "import unittest\n\nclass Test_filter_consonant_ending(unittest.TestCase):\n def test_filter_none(self):\n words = ['foo', 'neato']\n res = [w for w in words if strain.filter_consonant_ending(w)]\n self.assertEqual(res, [])\n\n def test_filter_some(self):\n words = ['bar', 'baz', 'foo']\n res = [w for w in words if strain.filter_consonant_ending(w)]\n self.assertEqual(res, ['bar', 'baz'])\n", "method_code": "def filter_consonant_ending(word):\n \"\"\"Filter words that end in consonants.\n\n :param word (str): The word to filter.\n :rtype match (bool): An re.MatchObject or None.\n \"\"\"\n cons = namebot_settings.regexes['consonant_ending']\n return re.search(cons, word[-1]) is not None", "context": "def filter_consonant_ending(word): ...\ndef filter_vowel_cons_ratio(word, ratio=0.5): ...\ndef filter_length(word, min_length=namebot_settings.MIN_LENGTH, max_length=namebot_settings.MAX_LENGTH): ...\ndef filter_startswith(word, beginning=None): ...\ndef filter_endswith(word, ending=None): ...\ndef filter_tld(word, tld='.com'): ...\ndef filter_dmetaphone(word, code=None): ...\ndef filter_soundex(word, code=None): ...\ndef filter_nysiis(word, code=None): ...\ndef filter_consonant_ending(word): ...\ndef filter_vowel_ending(word): ...\n", "repository": "christabor/namebot", "test_name": "test_filter_none", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000360.py"} {"focal_file": "namebot/techniques_language.py", "focal_class": null, "focal_method": "lookup_latin_word", "tests": "import unittest\n\nclass Test_lookup_latin_word(unittest.TestCase):\n def test_lookup_none(self):\n self.assertEqual(tl.lookup_latin_word(None), [])\n\n def test_lookup_basic(self):\n self.assertEqual(tl.lookup_latin_word('cool'), [['tepesco']])\n\n def test_lookup_basic_multi_results(self):\n self.assertEqual(tl.lookup_latin_word('elevate'), [['extollo'], ['attollo'], ['tollo', 'sustuli', 'sublatum']])\n", "method_code": "def lookup_latin_word(word):\n \"\"\"Search the latin word list for any matches for the given `word`.\n\n Args:\n word (str) - The word to search for\n\n Returns:\n results (list) - A nested list with each matching definition(s) group.\n \"\"\"\n results = []\n if not word:\n return results\n for lword, keywords in lwords.iteritems():\n if word in keywords:\n results.append(lword.split(','))\n return results", "context": "def lookup_latin_word(word): ...\ndef lookup_latin_word(word): ...\ndef lookup_latin_words(words): ...\n", "repository": "christabor/namebot", "test_name": "test_lookup_none", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000361.py"} {"focal_file": "namebot/techniques_language.py", "focal_class": null, "focal_method": "lookup_latin_words", "tests": "import unittest\n\nclass Test_lookup_latin_words(unittest.TestCase):\n def test_lookup_multiple_words(self):\n self.assertEqual(tl.lookup_latin_words(['cool', 'no-word']), [[['tepesco']], []])\n\n def test_lookup_multiple_words_empty(self):\n self.assertEqual(tl.lookup_latin_words([]), [])\n\n def test_lookup_multiple_words_none(self):\n self.assertEqual(tl.lookup_latin_words(None), [])\n\n def test_lookup_multiple_words_nested_results(self):\n results = tl.lookup_latin_words(['cool'])\n for result in results:\n self.assertIsInstance(result, list)\n", "method_code": "def lookup_latin_words(words):\n \"\"\"Look up the matching latin definitions for a list of words.\n\n Args:\n words (list): A list of words.\n\n Returns:\n results (list): The updated list.\n \"\"\"\n results = []\n if not words:\n return results\n for word in words:\n results.append(lookup_latin_word(word))\n return results", "context": "def lookup_latin_words(words): ...\ndef lookup_latin_word(word): ...\ndef lookup_latin_words(words): ...\n", "repository": "christabor/namebot", "test_name": "test_lookup_multiple_words", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000362.py"} {"focal_file": "namebot/techniques.py", "focal_class": null, "focal_method": "duplifixify", "tests": "import unittest\n\nclass Test_duplifixify(unittest.TestCase):\n def test_duplifix(self):\n res = techniques.duplifixify(self.words)\n self.assertEqual(res[:3], ['shop ahop', 'shop bhop', 'shop chop'])\n", "method_code": "def duplifixify(words):\n \"\"\"Apply a duplifix technique to a set of words (e.g: teeny weeny, etc...).\n\n :param words (list) - The list of words to operate on.\n :rtype new_arr (list): the updated *fixed words\n \"\"\"\n new_arr = []\n for word in words:\n if not word:\n continue\n for letter in _alphabet:\n duplicate_word = '{}{}'.format(letter, word[1:]) == word\n if word[0] is not letter and (not duplicate_word):\n new_arr.append('{} {}{}'.format(word, letter, word[1:]))\n return new_arr", "context": "def duplifixify(words): ...\ndef slice_ends(word, count=1): ...\ndef domainify(words, tld='com'): ...\ndef spoonerism(words): ...\ndef kniferism(words): ...\ndef forkerism(words): ...\ndef reduplication_ablaut(words, count=1, random=True, vowel='e'): ...\ndef prefixify(words): ...\ndef suffixify(words): ...\ndef duplifixify(words): ...\ndef disfixify(words, replaces=1): ...\ndef infixify(words): ...\ndef simulfixify(words, pairs=None, max=5): ...\ndef palindrome(word): ...\ndef palindromes(words): ...\ndef make_founder_product_name(founder1, founder2, product): ...\ndef make_name_alliteration(words, divider=' '): ...\ndef make_name_abbreviation(words): ...\ndef make_vowel(words, vowel_type, vowel_index): ...\ndef make_portmanteau_default_vowel(words): ...\ndef make_portmanteau_split(words): ...\ndef make_punctuator(words, replace): ...\ndef make_punctuator_vowels(words): ...\ndef make_vowelify(words): ...\ndef make_misspelling(words): ...\ndef _pig_latinize(word, postfix='ay'): ...\ndef pig_latinize(words, postfix='ay'): ...\ndef acronym_lastname(description, lastname): ...\ndef get_descriptors(words): ...\ndef _add_pos_subtypes(nouns, verbs): ...\ndef _create_pos_subtypes(words): ...\ndef make_descriptors(words): ...\ndef all_prefix_first_vowel(word, letters=list(ascii_uppercase)): ...\ndef recycle(words, func, times=2): ...\ndef backronym(acronym, theme, max_attempts=10): ...\ndef super_scrub(data): ...\ndef generate_all_techniques(words): ...\n", "repository": "christabor/namebot", "test_name": "test_duplifix", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000363.py"} {"focal_file": "namebot/techniques.py", "focal_class": null, "focal_method": "simulfixify", "tests": "import unittest\n\nclass Test_simulfixify(unittest.TestCase):\n def test_simulfix(self):\n res = techniques.simulfixify(self.words)\n self.assertIsInstance(res, list)\n self.assertGreater(len(res), len(self.words))\n for word in res:\n self.assertEqual(len(self.words[0]) + 2, len(word))\n", "method_code": "def simulfixify(words, pairs=None, max=5):\n \"\"\"Generate simulfixed words.\n\n Args:\n words (list) - List of words to operate on.\n pairs (list, optional) - Simulfix pairs to use for each word.\n If not specified, these will be generated\n randomly as vowel + consonant strings.\n max (int, optional): The number of simulfix pairs to generate\n (if pairs is not specified.)\n\n Returns:\n results (list) - The simulfix version of each word,\n for each simulfix pair.\n \"\"\"\n results = []\n if pairs is None:\n pairs = ['{}{}'.format(choice(_vowels), choice(_consonants)) for _ in range(max)]\n for word in words:\n for combo in pairs:\n mid = len(word) // 2\n _word = '{}{}{}'.format(word[0:mid], combo, word[mid:])\n results.append(_word)\n return results", "context": "def simulfixify(words, pairs=None, max=5): ...\ndef slice_ends(word, count=1): ...\ndef domainify(words, tld='com'): ...\ndef spoonerism(words): ...\ndef kniferism(words): ...\ndef forkerism(words): ...\ndef reduplication_ablaut(words, count=1, random=True, vowel='e'): ...\ndef prefixify(words): ...\ndef suffixify(words): ...\ndef duplifixify(words): ...\ndef disfixify(words, replaces=1): ...\ndef infixify(words): ...\ndef simulfixify(words, pairs=None, max=5): ...\ndef palindrome(word): ...\ndef palindromes(words): ...\ndef make_founder_product_name(founder1, founder2, product): ...\ndef make_name_alliteration(words, divider=' '): ...\ndef make_name_abbreviation(words): ...\ndef make_vowel(words, vowel_type, vowel_index): ...\ndef make_portmanteau_default_vowel(words): ...\ndef make_portmanteau_split(words): ...\ndef make_punctuator(words, replace): ...\ndef make_punctuator_vowels(words): ...\ndef make_vowelify(words): ...\ndef make_misspelling(words): ...\ndef _pig_latinize(word, postfix='ay'): ...\ndef pig_latinize(words, postfix='ay'): ...\ndef acronym_lastname(description, lastname): ...\ndef get_descriptors(words): ...\ndef _add_pos_subtypes(nouns, verbs): ...\ndef _create_pos_subtypes(words): ...\ndef make_descriptors(words): ...\ndef all_prefix_first_vowel(word, letters=list(ascii_uppercase)): ...\ndef recycle(words, func, times=2): ...\ndef backronym(acronym, theme, max_attempts=10): ...\ndef super_scrub(data): ...\ndef generate_all_techniques(words): ...\n", "repository": "christabor/namebot", "test_name": "test_simulfix", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000364.py"} {"focal_file": "namebot/techniques.py", "focal_class": null, "focal_method": "pig_latinize", "tests": "import unittest\n\nclass Test_pig_latinize(unittest.TestCase):\n def test_pig_latinize(self):\n words = techniques.pig_latinize(['purring', 'cats'])\n self.assertEqual(techniques.recycle(words, techniques.pig_latinize), ['urringpaywayway', 'atscaywayway'])\n", "method_code": "def pig_latinize(words, postfix='ay'):\n \"\"\"Pig latinize a set of words.\n\n Args:\n words (list): A list of words.\n postfix (str, optional): A postfix to use. Default is `ay`.\n\n Returns:\n words (list): The updated list.\n\n \"\"\"\n return [_pig_latinize(word, postfix=postfix) for word in words]", "context": "def pig_latinize(words, postfix='ay'): ...\ndef slice_ends(word, count=1): ...\ndef domainify(words, tld='com'): ...\ndef spoonerism(words): ...\ndef kniferism(words): ...\ndef forkerism(words): ...\ndef reduplication_ablaut(words, count=1, random=True, vowel='e'): ...\ndef prefixify(words): ...\ndef suffixify(words): ...\ndef duplifixify(words): ...\ndef disfixify(words, replaces=1): ...\ndef infixify(words): ...\ndef simulfixify(words, pairs=None, max=5): ...\ndef palindrome(word): ...\ndef palindromes(words): ...\ndef make_founder_product_name(founder1, founder2, product): ...\ndef make_name_alliteration(words, divider=' '): ...\ndef make_name_abbreviation(words): ...\ndef make_vowel(words, vowel_type, vowel_index): ...\ndef make_portmanteau_default_vowel(words): ...\ndef make_portmanteau_split(words): ...\ndef make_punctuator(words, replace): ...\ndef make_punctuator_vowels(words): ...\ndef make_vowelify(words): ...\ndef make_misspelling(words): ...\ndef _pig_latinize(word, postfix='ay'): ...\ndef pig_latinize(words, postfix='ay'): ...\ndef acronym_lastname(description, lastname): ...\ndef get_descriptors(words): ...\ndef _add_pos_subtypes(nouns, verbs): ...\ndef _create_pos_subtypes(words): ...\ndef make_descriptors(words): ...\ndef all_prefix_first_vowel(word, letters=list(ascii_uppercase)): ...\ndef recycle(words, func, times=2): ...\ndef backronym(acronym, theme, max_attempts=10): ...\ndef super_scrub(data): ...\ndef generate_all_techniques(words): ...\n", "repository": "christabor/namebot", "test_name": "test_pig_latinize", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000365.py"} {"focal_file": "namebot/scoring.py", "focal_class": null, "focal_method": "score_dmetaphone", "tests": "import unittest\n\nclass Test_score_dmetaphone(unittest.TestCase):\n def test_score_dmetaphone_basic(self):\n self.assertIsInstance(sc.score_dmetaphone(self.words), list)\n", "method_code": "def score_dmetaphone(words):\n \"\"\"Score words using the double metaphone algorithm.\n\n :param words (list): the list of words.\n :rtype scores (list): the scored words\n \"\"\"\n scores = []\n for word in words:\n res, output = dmeta(word)\n scores.append('{0}:{1}:{2}'.format(word, res, output))\n return scores", "context": "def score_dmetaphone(words): ...\ndef score_dmetaphone(words): ...\ndef score_soundex(words): ...\ndef score_nysiis(words): ...\ndef score_length(word): ...\ndef bounded(num, start, end): ...\ndef score_pronounceability(word): ...\ndef score_simplicity(word): ...\ndef score_name_overall(word): ...\ndef score_names_overall(words): ...\ndef generate_all_scoring(words): ...\n", "repository": "christabor/namebot", "test_name": "test_score_dmetaphone_basic", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000366.py"} {"focal_file": "namebot/scoring.py", "focal_class": null, "focal_method": "score_nysiis", "tests": "import unittest\n\nclass Test_score_nysiis(unittest.TestCase):\n def test_score_nysiis_basic(self):\n self.assertIsInstance(sc.score_nysiis(self.words), list)\n", "method_code": "def score_nysiis(words):\n \"\"\"Score words using the nysiis algorithm.\n\n :param words (list): the list of words.\n :rtype scores (list): the scored words\n \"\"\"\n return ['{}: {}'.format(w.lower(), fuzzy.nysiis(w)) for w in words]", "context": "def score_nysiis(words): ...\ndef score_dmetaphone(words): ...\ndef score_soundex(words): ...\ndef score_nysiis(words): ...\ndef score_length(word): ...\ndef bounded(num, start, end): ...\ndef score_pronounceability(word): ...\ndef score_simplicity(word): ...\ndef score_name_overall(word): ...\ndef score_names_overall(words): ...\ndef generate_all_scoring(words): ...\n", "repository": "christabor/namebot", "test_name": "test_score_nysiis_basic", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000367.py"} {"focal_file": "namebot/scoring.py", "focal_class": null, "focal_method": "score_length", "tests": "import unittest\n\nclass Test_score_length(unittest.TestCase):\n def test_score_length1(self):\n self.assertEqual(sc.score_length('a really long company name'), 1)\n\n def test_score_length2(self):\n self.assertEqual(sc.score_length('somewhat long name'), 2)\n\n def test_score_length3(self):\n self.assertEqual(sc.score_length('name'), 3)\n\n def test_score_length4(self):\n self.assertEqual(sc.score_length('western digital'), 4)\n\n def test_score_length5(self):\n self.assertEqual(sc.score_length('facebook'), 5)\n\n def test_score_length_empty(self):\n self.assertEqual(sc.score_length(''), 0)\n\n def test_score_length_none(self):\n self.assertEqual(sc.score_length(None), 0)\n", "method_code": "def score_length(word):\n \"\"\"Return a score, 1-5, of the length of the word.\n\n Really long, or really short words get a lower score.\n There is no hard science, but popular opinion suggests\n that a word somewhere between 8-15 letters is optimal.\n\n :param word (str): The word to score.\n :rtype score (int): The resulting score.\n \"\"\"\n if not word or len(word) == 0:\n return 0\n _len = len(word)\n if _len > 20:\n return 1\n elif _len > 15 and _len <= 20:\n return 2\n elif _len <= 4:\n return 3\n elif _len >= 10 and _len <= 15:\n return 4\n elif _len > 4 and _len < 10:\n return 5", "context": "def score_length(word): ...\ndef score_dmetaphone(words): ...\ndef score_soundex(words): ...\ndef score_nysiis(words): ...\ndef score_length(word): ...\ndef bounded(num, start, end): ...\ndef score_pronounceability(word): ...\ndef score_simplicity(word): ...\ndef score_name_overall(word): ...\ndef score_names_overall(words): ...\ndef generate_all_scoring(words): ...\n", "repository": "christabor/namebot", "test_name": "test_score_length1", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000368.py"} {"focal_file": "namebot/scoring.py", "focal_class": null, "focal_method": "score_pronounceability", "tests": "import unittest\n\nclass Test_score_pronounceability(unittest.TestCase):\n def test_score_pronounce_no_vowels(self):\n self.assertEqual(sc.score_pronounceability('vry bd wrd'), 0)\n\n def test_score_pronounce1(self):\n self.assertEqual(sc.score_pronounceability('ths vry bad wrd'), 1)\n\n def test_score_pronounce2(self):\n self.assertEqual(sc.score_pronounceability('bd word'), 2)\n\n def test_score_pronounce3(self):\n self.assertEqual(sc.score_pronounceability('CVS health'), 3)\n\n def test_score_pronounce4(self):\n self.assertEqual(sc.score_pronounceability('chevron'), 4)\n\n def test_score_pronounce5(self):\n self.assertEqual(sc.score_pronounceability('google'), 5)\n\n def test_score_pronounce_empty(self):\n self.assertEqual(sc.score_pronounceability(''), 0)\n\n def test_score_pronounce_none(self):\n self.assertEqual(sc.score_pronounceability(None), 0)\n", "method_code": "def score_pronounceability(word):\n \"\"\"Get the ratio of vowels to consonants, a very basic measurement.\n\n Half vowels and half consonants indicates a highly pronounceable word.\n For example, 0.5 / 0.5 = 1.0, so one is perfect, and lower is worse.\n\n The 1-5 scale translation:\n\n 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0\n 0 1 2 3 4 5 4 3 2 1 5\n\n :param word (string): The name\n :rtype (int): The final pronounceability score\n \"\"\"\n if not word or len(word) == 0:\n return 0\n word = re.sub('[^a-zA-Z0-9]', '', word)\n re_vowels = re.compile('[a|e|i|o|u]')\n re_cons = re.compile('[^a|e|i|o|u]')\n vowels = float(len(re.findall(re_vowels, word)))\n consonants = float(len(re.findall(re_cons, word)))\n if vowels is 0.0 or consonants is 0.0:\n return 0\n if vowels < consonants:\n ratio = vowels / consonants\n else:\n ratio = consonants / vowels\n if ratio == 0.0:\n return 0\n if ratio == 1.0:\n return 5\n if bounded(ratio, 0.0, 0.1) or bounded(ratio, 0.9, 1.0):\n return 1\n if bounded(ratio, 0.1, 0.2) or bounded(ratio, 0.8, 0.9):\n return 2\n if bounded(ratio, 0.2, 0.3) or bounded(ratio, 0.7, 0.8):\n return 3\n if bounded(ratio, 0.3, 0.4) or bounded(ratio, 0.6, 0.7):\n return 4\n if bounded(ratio, 0.4, 0.5) or bounded(ratio, 0.5, 0.6):\n return 5\n return 0", "context": "def score_pronounceability(word): ...\ndef score_dmetaphone(words): ...\ndef score_soundex(words): ...\ndef score_nysiis(words): ...\ndef score_length(word): ...\ndef bounded(num, start, end): ...\ndef score_pronounceability(word): ...\ndef score_simplicity(word): ...\ndef score_name_overall(word): ...\ndef score_names_overall(words): ...\ndef generate_all_scoring(words): ...\n", "repository": "christabor/namebot", "test_name": "test_score_pronounce_no_vowels", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000369.py"} {"focal_file": "namebot/scoring.py", "focal_class": null, "focal_method": "score_simplicity", "tests": "import unittest\n\nclass Test_score_simplicity(unittest.TestCase):\n def test_score_simple1(self):\n self.assertEqual(sc.score_simplicity('a very poor name indeed'), 1)\n\n def test_score_simple2(self):\n self.assertEqual(sc.score_simplicity('not all that great'), 2)\n\n def test_score_simple3(self):\n self.assertEqual(sc.score_simplicity('not so perfect'), 3)\n\n def test_score_simple4(self):\n self.assertEqual(sc.score_simplicity('not perfect'), 4)\n\n def test_score_simple5(self):\n self.assertEqual(sc.score_simplicity('perfect'), 5)\n\n def test_score_simple_empty(self):\n self.assertEqual(sc.score_simplicity(''), 0)\n\n def test_score_simple_none(self):\n self.assertEqual(sc.score_simplicity(None), 0)\n\n def test_score_overall_empty(self):\n self.assertEqual(sc.score_simplicity(''), 0)\n", "method_code": "def score_simplicity(word):\n \"\"\"Determine how simple the word is.\n\n Simple is defined as the number of separate words.\n In this case, higher is better, indicating a better score.\n\n :param word (string): the name\n :rtype score (int): the final simplicity score\n\n >>> score_simplicity('the cat in the hat')\n >>> 1\n >>> score_simplicity('facebook')\n >>> 5\n \"\"\"\n if not word or len(word) == 0:\n return 0\n word_count = len(re.split('[^a-z]', word))\n if word_count == 1:\n return 5\n if word_count < 3:\n return 4\n if word_count < 4:\n return 3\n if word_count < 5:\n return 2\n return 1", "context": "def score_simplicity(word): ...\ndef score_dmetaphone(words): ...\ndef score_soundex(words): ...\ndef score_nysiis(words): ...\ndef score_length(word): ...\ndef bounded(num, start, end): ...\ndef score_pronounceability(word): ...\ndef score_simplicity(word): ...\ndef score_name_overall(word): ...\ndef score_names_overall(words): ...\ndef generate_all_scoring(words): ...\n", "repository": "christabor/namebot", "test_name": "test_score_simple1", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000370.py"} {"focal_file": "namebot/scoring.py", "focal_class": null, "focal_method": "score_name_overall", "tests": "import unittest\n\nclass Test_score_name_overall(unittest.TestCase):\n def test_score_overall_low(self):\n self.assertEqual(sc.score_name_overall('not vry grt n4m3'), 40.0)\n\n def test_score_overall_mid(self):\n self.assertEqual(sc.score_name_overall('CVS Health'), 80.0)\n\n def test_score_overall_high(self):\n self.assertEqual(sc.score_name_overall('google'), 100.0)\n", "method_code": "def score_name_overall(word):\n \"\"\"Score the name using separate scoring functions, then normalize to 100.\n\n This method gives an overall intuitive score.\n The closer to 100%, the better.\n\n :param word (string): the name\n :rtype score (float): the final name score\n \"\"\"\n length = score_length(word)\n pronounceability = score_pronounceability(word)\n simplicity = score_simplicity(word)\n _scores = sum([length, pronounceability, simplicity])\n score = round(_scores * 10)\n if score > 100:\n return 100\n return score", "context": "def score_name_overall(word): ...\ndef score_dmetaphone(words): ...\ndef score_soundex(words): ...\ndef score_nysiis(words): ...\ndef score_length(word): ...\ndef bounded(num, start, end): ...\ndef score_pronounceability(word): ...\ndef score_simplicity(word): ...\ndef score_name_overall(word): ...\ndef score_names_overall(words): ...\ndef generate_all_scoring(words): ...\n", "repository": "christabor/namebot", "test_name": "test_score_overall_low", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000371.py"} {"focal_file": "namebot/scoring.py", "focal_class": null, "focal_method": "score_names_overall", "tests": "import unittest\n\nclass Test_score_names_overall(unittest.TestCase):\n def test_scores_overall(self):\n self.assertIsInstance(sc.score_names_overall(['google', 'microsoft', 'apple']), list)\n", "method_code": "def score_names_overall(words):\n \"\"\"Score all names.\n\n :param words (list): the list of words.\n :rtype words (list): a list of tuples, with the score and word.\n \"\"\"\n return [(score_name_overall(w), w) for w in words]", "context": "def score_names_overall(words): ...\ndef score_dmetaphone(words): ...\ndef score_soundex(words): ...\ndef score_nysiis(words): ...\ndef score_length(word): ...\ndef bounded(num, start, end): ...\ndef score_pronounceability(word): ...\ndef score_simplicity(word): ...\ndef score_name_overall(word): ...\ndef score_names_overall(words): ...\ndef generate_all_scoring(words): ...\n", "repository": "christabor/namebot", "test_name": "test_scores_overall", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000372.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/build_ext.py", "focal_class": "build_ext", "focal_method": "get_ext_filename", "tests": "import unittest\n\nclass Test_build_ext_get_ext_filename(unittest.TestCase):\n def test_get_ext_filename(self):\n dist = Distribution()\n cmd = build_ext(dist)\n cmd.ext_map['foo/bar'] = ''\n res = cmd.get_ext_filename('foo')\n wanted = distutils_build_ext.get_ext_filename(cmd, 'foo')\n assert res == wanted\n", "method_code": " def get_ext_filename(self, fullname):\n filename = _build_ext.get_ext_filename(self, fullname)\n if fullname in self.ext_map:\n ext = self.ext_map[fullname]\n if isinstance(ext, Library):\n fn, ext = os.path.splitext(filename)\n return self.shlib_compiler.library_filename(fn, libtype)\n elif use_stubs and ext._links_to_dynamic:\n d, fn = os.path.split(filename)\n return os.path.join(d, 'dl-' + fn)\n return filename\n ", "context": "class build_ext(_build_ext):\n def get_ext_filename(self, fullname): ...\n def run(self): ...\n def copy_extensions_to_source(self): ...\n def initialize_options(self): ...\n def finalize_options(self): ...\n def setup_shlib_compiler(self): ...\n def get_export_symbols(self, ext): ...\n def build_extension(self, ext): ...\n def links_to_dynamic(self, ext): ...\n def get_outputs(self): ...\n def write_stub(self, output_dir, ext, compile=False): ...\n", "repository": "snitkdan/books", "test_name": "test_get_ext_filename", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000373.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/easy_install.py", "focal_class": "easy_install", "focal_method": "install_site_py", "tests": "import unittest\n\nclass Test_easy_install_install_site_py(unittest.TestCase):\n def test_install_site_py(self):\n dist = Distribution()\n cmd = easy_install(dist)\n cmd.sitepy_installed = False\n cmd.install_dir = tempfile.mkdtemp()\n try:\n cmd.install_site_py()\n sitepy = os.path.join(cmd.install_dir, 'site.py')\n self.assertTrue(os.path.exists(sitepy))\n finally:\n shutil.rmtree(cmd.install_dir)\n", "method_code": " def install_site_py(self):\n \"\"\"Make sure there's a site.py in the target dir, if needed\"\"\"\n if self.sitepy_installed:\n return\n sitepy = os.path.join(self.install_dir, 'site.py')\n source = resource_string('setuptools', 'site-patch.py')\n current = ''\n if os.path.exists(sitepy):\n log.debug('Checking existing site.py in %s', self.install_dir)\n f = open(sitepy, 'rb')\n current = f.read()\n if sys.version_info >= (3,):\n current = current.decode()\n f.close()\n if not current.startswith('def __boot():'):\n raise DistutilsError('%s is not a setuptools-generated site.py; please remove it.' % sitepy)\n if current != source:\n log.info('Creating %s', sitepy)\n if not self.dry_run:\n ensure_directory(sitepy)\n f = open(sitepy, 'wb')\n f.write(source)\n f.close()\n self.byte_compile([sitepy])\n self.sitepy_installed = True\n ", "context": "class easy_install(Command):\n def install_site_py(self): ...\n def initialize_options(self): ...\n def delete_blockers(self, blockers): ...\n def finalize_options(self): ...\n def _expand_attrs(self, attrs): ...\n def expand_basedirs(self): ...\n def expand_dirs(self): ...\n def run(self): ...\n def pseudo_tempname(self): ...\n def warn_deprecated_options(self): ...\n def check_site_dir(self): ...\n def cant_write_to_target(self): ...\n def check_pth_processing(self): ...\n def install_egg_scripts(self, dist): ...\n def add_output(self, path): ...\n def not_editable(self, spec): ...\n def check_editable(self, spec): ...\n def easy_install(self, spec, deps=False): ...\n def install_item(self, spec, download, tmpdir, deps, install_needed=False): ...\n def select_scheme(self, name): ...\n def process_distribution(self, requirement, dist, deps=True, *info): ...\n def should_unzip(self, dist): ...\n def maybe_move(self, spec, dist_filename, setup_base): ...\n def install_wrapper_scripts(self, dist): ...\n def install_script(self, dist, script_name, script_text, dev_path=None): ...\n def write_script(self, script_name, contents, mode='t', blockers=()): ...\n def install_eggs(self, spec, dist_filename, tmpdir): ...\n def egg_distribution(self, egg_path): ...\n def install_egg(self, egg_path, tmpdir): ...\n def install_exe(self, dist_filename, tmpdir): ...\n def exe_to_egg(self, dist_filename, egg_tmp): ...\n def installation_report(self, req, dist, what='Installed'): ...\n def report_editable(self, spec, setup_script): ...\n def run_setup(self, setup_script, setup_base, args): ...\n def build_and_install(self, setup_script, setup_base): ...\n def _set_fetcher_options(self, base): ...\n def update_pth(self, dist): ...\n def unpack_progress(self, src, dst): ...\n def unpack_and_compile(self, egg_path, destination): ...\n def byte_compile(self, to_compile): ...\n def no_default_version_msg(self): ...\n def create_home_path(self): ...\n def _expand(self, *attrs): ...\n\n description = 'Find/get/install Python packages'\n command_consumes_arguments = True\n user_options = [('prefix=', None, 'installation prefix'), ('zip-ok', 'z', 'install package as a zipfile'), ('multi-version', 'm', 'make apps have to require() a version'), ('upgrade', 'U', 'force upgrade (searches PyPI for latest versions)'), ('install-dir=', 'd', 'install package to DIR'), ('script-dir=', 's', 'install scripts to DIR'), ('exclude-scripts', 'x', \"Don't install scripts\"), ('always-copy', 'a', 'Copy all needed packages to install dir'), ('index-url=', 'i', 'base URL of Python Package Index'), ('find-links=', 'f', 'additional URL(s) to search for packages'), ('build-directory=', 'b', 'download/extract/build in DIR; keep the results'), ('optimize=', 'O', 'also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable [default: -O0]'), ('record=', None, 'filename in which to record list of installed files'), ('always-unzip', 'Z', \"don't install as a zipfile, no matter what\"), ('site-dirs=', 'S', 'list of directories where .pth files work'), ('editable', 'e', 'Install specified packages in editable form'), ('no-deps', 'N', \"don't install dependencies\"), ('allow-hosts=', 'H', 'pattern(s) that hostnames must match'), ('local-snapshots-ok', 'l', 'allow building eggs from local checkouts'), ('version', None, 'print version information and exit'), ('install-layout=', None, 'installation layout to choose (known values: deb)'), ('force-installation-into-system-dir', '0', 'force installation into /usr'), ('no-find-links', None, \"Don't load find-links defined in packages being installed\")]\n boolean_options = ['zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version', 'force-installation-into-system-dir']\n negative_opt = {'always-unzip': 'zip-ok'}\n create_index = PackageIndex\n INSTALL_SCHEMES = dict(posix=dict(install_dir='$base/lib/python$py_version_short/site-packages', script_dir='$base/bin'), unix_local=dict(install_dir='$base/local/lib/python$py_version_short/%s' % sitedir_name, script_dir='$base/local/bin'), posix_local=dict(install_dir='$base/local/lib/python$py_version_short/%s' % sitedir_name, script_dir='$base/local/bin'), deb_system=dict(install_dir='$base/lib/python3/%s' % sitedir_name, script_dir='$base/bin'))\n DEFAULT_SCHEME = dict(install_dir='$base/Lib/site-packages', script_dir='$base/Scripts')\n", "repository": "snitkdan/books", "test_name": "test_install_site_py", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000374.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/easy_install.py", "focal_class": null, "focal_method": "get_script_args", "tests": "import unittest\n\nclass Test_get_script_args(unittest.TestCase):\n def test_get_script_args(self):\n dist = FakeDist()\n old_platform = sys.platform\n try:\n name, script = [i for i in next(get_script_args(dist))][0:2]\n finally:\n sys.platform = old_platform\n self.assertEqual(script, WANTED)\n", "method_code": " def get_script_args(cls, dist, executable=sys_executable, wininst=False):\n \"\"\"\n Yield write_script() argument tuples for a distribution's entrypoints\n \"\"\"\n gen_class = cls.get_writer(wininst)\n spec = str(dist.as_requirement())\n header = get_script_header('', executable, wininst)\n for type_ in ('console', 'gui'):\n group = type_ + '_scripts'\n for name, ep in dist.get_entry_map(group).items():\n script_text = gen_class.template % locals()\n for res in gen_class._get_script_args(type_, name, header, script_text):\n yield res\n ", "context": "class ScriptWriter(object):\n @classmethod\n def get_script_args(cls, dist, executable=sys_executable, wininst=False): ...\n def get_writer(cls, force_windows): ...\n def _get_script_args(cls, type_, name, header, script_text): ...\n\n template = textwrap.dedent(\"\\n # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\\n __requires__ = %(spec)r\\n import sys\\n from pkg_resources import load_entry_point\\n\\n if __name__ == '__main__':\\n sys.exit(\\n load_entry_point(%(spec)r, %(group)r, %(name)r)()\\n )\\n \").lstrip()\n", "repository": "snitkdan/books", "test_name": "test_get_script_args", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000375.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/easy_install.py", "focal_class": "easy_install", "focal_method": "easy_install", "tests": "import unittest\n\nclass Test_easy_install_easy_install(unittest.TestCase):\n def test_user_install_implied(self):\n site.ENABLE_USER_SITE = True\n dist = Distribution()\n dist.script_name = 'setup.py'\n cmd = easy_install(dist)\n cmd.args = ['py']\n cmd.ensure_finalized()\n self.assertTrue(cmd.user, 'user should be implied')\n", "method_code": " def easy_install(self, spec, deps=False):\n tmpdir = tempfile.mkdtemp(prefix='easy_install-')\n download = None\n if not self.editable:\n self.install_site_py()\n try:\n if not isinstance(spec, Requirement):\n if URL_SCHEME(spec):\n self.not_editable(spec)\n download = self.package_index.download(spec, tmpdir)\n return self.install_item(None, download, tmpdir, deps, True)\n elif os.path.exists(spec):\n self.not_editable(spec)\n return self.install_item(None, spec, tmpdir, deps, True)\n else:\n spec = parse_requirement_arg(spec)\n self.check_editable(spec)\n dist = self.package_index.fetch_distribution(spec, tmpdir, self.upgrade, self.editable, not self.always_copy, self.local_index)\n if dist is None:\n msg = 'Could not find suitable distribution for %r' % spec\n if self.always_copy:\n msg += ' (--always-copy skips system and development eggs)'\n raise DistutilsError(msg)\n elif dist.precedence == DEVELOP_DIST:\n self.process_distribution(spec, dist, deps, 'Using')\n return dist\n else:\n return self.install_item(spec, dist.location, tmpdir, deps)\n finally:\n if os.path.exists(tmpdir):\n rmtree(tmpdir)\n ", "context": "class easy_install(Command):\n def easy_install(self, spec, deps=False): ...\n def initialize_options(self): ...\n def delete_blockers(self, blockers): ...\n def finalize_options(self): ...\n def _expand_attrs(self, attrs): ...\n def expand_basedirs(self): ...\n def expand_dirs(self): ...\n def run(self): ...\n def pseudo_tempname(self): ...\n def warn_deprecated_options(self): ...\n def check_site_dir(self): ...\n def cant_write_to_target(self): ...\n def check_pth_processing(self): ...\n def install_egg_scripts(self, dist): ...\n def add_output(self, path): ...\n def not_editable(self, spec): ...\n def check_editable(self, spec): ...\n def install_item(self, spec, download, tmpdir, deps, install_needed=False): ...\n def select_scheme(self, name): ...\n def process_distribution(self, requirement, dist, deps=True, *info): ...\n def should_unzip(self, dist): ...\n def maybe_move(self, spec, dist_filename, setup_base): ...\n def install_wrapper_scripts(self, dist): ...\n def install_script(self, dist, script_name, script_text, dev_path=None): ...\n def write_script(self, script_name, contents, mode='t', blockers=()): ...\n def install_eggs(self, spec, dist_filename, tmpdir): ...\n def egg_distribution(self, egg_path): ...\n def install_egg(self, egg_path, tmpdir): ...\n def install_exe(self, dist_filename, tmpdir): ...\n def exe_to_egg(self, dist_filename, egg_tmp): ...\n def installation_report(self, req, dist, what='Installed'): ...\n def report_editable(self, spec, setup_script): ...\n def run_setup(self, setup_script, setup_base, args): ...\n def build_and_install(self, setup_script, setup_base): ...\n def _set_fetcher_options(self, base): ...\n def update_pth(self, dist): ...\n def unpack_progress(self, src, dst): ...\n def unpack_and_compile(self, egg_path, destination): ...\n def byte_compile(self, to_compile): ...\n def no_default_version_msg(self): ...\n def install_site_py(self): ...\n def create_home_path(self): ...\n def _expand(self, *attrs): ...\n\n description = 'Find/get/install Python packages'\n command_consumes_arguments = True\n user_options = [('prefix=', None, 'installation prefix'), ('zip-ok', 'z', 'install package as a zipfile'), ('multi-version', 'm', 'make apps have to require() a version'), ('upgrade', 'U', 'force upgrade (searches PyPI for latest versions)'), ('install-dir=', 'd', 'install package to DIR'), ('script-dir=', 's', 'install scripts to DIR'), ('exclude-scripts', 'x', \"Don't install scripts\"), ('always-copy', 'a', 'Copy all needed packages to install dir'), ('index-url=', 'i', 'base URL of Python Package Index'), ('find-links=', 'f', 'additional URL(s) to search for packages'), ('build-directory=', 'b', 'download/extract/build in DIR; keep the results'), ('optimize=', 'O', 'also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable [default: -O0]'), ('record=', None, 'filename in which to record list of installed files'), ('always-unzip', 'Z', \"don't install as a zipfile, no matter what\"), ('site-dirs=', 'S', 'list of directories where .pth files work'), ('editable', 'e', 'Install specified packages in editable form'), ('no-deps', 'N', \"don't install dependencies\"), ('allow-hosts=', 'H', 'pattern(s) that hostnames must match'), ('local-snapshots-ok', 'l', 'allow building eggs from local checkouts'), ('version', None, 'print version information and exit'), ('install-layout=', None, 'installation layout to choose (known values: deb)'), ('force-installation-into-system-dir', '0', 'force installation into /usr'), ('no-find-links', None, \"Don't load find-links defined in packages being installed\")]\n boolean_options = ['zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version', 'force-installation-into-system-dir']\n negative_opt = {'always-unzip': 'zip-ok'}\n create_index = PackageIndex\n INSTALL_SCHEMES = dict(posix=dict(install_dir='$base/lib/python$py_version_short/site-packages', script_dir='$base/bin'), unix_local=dict(install_dir='$base/local/lib/python$py_version_short/%s' % sitedir_name, script_dir='$base/local/bin'), posix_local=dict(install_dir='$base/local/lib/python$py_version_short/%s' % sitedir_name, script_dir='$base/local/bin'), deb_system=dict(install_dir='$base/lib/python3/%s' % sitedir_name, script_dir='$base/bin'))\n DEFAULT_SCHEME = dict(install_dir='$base/Lib/site-packages', script_dir='$base/Scripts')\n", "repository": "snitkdan/books", "test_name": "test_user_install_implied", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000376.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "url_ok", "tests": "import unittest\n\nclass Test_url_ok(unittest.TestCase):\n def test_url_ok(self):\n index = setuptools.package_index.PackageIndex(hosts=('www.example.com',))\n url = 'file:///tmp/test_package_index'\n self.assertTrue(index.url_ok(url, True))\n", "method_code": " def url_ok(self, url, fatal=False):\n s = URL_SCHEME(url)\n if s and s.group(1).lower() == 'file' or self.allows(urlparse(url)[1]):\n return True\n msg = '\\nNote: Bypassing %s (disallowed host; see http://bit.ly/1dg9ijs for details).\\n'\n if fatal:\n raise DistutilsError(msg % url)\n else:\n self.warn(msg, url)\n ", "context": "class PackageIndex(Environment):\n def url_ok(self, url, fatal=False): ...\n def __init__(self, index_url='https://pypi.python.org/simple', hosts=('*',), ca_bundle=None, verify_ssl=True, *args, **kw): ...\n def process_url(self, url, retrieve=False): ...\n def process_filename(self, fn, nested=False): ...\n def scan_egg_links(self, search_path): ...\n def scan_egg_link(self, path, entry): ...\n def process_index(self, url, page): ...\n def need_version_info(self, url): ...\n def scan_all(self, msg=None, *args): ...\n def find_packages(self, requirement): ...\n def obtain(self, requirement, installer=None): ...\n def check_hash(self, checker, filename, tfp): ...\n def add_find_links(self, urls): ...\n def prescan(self): ...\n def not_found_in_index(self, requirement): ...\n def download(self, spec, tmpdir): ...\n def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None): ...\n def fetch(self, requirement, tmpdir, force_scan=False, source=False): ...\n def gen_setup(self, filename, fragment, tmpdir): ...\n def _download_to(self, url, filename): ...\n def reporthook(self, url, filename, blocknum, blksize, size): ...\n def open_url(self, url, warning=None): ...\n def _download_url(self, scheme, url, tmpdir): ...\n def scan_url(self, url): ...\n def _attempt_download(self, url, filename): ...\n def _download_html(self, url, headers, filename): ...\n def _download_svn(self, url, filename): ...\n def _vcs_split_rev_from_url(url, pop_prefix=False): ...\n def _download_git(self, url, filename): ...\n def _download_hg(self, url, filename): ...\n def debug(self, msg, *args): ...\n def info(self, msg, *args): ...\n def warn(self, msg, *args): ...\n\n self.index_url = index_url + '/'[:not index_url.endswith('/')]\n self.scanned_urls = {}\n self.fetched_urls = {}\n self.package_pages = {}\n self.allows = re.compile('|'.join(map(translate, hosts))).match\n self.to_scan = []\n\n dl_blocksize = 8192\n", "repository": "snitkdan/books", "test_name": "test_url_ok", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000377.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "parse_bdist_wininst", "tests": "import unittest\n\nclass Test_parse_bdist_wininst(unittest.TestCase):\n def test_parse_bdist_wininst(self):\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win32-py2.4.exe'), ('reportlab-2.5', '2.4', 'win32'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win32.exe'), ('reportlab-2.5', None, 'win32'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win-amd64-py2.7.exe'), ('reportlab-2.5', '2.7', 'win-amd64'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win-amd64.exe'), ('reportlab-2.5', None, 'win-amd64'))\n", "method_code": "def parse_bdist_wininst(name):\n \"\"\"Return (base,pyversion) or (None,None) for possible .exe name\"\"\"\n lower = name.lower()\n base, py_ver, plat = (None, None, None)\n if lower.endswith('.exe'):\n if lower.endswith('.win32.exe'):\n base = name[:-10]\n plat = 'win32'\n elif lower.startswith('.win32-py', -16):\n py_ver = name[-7:-4]\n base = name[:-16]\n plat = 'win32'\n elif lower.endswith('.win-amd64.exe'):\n base = name[:-14]\n plat = 'win-amd64'\n elif lower.startswith('.win-amd64-py', -20):\n py_ver = name[-7:-4]\n base = name[:-20]\n plat = 'win-amd64'\n return (base, py_ver, plat)", "context": "def parse_bdist_wininst(name): ...\ndef parse_bdist_wininst(name): ...\ndef egg_info_for_url(url): ...\ndef distros_for_url(url, metadata=None): ...\ndef distros_for_location(location, basename, metadata=None): ...\ndef distros_for_filename(filename, metadata=None): ...\ndef interpret_distro_name(location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None): ...\ndef unique_everseen(iterable, key=None): ...\ndef unique_values(func): ...\ndef find_external_links(url, page): ...\ndef uchr(c): ...\ndef decode_entity(match): ...\ndef htmldecode(text): ...\ndef socket_timeout(timeout=15): ...\ndef _encode_auth(auth): ...\ndef open_with_auth(url, opener=urllib2.urlopen): ...\ndef fix_sf_url(url): ...\ndef local_open(url): ...\n", "repository": "snitkdan/books", "test_name": "test_parse_bdist_wininst", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000378.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "report", "tests": "import unittest\n\nclass Test_report(unittest.TestCase):\n def test_report(self):\n checker = setuptools.package_index.HashChecker.from_url('http://foo/bar#md5=f12895fdffbd45007040d2e44df98478')\n rep = checker.report(lambda x: x, 'My message about %s')\n self.assertEqual(rep, 'My message about md5')\n", "method_code": " def report(self, reporter, template):\n \"\"\"\n Call reporter with information about the checker (hash name)\n substituted into the template.\n \"\"\"\n return\n ", "context": "class ContentChecker(object):\n def report(self, reporter, template): ...\n def feed(self, block): ...\n def is_valid(self): ...\n", "repository": "snitkdan/books", "test_name": "test_report", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000379.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/easy_install.py", "focal_class": null, "focal_method": "get_script_header", "tests": "import unittest\n\nclass Test_get_script_header(unittest.TestCase):\n def test_get_script_header(self):\n if not sys.platform.startswith('java') or not is_sh(sys.executable):\n expected = '#!%s\\n' % nt_quote_arg(os.path.normpath(sys.executable))\n self.assertEqual(get_script_header('#!/usr/local/bin/python'), expected)\n expected = '#!%s -x\\n' % nt_quote_arg(os.path.normpath(sys.executable))\n self.assertEqual(get_script_header('#!/usr/bin/python -x'), expected)\n self.assertEqual(get_script_header('#!/usr/bin/python', executable=self.non_ascii_exe), '#!%s -x\\n' % self.non_ascii_exe)\n candidate = get_script_header('#!/usr/bin/python', executable=self.exe_with_spaces)\n self.assertEqual(candidate, '#!\"%s\"\\n' % self.exe_with_spaces)\n\n def test_get_script_header_jython_workaround(self):\n if sys.version_info >= (3,) and os.environ.get('LC_CTYPE') in (None, 'C', 'POSIX'):\n return\n\n class java:\n\n class lang:\n\n class System:\n\n @staticmethod\n def getProperty(property):\n return ''\n sys.modules['java'] = java\n platform = sys.platform\n sys.platform = 'java1.5.0_13'\n stdout, stderr = (sys.stdout, sys.stderr)\n try:\n exe = os.path.normpath(os.path.splitext(__file__)[0] + '.py')\n self.assertEqual(get_script_header('#!/usr/local/bin/python', executable=exe), '#!/usr/bin/env %s\\n' % exe)\n sys.stdout = sys.stderr = StringIO()\n self.assertEqual(get_script_header('#!/usr/bin/python -x', executable=exe), '#!%s -x\\n' % exe)\n self.assertTrue('Unable to adapt shebang line' in sys.stdout.getvalue())\n sys.stdout = sys.stderr = StringIO()\n self.assertEqual(get_script_header('#!/usr/bin/python', executable=self.non_ascii_exe), '#!%s -x\\n' % self.non_ascii_exe)\n self.assertTrue('Unable to adapt shebang line' in sys.stdout.getvalue())\n finally:\n del sys.modules['java']\n sys.platform = platform\n sys.stdout, sys.stderr = (stdout, stderr)\n", "method_code": "def get_script_header(script_text, executable=sys_executable, wininst=False):\n \"\"\"Create a #! line, getting options (if any) from script_text\"\"\"\n from distutils.command.build_scripts import first_line_re\n if not isinstance(first_line_re.pattern, str):\n first_line_re = re.compile(first_line_re.pattern.decode())\n first = (script_text + '\\n').splitlines()[0]\n match = first_line_re.match(first)\n options = ''\n if match:\n options = match.group(1) or ''\n if options:\n options = ' ' + options\n if wininst:\n executable = 'python.exe'\n else:\n executable = nt_quote_arg(executable)\n hdr = '#!%(executable)s%(options)s\\n' % locals()\n if not isascii(hdr):\n if options:\n if options.strip().startswith('-'):\n options = ' -x' + options.strip()[1:]\n else:\n options = ' -x'\n executable = fix_jython_executable(executable, options)\n hdr = '#!%(executable)s%(options)s\\n' % locals()\n return hdr", "context": "def get_script_header(script_text, executable=sys_executable, wininst=False): ...\ndef is_64bit(): ...\ndef samefile(p1, p2): ...\ndef get_site_dirs(): ...\ndef expand_paths(inputs): ...\ndef extract_wininst_cfg(dist_filename): ...\ndef get_exe_prefixes(exe_filename): ...\ndef parse_requirement_arg(spec): ...\ndef get_script_header(script_text, executable=sys_executable, wininst=False): ...\ndef auto_chmod(func, arg, exc): ...\ndef uncache_zipdir(path): ...\ndef _uncache(path, cache): ...\ndef is_python(text, filename=''): ...\ndef is_sh(executable): ...\ndef nt_quote_arg(arg): ...\ndef is_python_script(script_text, filename): ...\ndef chmod(path, mode): ...\ndef fix_jython_executable(executable, options): ...\ndef get_win_launcher(type): ...\ndef load_launcher_manifest(name): ...\ndef rmtree(path, ignore_errors=False, onerror=auto_chmod): ...\ndef current_umask(): ...\ndef bootstrap(): ...\ndef main(argv=None, **kw): ...\n", "repository": "snitkdan/books", "test_name": "test_get_script_header", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000380.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/upload_docs.py", "focal_class": "upload_docs", "focal_method": "create_zipfile", "tests": "import unittest\n\nclass Test_upload_docs_create_zipfile(unittest.TestCase):\n def test_create_zipfile(self):\n dist = Distribution()\n cmd = upload_docs(dist)\n cmd.upload_dir = self.upload_dir\n cmd.target_dir = self.upload_dir\n tmp_dir = tempfile.mkdtemp()\n tmp_file = os.path.join(tmp_dir, 'foo.zip')\n try:\n zip_file = cmd.create_zipfile(tmp_file)\n assert zipfile.is_zipfile(tmp_file)\n zip_file = zipfile.ZipFile(tmp_file)\n assert zip_file.namelist() == ['index.html']\n zip_file.close()\n finally:\n shutil.rmtree(tmp_dir)\n", "method_code": " def create_zipfile(self, filename):\n zip_file = zipfile.ZipFile(filename, 'w')\n try:\n self.mkpath(self.target_dir)\n for root, dirs, files in os.walk(self.target_dir):\n if root == self.target_dir and (not files):\n raise DistutilsOptionError(\"no files found in upload directory '%s'\" % self.target_dir)\n for name in files:\n full = os.path.join(root, name)\n relative = root[len(self.target_dir):].lstrip(os.path.sep)\n dest = os.path.join(relative, name)\n zip_file.write(full, dest)\n finally:\n zip_file.close()\n ", "context": "class upload_docs(upload):\n def create_zipfile(self, filename): ...\n def has_sphinx(self): ...\n def initialize_options(self): ...\n def finalize_options(self): ...\n def run(self): ...\n def upload_file(self, filename): ...\n\n description = 'Upload documentation to PyPI'\n user_options = [('repository=', 'r', 'url of repository [default: %s]' % upload.DEFAULT_REPOSITORY), ('show-response', None, 'display full response text from server'), ('upload-dir=', None, 'directory to upload')]\n boolean_options = upload.boolean_options\n sub_commands = [('build_sphinx', has_sphinx)]\n", "repository": "snitkdan/books", "test_name": "test_create_zipfile", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000381.py"} {"focal_file": "pyrocore/src/pyrocore/torrent/engine.py", "focal_class": null, "focal_method": "_interval_sum", "tests": "import unittest\n\nclass Test_interval_sum(unittest.TestCase):\n def test_interval_sum(self):\n for context in (None, 'unittest'):\n for interval, kwargs, expected in self.INTERVAL_DATA:\n kwargs['context'] = context\n result = engine._interval_sum(interval, **kwargs)\n self.assertEqual(expected, result, 'for interval=%r kw=%r' % (interval, kwargs))\n", "method_code": "def _interval_sum(interval, start=None, end=None, context=None):\n \"\"\" Return sum of intervals between \"R\"esume and \"P\"aused events\n in C{interval}, optionally limited by a time window defined\n by C{start} and C{end}. Return empty list if there's no sensible\n information.\n\n C{interval} is a series of event types and timestamps,\n e.g. \"R1283008245P1283008268\".\n \"\"\"\n end = end and float(end) or time.time()\n events = _interval_split(interval, context=context)\n result = []\n while events:\n event, resumed = events.pop()\n if event != 'R':\n continue\n resumed = max(resumed, start or resumed)\n if events:\n if not events[-1][0] == 'P':\n continue\n _, paused = events.pop()\n paused = min(paused, end)\n else:\n paused = end\n if resumed >= paused:\n continue\n result.append(paused - resumed)\n return sum(result) if result else None", "context": "def _interval_sum(interval, start=None, end=None, context=None): ...\ndef untyped(val): ...\ndef ratio_float(intval): ...\ndef percent(floatval): ...\ndef _duration(start, end): ...\ndef _interval_split(interval, only=None, context=None, event_re=re.compile('[A-Z][0-9]+')): ...\ndef _interval_sum(interval, start=None, end=None, context=None): ...\ndef _fmt_duration(duration): ...\ndef _fmt_tags(tagset): ...\ndef _fmt_files(filelist): ...\ndef detect_traits(item): ...\n", "repository": "aybassiouny/pyroscope", "test_name": "test_interval_sum", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000382.py"} {"focal_file": "src/ExtendedRequestsLibrary/__init__.py", "focal_class": "ExtendedRequestsLibrary", "focal_method": "delete_session", "tests": "import unittest\n\nclass Test_ExtendedRequestsLibrary_delete_session(unittest.TestCase):\n def test_delete_should_remove_session(self):\n \"\"\"Delete session should successfully remove requested existing session.\"\"\"\n library = ExtendedRequestsLibrary()\n library.create_session(self.label, self.base_url)\n self.assertIsNotNone(library.get_session_object(self.label))\n library.delete_session(self.label)\n with self.assertRaises(RuntimeError) as context:\n library._cache.switch(self.label)\n self.assertTrue(\"Non-existing index or alias '%s'.\" % self.label in context.exception)\n", "method_code": " def delete_session(self, label):\n \"\"\"Removes session object using the given ``label``.\n \n Arguments:\n - ``label``: A case and space insensitive string to identify\n the Session object in the cache.\n \n Examples:\n | Delete Session | label |\n \"\"\"\n self._cache.switch(label)\n index = self._cache.current_index\n self._cache.current = self._cache._no_current\n self._cache._connections[index - 1] = None\n self._cache._aliases['x-%s-x' % label] = self._cache._aliases.pop(label)\n ", "context": "class ExtendedRequestsLibrary(RequestsLibraryUtility):\n def delete_session(self, label): ...\n def __init__(self): ...\n def __getattribute__(self, name): ...\n def create_client_oauth2_session(self, *args, **kwargs): ...\n def create_ntlm_session(self, label, base_url, auth, **kwargs): ...\n def create_password_oauth2_session(self, *args, **kwargs): ...\n def create_session(self, label, base_url, **kwargs): ...\n def delete_request(self, label, uri, **kwargs): ...\n def get_request(self, label, uri, **kwargs): ...\n def get_session_object(self, label): ...\n def head_request(self, label, uri, **kwargs): ...\n def options_request(self, label, uri, **kwargs): ...\n def patch_request(self, label, uri, **kwargs): ...\n def post_request(self, label, uri, **kwargs): ...\n def put_request(self, label, uri, **kwargs): ...\n def _create_oauth2_session(self, client, *args, **kwargs): ...\n def _finalize_response(session, response, method): ...\n def _register_url(self, url=None): ...\n def _register_urls(self, base_url=None, token_url=None): ...\n def _session_init(self, session=None, **kwargs): ...\n\n self._primers = {}\n self.cookies = None\n self.timeout = 90\n self.verify = False\n\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n ROBOT_LIBRARY_VERSION = __version__\n", "repository": "rickypc/robotframework-extendedrequestslibrary", "test_name": "test_delete_should_remove_session", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000383.py"} {"focal_file": "src/ExtendedRequestsLibrary/__init__.py", "focal_class": null, "focal_method": "create_session", "tests": "import unittest\n\nclass Test_create_session(unittest.TestCase):\n def test_create_session_workflow(self):\n \"\"\"Should create session workflow.\"\"\"\n library = self.library\n session = mock.Mock()\n library._cache.switch.return_value = session\n library.create_session(self.label, self.base_url)\n self.assertEqual(library.get_session_object(self.label), session)\n", "method_code": " def create_session(self, label, base_url, **kwargs):\n \"\"\"Create and return a HTTP session object to a server.\n \n Arguments:\n - ``label``: A case and space insensitive string to identify the OAuth2 session.\n - ``base_url``: The server base URL.\n - ``auth``: A list of HTTP basic authentication credentials. ['username', 'password']\n - ``headers``: Default headers dictionary.\n - ``timeout``: The connection timeout in seconds.\n - ``proxies``: The proxy URLs dictionary for HTTP and/or HTTPS communication.\n - ``verify``: Set to True if [http://goo.gl/8p7MOG|Requests] should verify the SSL\n certificate.\n \n Examples:\n | @{auth} = | Create List | username | password |\n | ${var} = | Create Session | label | https://service | auth=@{auth} |\n \"\"\"\n return super(ExtendedRequestsLibrary, self).create_session(label, base_url, **kwargs)\n ", "context": "class ExtendedRequestsLibrary(RequestsLibraryUtility):\n def create_session(self, label, base_url, **kwargs): ...\n def __init__(self): ...\n def __getattribute__(self, name): ...\n def create_client_oauth2_session(self, *args, **kwargs): ...\n def create_ntlm_session(self, label, base_url, auth, **kwargs): ...\n def create_password_oauth2_session(self, *args, **kwargs): ...\n def delete_request(self, label, uri, **kwargs): ...\n def delete_session(self, label): ...\n def get_request(self, label, uri, **kwargs): ...\n def get_session_object(self, label): ...\n def head_request(self, label, uri, **kwargs): ...\n def options_request(self, label, uri, **kwargs): ...\n def patch_request(self, label, uri, **kwargs): ...\n def post_request(self, label, uri, **kwargs): ...\n def put_request(self, label, uri, **kwargs): ...\n def _create_oauth2_session(self, client, *args, **kwargs): ...\n def _finalize_response(session, response, method): ...\n def _register_url(self, url=None): ...\n def _register_urls(self, base_url=None, token_url=None): ...\n def _session_init(self, session=None, **kwargs): ...\n\n self._primers = {}\n self.cookies = None\n self.timeout = 90\n self.verify = False\n\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n ROBOT_LIBRARY_VERSION = __version__\n", "repository": "rickypc/robotframework-extendedrequestslibrary", "test_name": "test_create_session_workflow", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000384.py"} {"focal_file": "src/ExtendedRequestsLibrary/__init__.py", "focal_class": null, "focal_method": "create_ntlm_session", "tests": "import unittest\n\nclass Test_create_ntlm_session(unittest.TestCase):\n def test_create_ntlm_session_workflow(self):\n \"\"\"Should create NTLM session workflow.\"\"\"\n library = self.library\n session = mock.Mock()\n library._cache.switch.return_value = session\n library.create_ntlm_session(self.label, self.base_url, auth=('MY-DOMAIN', self.username, self.password))\n self.assertEqual(library.get_session_object(self.label), session)\n", "method_code": " def create_ntlm_session(self, label, base_url, auth, **kwargs):\n \"\"\"Create and return a [https://goo.gl/zac4cn|NTLM] session object to a server.\n \n Arguments:\n - ``label``: A case and space insensitive string to identify the OAuth2 session.\n - ``base_url``: The server base URL.\n - ``auth``: A list of NTLM authentication credentials. ['domain', 'username', 'password']\n - ``headers``: Default headers dictionary.\n - ``timeout``: The connection timeout in seconds.\n - ``proxies``: The proxy URLs dictionary for HTTP and/or HTTPS communication.\n - ``verify``: Set to True if [http://goo.gl/8p7MOG|Requests] should verify the SSL\n certificate.\n \n Examples:\n | @{auth} = | Create List | domain | username | password |\n | ${var} = | Create NTLM Session | label | https://service | auth=@{auth} |\n \"\"\"\n return super(ExtendedRequestsLibrary, self).create_ntlm_session(label, base_url, auth, **kwargs)\n ", "context": "class ExtendedRequestsLibrary(RequestsLibraryUtility):\n def create_ntlm_session(self, label, base_url, auth, **kwargs): ...\n def __init__(self): ...\n def __getattribute__(self, name): ...\n def create_client_oauth2_session(self, *args, **kwargs): ...\n def create_password_oauth2_session(self, *args, **kwargs): ...\n def create_session(self, label, base_url, **kwargs): ...\n def delete_request(self, label, uri, **kwargs): ...\n def delete_session(self, label): ...\n def get_request(self, label, uri, **kwargs): ...\n def get_session_object(self, label): ...\n def head_request(self, label, uri, **kwargs): ...\n def options_request(self, label, uri, **kwargs): ...\n def patch_request(self, label, uri, **kwargs): ...\n def post_request(self, label, uri, **kwargs): ...\n def put_request(self, label, uri, **kwargs): ...\n def _create_oauth2_session(self, client, *args, **kwargs): ...\n def _finalize_response(session, response, method): ...\n def _register_url(self, url=None): ...\n def _register_urls(self, base_url=None, token_url=None): ...\n def _session_init(self, session=None, **kwargs): ...\n\n self._primers = {}\n self.cookies = None\n self.timeout = 90\n self.verify = False\n\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n ROBOT_LIBRARY_VERSION = __version__\n", "repository": "rickypc/robotframework-extendedrequestslibrary", "test_name": "test_create_ntlm_session_workflow", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000385.py"} {"focal_file": "src/ExtendedRequestsLibrary/__init__.py", "focal_class": null, "focal_method": "get_session_object", "tests": "import unittest\n\nclass Test_get_session_object(unittest.TestCase):\n @mock.patch('ExtendedRequestsLibrary.OAuth2Session')\n @mock.patch('ExtendedRequestsLibrary.logger')\n def test_get_session_object_workflow(self, mock_logger, mock_oauth2):\n \"\"\"Should return session object successfully.\"\"\"\n library = self.library\n oauth2_instance = mock_oauth2()\n library._cache.switch.return_value = oauth2_instance\n library.get_session_object(self.label)\n library._cache.switch.assert_called_with(self.label)\n mock_logger.debug.assert_called_with(vars(library._cache.switch()))\n", "method_code": " def get_session_object(self, label):\n \"\"\"Returns the session object found in the cache using the given ``label``\n \n Arguments:\n - ``label``: A case and space insensitive string to identify\n the Session object in the cache.\n \n Examples:\n | ${var} = | Get Session Object | label |\n \"\"\"\n response = self._cache.switch(label)\n logger.debug(vars(response))\n return response\n ", "context": "class ExtendedRequestsLibrary(RequestsLibraryUtility):\n def get_session_object(self, label): ...\n def __init__(self): ...\n def __getattribute__(self, name): ...\n def create_client_oauth2_session(self, *args, **kwargs): ...\n def create_ntlm_session(self, label, base_url, auth, **kwargs): ...\n def create_password_oauth2_session(self, *args, **kwargs): ...\n def create_session(self, label, base_url, **kwargs): ...\n def delete_request(self, label, uri, **kwargs): ...\n def delete_session(self, label): ...\n def get_request(self, label, uri, **kwargs): ...\n def head_request(self, label, uri, **kwargs): ...\n def options_request(self, label, uri, **kwargs): ...\n def patch_request(self, label, uri, **kwargs): ...\n def post_request(self, label, uri, **kwargs): ...\n def put_request(self, label, uri, **kwargs): ...\n def _create_oauth2_session(self, client, *args, **kwargs): ...\n def _finalize_response(session, response, method): ...\n def _register_url(self, url=None): ...\n def _register_urls(self, base_url=None, token_url=None): ...\n def _session_init(self, session=None, **kwargs): ...\n\n self._primers = {}\n self.cookies = None\n self.timeout = 90\n self.verify = False\n\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n ROBOT_LIBRARY_VERSION = __version__\n", "repository": "rickypc/robotframework-extendedrequestslibrary", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000386.py"} {"focal_file": "src/ExtendedRequestsLibrary/__init__.py", "focal_class": null, "focal_method": "_finalize_response", "tests": "import unittest\n\nclass Test_finalize_response(unittest.TestCase):\n @mock.patch('ExtendedRequestsLibrary.OAuth2Session')\n @mock.patch('ExtendedRequestsLibrary.logger')\n def test_finalize_response(self, mock_logger, mock_oauth2):\n \"\"\"Should finalize response.\"\"\"\n oauth2_instance = mock_oauth2()\n type(oauth2_instance.head()).content = mock.PropertyMock(return_value=self.value)\n response = oauth2_instance.head()\n self.library._finalize_response(oauth2_instance, response, 'HEAD')\n self.assertEqual(oauth2_instance.last_resp, response)\n mock_logger.debug.assert_called_with('%s response: %s' % ('HEAD', self.value))\n", "method_code": " def _finalize_response(session, response, method):\n \"\"\"Store last response object, logging, and return the response\"\"\"\n session.last_resp = response\n logger.debug('%s response: %s' % (method, response.content))\n return response\n ", "context": "class ExtendedRequestsLibrary(RequestsLibraryUtility):\n @staticmethod\n def _finalize_response(session, response, method): ...\n def __init__(self): ...\n def __getattribute__(self, name): ...\n def create_client_oauth2_session(self, *args, **kwargs): ...\n def create_ntlm_session(self, label, base_url, auth, **kwargs): ...\n def create_password_oauth2_session(self, *args, **kwargs): ...\n def create_session(self, label, base_url, **kwargs): ...\n def delete_request(self, label, uri, **kwargs): ...\n def delete_session(self, label): ...\n def get_request(self, label, uri, **kwargs): ...\n def get_session_object(self, label): ...\n def head_request(self, label, uri, **kwargs): ...\n def options_request(self, label, uri, **kwargs): ...\n def patch_request(self, label, uri, **kwargs): ...\n def post_request(self, label, uri, **kwargs): ...\n def put_request(self, label, uri, **kwargs): ...\n def _create_oauth2_session(self, client, *args, **kwargs): ...\n def _register_url(self, url=None): ...\n def _register_urls(self, base_url=None, token_url=None): ...\n def _session_init(self, session=None, **kwargs): ...\n\n self._primers = {}\n self.cookies = None\n self.timeout = 90\n self.verify = False\n\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n ROBOT_LIBRARY_VERSION = __version__\n", "repository": "rickypc/robotframework-extendedrequestslibrary", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000387.py"} {"focal_file": "src/ExtendedRequestsLibrary/__init__.py", "focal_class": null, "focal_method": "_register_url", "tests": "import unittest\n\nclass Test_register_url(unittest.TestCase):\n @mock.patch('ExtendedRequestsLibrary.requests')\n def test_should_register_url(self, mock_requests):\n \"\"\"Should register URL.\"\"\"\n hostname = 'subdomain.domain.moo'\n library = self.library\n self.assertFalse(hostname in library._primers)\n library._register_url('http://%s' % hostname)\n mock_requests.head.assert_called_with('http://%s' % hostname, verify=False)\n self.assertTrue(hostname in library._primers)\n", "method_code": " def _register_url(self, url=None):\n \"\"\"Make HEAD request to warm up the destination server\"\"\"\n host = urlparse(url).hostname\n if host not in self._primers:\n requests.head('%s' % url, verify=False)\n self._primers[host] = 1\n ", "context": "class ExtendedRequestsLibrary(RequestsLibraryUtility):\n def _register_url(self, url=None): ...\n def __init__(self): ...\n def __getattribute__(self, name): ...\n def create_client_oauth2_session(self, *args, **kwargs): ...\n def create_ntlm_session(self, label, base_url, auth, **kwargs): ...\n def create_password_oauth2_session(self, *args, **kwargs): ...\n def create_session(self, label, base_url, **kwargs): ...\n def delete_request(self, label, uri, **kwargs): ...\n def delete_session(self, label): ...\n def get_request(self, label, uri, **kwargs): ...\n def get_session_object(self, label): ...\n def head_request(self, label, uri, **kwargs): ...\n def options_request(self, label, uri, **kwargs): ...\n def patch_request(self, label, uri, **kwargs): ...\n def post_request(self, label, uri, **kwargs): ...\n def put_request(self, label, uri, **kwargs): ...\n def _create_oauth2_session(self, client, *args, **kwargs): ...\n def _finalize_response(session, response, method): ...\n def _register_urls(self, base_url=None, token_url=None): ...\n def _session_init(self, session=None, **kwargs): ...\n\n self._primers = {}\n self.cookies = None\n self.timeout = 90\n self.verify = False\n\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n ROBOT_LIBRARY_VERSION = __version__\n", "repository": "rickypc/robotframework-extendedrequestslibrary", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000388.py"} {"focal_file": "src/ExtendedRequestsLibrary/__init__.py", "focal_class": null, "focal_method": "_register_urls", "tests": "import unittest\n\nclass Test_register_urls(unittest.TestCase):\n def test_should_register_urls(self):\n \"\"\"Should register multiple URLs.\"\"\"\n library = self.library\n library._register_url = mock.Mock()\n library._register_urls(base_url='http://localhost1', token_url='https://localhost2')\n library._register_url.assert_any_call('http://localhost1')\n library._register_url.assert_any_call('https://localhost2')\n self.assertTrue(library._register_url.call_count, 2)\n", "method_code": " def _register_urls(self, base_url=None, token_url=None):\n \"\"\"Make HEAD requests for both base URL and token URL\"\"\"\n self._register_url(base_url)\n self._register_url(token_url)\n ", "context": "class ExtendedRequestsLibrary(RequestsLibraryUtility):\n def _register_urls(self, base_url=None, token_url=None): ...\n def __init__(self): ...\n def __getattribute__(self, name): ...\n def create_client_oauth2_session(self, *args, **kwargs): ...\n def create_ntlm_session(self, label, base_url, auth, **kwargs): ...\n def create_password_oauth2_session(self, *args, **kwargs): ...\n def create_session(self, label, base_url, **kwargs): ...\n def delete_request(self, label, uri, **kwargs): ...\n def delete_session(self, label): ...\n def get_request(self, label, uri, **kwargs): ...\n def get_session_object(self, label): ...\n def head_request(self, label, uri, **kwargs): ...\n def options_request(self, label, uri, **kwargs): ...\n def patch_request(self, label, uri, **kwargs): ...\n def post_request(self, label, uri, **kwargs): ...\n def put_request(self, label, uri, **kwargs): ...\n def _create_oauth2_session(self, client, *args, **kwargs): ...\n def _finalize_response(session, response, method): ...\n def _register_url(self, url=None): ...\n def _session_init(self, session=None, **kwargs): ...\n\n self._primers = {}\n self.cookies = None\n self.timeout = 90\n self.verify = False\n\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n ROBOT_LIBRARY_VERSION = __version__\n", "repository": "rickypc/robotframework-extendedrequestslibrary", "test_name": "test_should_register_urls", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000389.py"} {"focal_file": "src/models/chess_game.py", "focal_class": null, "focal_method": "get_pawn_promote_types", "tests": "import unittest\n\nclass Test_get_pawn_promote_types(unittest.TestCase):\n def test_move_result_pawn_promotion(self):\n self.p1.color = Color.WHITE\n self.p2.color = Color.BLACK\n fen = '8/P2n4/4b3/2q1k3/K7/8/3RB1p1/8 b - -'\n game = ChessGame(fen=fen, white_player=self.p1, black_player=self.p2)\n result = game.move_piece('g2', 'g1')\n expected_move_result = MoveResult()\n expected_move_result.pawn_promote_info = {'player': self.p2, 'promote_types': game.get_pawn_promote_types()}\n self.assertEqual(expected_move_result, result)\n result = game.promote_pawn('g2', 'g1', Type.QUEEN)\n expected_move_result = MoveResult()\n expected_move_result.update_positions = {'g2': None, 'g1': Queen(Color.BLACK)}\n self.assertEqual(expected_move_result, result)\n result = game.move_piece('a7', 'a8')\n expected_move_result = MoveResult()\n expected_move_result.pawn_promote_info = {'player': self.p1, 'promote_types': game.get_pawn_promote_types()}\n self.assertEqual(expected_move_result, result)\n result = game.promote_pawn('a7', 'a8', Type.KNIGHT)\n expected_promote_result = MoveResult()\n expected_promote_result.update_positions = {'a7': None, 'a8': Knight(Color.WHITE)}\n self.assertEqual(expected_promote_result, result)\n\n def test_pawn_capture_promotion(self):\n \"\"\"\n Perform piece capture with a pawn that will place the pawn on the last row.\n Expected result is the pawn can be promoted.\n :return:\n \"\"\"\n self.p1.color = Color.WHITE\n self.p2.color = Color.BLACK\n fen = '2b1k2r/5pP1/2n1p3/1P5p/3B1P2/2P3N1/7P/3RK3 w - -'\n game = ChessGame(fen=fen, white_player=self.p1, black_player=self.p2)\n result = game.move_piece('g7', 'h8')\n expected_move_result = MoveResult()\n expected_move_result.pawn_promote_info = {'player': self.p1, 'promote_types': game.get_pawn_promote_types()}\n self.assertEqual(expected_move_result, result)\n result = game.promote_pawn('g7', 'h8', Type.QUEEN)\n expected_promote_result = MoveResult()\n expected_promote_result.update_positions = {'g7': None, 'h8': Queen(Color.WHITE)}\n expected_promote_result.king_in_check = self.p2\n self.assertEqual(expected_promote_result, result)\n", "method_code": " def get_pawn_promote_types(cls):\n \"\"\"\n Retrieve the piece types a pawn can promote to.\n \n :return: Type[]\n \"\"\"\n return [Type.ROOK, Type.KNIGHT, Type.BISHOP, Type.QUEEN]\n ", "context": "class ChessGame(db.Model):\n @classmethod\n def get_pawn_promote_types(cls): ...\n def __init__(self, fen=None, **kwargs): ...\n def board(self): ...\n def board(self, board): ...\n def get_legal_moves(self, position): ...\n def move_piece(self, start_position, end_position): ...\n def current_player(self): ...\n def promote_pawn(self, start_position, end_position, piece_type): ...\n def get_winner(self): ...\n def can_promote_pawn(self, start_position, end_position): ...\n def save_to_db(self): ...\n def delete_from_db(self): ...\n def to_dict(self): ...\n def load_by_id(cls, game_id): ...\n def _get_player_by_color(self, color): ...\n def __str__(self): ...\n\n self.fen = fen if fen else 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -'\n self._board = ChessBoard(fen)\n\n __tablename__ = 'game'\n id = db.Column(db.Integer, primary_key=True)\n fen = db.Column(db.String(100))\n white_player_id = db.Column(db.Integer, db.ForeignKey('players.id'))\n black_player_id = db.Column(db.Integer, db.ForeignKey('players.id'))\n is_over = db.Column(db.Boolean, default=False)\n white_player = db.relationship('Player', foreign_keys=white_player_id)\n black_player = db.relationship('Player', foreign_keys=black_player_id)\n score = db.relationship('GameScore', uselist=False, back_populates='game')\n", "repository": "nickjamesio/Chess", "test_name": "test_move_result_pawn_promotion", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000390.py"} {"focal_file": "tools/android/incremental_install_test.py", "focal_class": null, "focal_method": "_CallIncrementalInstall", "tests": "import unittest\n\nclass Test_CallIncrementalInstall(unittest.TestCase):\n def testMissingNativeManifestWithIncrementalInstall(self):\n self._CreateZip()\n with open('liba.so', 'w') as f:\n f.write('liba_1')\n native_libs = ['armeabi-v7a:liba.so']\n self._CallIncrementalInstall(incremental=False, native_libs=native_libs)\n self.assertEquals('liba_1', self._GetDeviceFile('native/liba.so'))\n self._PutDeviceFile('native/liba.so', 'GARBAGE')\n self._CallIncrementalInstall(incremental=False, native_libs=native_libs)\n self.assertEquals('liba_1', self._GetDeviceFile('native/liba.so'))\n\n def testNonIncrementalInstallOverwritesNativeLibs(self):\n self._CreateZip()\n with open('liba.so', 'w') as f:\n f.write('liba_1')\n native_libs = ['armeabi-v7a:liba.so']\n self._CallIncrementalInstall(incremental=False, native_libs=native_libs)\n self.assertEquals('liba_1', self._GetDeviceFile('native/liba.so'))\n self._PutDeviceFile('native/liba.so', 'GARBAGE')\n self._CallIncrementalInstall(incremental=True, native_libs=native_libs)\n self.assertEquals('GARBAGE', self._GetDeviceFile('native/liba.so'))\n self._CallIncrementalInstall(incremental=False, native_libs=native_libs)\n self.assertEquals('liba_1', self._GetDeviceFile('native/liba.so'))\n\n def testIncrementalInstallOnPristineDevice(self):\n self._CreateZip()\n self._CreateLocalManifest('zip1 zp1 ip1 0', 'zip1 zip2 ip2 1', 'dex1 - ip3 0')\n try:\n self._CallIncrementalInstall(incremental=True)\n self.fail('Should have quit for incremental install on pristine device')\n except SystemExit:\n pass\n\n def testIncrementalInstallWithWrongInstallTimestamp(self):\n self._CreateRemoteManifest('zip1 zp1 ip1 0', 'zip1 zip2 ip2 1', 'dex1 - ip3 0')\n self._PutDeviceFile('dex/ip1', 'content1')\n self._PutDeviceFile('dex/ip2', 'content2')\n self._PutDeviceFile('dex/ip3', 'content3')\n self._mock_adb.package_timestamp = 'WRONG'\n self._CreateZip()\n self._CreateLocalManifest('zip1 zp1 ip1 0', 'zip1 zip2 ip2 1', 'dex1 - ip3 0')\n try:\n self._CallIncrementalInstall(incremental=True)\n self.fail('Should have quit if install timestamp is wrong')\n except SystemExit:\n pass\n", "method_code": " def _CallIncrementalInstall(self, incremental, native_libs=None, split_main_apk=None, split_apks=None, start_type='no'):\n if split_main_apk:\n apk = split_main_apk\n elif incremental:\n apk = None\n else:\n apk = self._APK\n incremental_install.IncrementalInstall(adb_path=self._ADB_PATH, execroot=self._EXEC_ROOT, stub_datafile=self._STUB_DATAFILE, dexmanifest=self._DEXMANIFEST, apk=apk, resource_apk=self._RESOURCE_APK, split_main_apk=split_main_apk, split_apks=split_apks, native_libs=native_libs, output_marker=self._OUTPUT_MARKER, adb_jobs=1, start_type=start_type, user_home_dir='/home/root')\n ", "context": "class IncrementalInstallTest(unittest.TestCase):\n def _CallIncrementalInstall(self, incremental, native_libs=None, split_main_apk=None, split_apks=None, start_type='no'): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _CreateZip(self, name='zip1', *files): ...\n def _CreateLocalManifest(self, *lines): ...\n def _CreateRemoteManifest(self, *lines): ...\n def _GetDeviceAppPath(self, f): ...\n def _GetDeviceFile(self, f): ...\n def _PutDeviceFile(self, f, content): ...\n def _DeleteDeviceFile(self, f): ...\n def testUploadToPristineDevice(self): ...\n def testSplitInstallToPristineDevice(self): ...\n def testSplitInstallUnchanged(self): ...\n def testSplitInstallChanges(self): ...\n def testMissingNativeManifestWithIncrementalInstall(self): ...\n def testNonIncrementalInstallOverwritesNativeLibs(self): ...\n def testNativeAbiCompatibility(self): ...\n def testUploadNativeLibs(self): ...\n def testUploadWithOneChangedFile(self): ...\n def testFullUploadWithOneChangedFile(self): ...\n def testUploadWithNewFile(self): ...\n def testDeletesFile(self): ...\n def testNothingToUpdate(self): ...\n def testNoResourcesToUpdate(self): ...\n def testUpdateResources(self): ...\n def testNoDevice(self): ...\n def testUnauthorizedDevice(self): ...\n def testInstallFailure(self): ...\n def testStartCold(self): ...\n def testColdStop(self): ...\n def testWarmStop(self): ...\n def testMultipleDevicesError(self): ...\n def testIncrementalInstallOnPristineDevice(self): ...\n def testIncrementalInstallWithWrongInstallTimestamp(self): ...\n def testSdkTooOld(self): ...\n\n _DEXMANIFEST = 'dexmanifest.txt'\n _ADB_PATH = '/test/adb'\n _OUTPUT_MARKER = 'full_deploy_marker'\n _APK = 'myapp_incremental.apk'\n _RESOURCE_APK = 'incremental.ap_'\n _STUB_DATAFILE = 'stub_application_data.txt'\n _OLD_APP_PACKGE = 'old.app.package'\n _APP_PACKAGE = 'new.app.package'\n _EXEC_ROOT = '.'\n", "repository": "shiningstarpxx/marvel", "test_name": "testMissingNativeManifestWithIncrementalInstall", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000391.py"} {"focal_file": "tools/android/incremental_install_test.py", "focal_class": null, "focal_method": "_PutDeviceFile", "tests": "import unittest\n\nclass Test_PutDeviceFile(unittest.TestCase):\n def testDeletesFile(self):\n self._CreateRemoteManifest('zip1 zp1 ip1 0', 'zip1 zip2 ip2 1')\n self._PutDeviceFile('dex/ip1', 'content1')\n self._PutDeviceFile('dex/ip2', 'content2')\n self._PutDeviceFile('install_timestamp', '1')\n self._mock_adb.package_timestamp = '1'\n self._CreateZip('zip1', ('zp1', 'content1'))\n self._CreateLocalManifest('zip1 zp1 ip1 0')\n self.assertTrue(self._GetDeviceAppPath('dex/ip2') in self._mock_adb.files)\n self._CallIncrementalInstall(incremental=True)\n self.assertFalse(self._GetDeviceAppPath('dex/ip2') in self._mock_adb.files)\n", "method_code": " def _PutDeviceFile(self, f, content):\n self._mock_adb.files[self._GetDeviceAppPath(f)] = content\n ", "context": "class IncrementalInstallTest(unittest.TestCase):\n def _PutDeviceFile(self, f, content): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _CreateZip(self, name='zip1', *files): ...\n def _CreateLocalManifest(self, *lines): ...\n def _CreateRemoteManifest(self, *lines): ...\n def _GetDeviceAppPath(self, f): ...\n def _GetDeviceFile(self, f): ...\n def _DeleteDeviceFile(self, f): ...\n def _CallIncrementalInstall(self, incremental, native_libs=None, split_main_apk=None, split_apks=None, start_type='no'): ...\n def testUploadToPristineDevice(self): ...\n def testSplitInstallToPristineDevice(self): ...\n def testSplitInstallUnchanged(self): ...\n def testSplitInstallChanges(self): ...\n def testMissingNativeManifestWithIncrementalInstall(self): ...\n def testNonIncrementalInstallOverwritesNativeLibs(self): ...\n def testNativeAbiCompatibility(self): ...\n def testUploadNativeLibs(self): ...\n def testUploadWithOneChangedFile(self): ...\n def testFullUploadWithOneChangedFile(self): ...\n def testUploadWithNewFile(self): ...\n def testDeletesFile(self): ...\n def testNothingToUpdate(self): ...\n def testNoResourcesToUpdate(self): ...\n def testUpdateResources(self): ...\n def testNoDevice(self): ...\n def testUnauthorizedDevice(self): ...\n def testInstallFailure(self): ...\n def testStartCold(self): ...\n def testColdStop(self): ...\n def testWarmStop(self): ...\n def testMultipleDevicesError(self): ...\n def testIncrementalInstallOnPristineDevice(self): ...\n def testIncrementalInstallWithWrongInstallTimestamp(self): ...\n def testSdkTooOld(self): ...\n\n _DEXMANIFEST = 'dexmanifest.txt'\n _ADB_PATH = '/test/adb'\n _OUTPUT_MARKER = 'full_deploy_marker'\n _APK = 'myapp_incremental.apk'\n _RESOURCE_APK = 'incremental.ap_'\n _STUB_DATAFILE = 'stub_application_data.txt'\n _OLD_APP_PACKGE = 'old.app.package'\n _APP_PACKAGE = 'new.app.package'\n _EXEC_ROOT = '.'\n", "repository": "shiningstarpxx/marvel", "test_name": "testDeletesFile", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000392.py"} {"focal_file": "tools/android/merge_manifests_test.py", "focal_class": null, "focal_method": "Reformat", "tests": "import unittest\n\nclass Test_Reformat(unittest.TestCase):\n def testReformat(self):\n text = ' a\\n b\\n\\n\\n \\t c'\n expected = 'a\\nb\\nc'\n self.assertEquals(expected, Reformat(text))\n", "method_code": "def Reformat(string):\n \"\"\"Reformat for comparison.\"\"\"\n string = re.compile('^[ \\\\t]*\\\\n?', re.MULTILINE).sub('', string)\n return string", "context": "def Reformat(string): ...\ndef Reformat(string): ...\n", "repository": "shiningstarpxx/marvel", "test_name": "testReformat", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000393.py"} {"focal_file": "tools/android/stubify_manifest_test.py", "focal_class": null, "focal_method": "GetApplication", "tests": "import unittest\n\nclass Test_GetApplication(unittest.TestCase):\n def testReplacesOldApplication(self):\n new_manifest, old_application, app_pkg = Stubify(MANIFEST_WITH_APPLICATION)\n self.assertEqual('com.google.package', app_pkg)\n self.assertEqual('old.application', old_application)\n self.assertEqual(STUB_APPLICATION, self.GetApplication(new_manifest))\n\n def testAddsNewAplication(self):\n new_manifest, old_application, app_pkg = Stubify(MANIFEST_WITHOUT_APPLICATION)\n self.assertEqual('com.google.package', app_pkg)\n self.assertEqual('android.app.Application', old_application)\n self.assertEqual(STUB_APPLICATION, self.GetApplication(new_manifest))\n", "method_code": " def GetApplication(self, manifest_string):\n manifest = ElementTree.fromstring(manifest_string)\n application = manifest.find('application')\n return application.get('{%s}name' % ANDROID)\n ", "context": "class StubifyTest(unittest.TestCase):\n def GetApplication(self, manifest_string): ...\n def testReplacesOldApplication(self): ...\n def testAddsNewAplication(self): ...\n def testRemovesHasCode(self): ...\n def assertHasPermission(self, manifest_string, permission): ...\n def testAddsPermission(self): ...\n def testDoesNotDuplicatePermission(self): ...\n def testBadManifest(self): ...\n def testTooManyApplications(self): ...\n", "repository": "shiningstarpxx/marvel", "test_name": "testReplacesOldApplication", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000394.py"} {"focal_file": "tools/android/stubify_manifest_test.py", "focal_class": null, "focal_method": "assertHasPermission", "tests": "import unittest\n\nclass Test_assertHasPermission(unittest.TestCase):\n def testAddsPermission(self):\n self.assertHasPermission(Stubify(MANIFEST_WITH_APPLICATION)[0], READ_EXTERNAL_STORAGE)\n\n def testDoesNotDuplicatePermission(self):\n self.assertHasPermission(Stubify(MANIFEST_WITH_PERMISSION)[0], READ_EXTERNAL_STORAGE)\n", "method_code": " def assertHasPermission(self, manifest_string, permission):\n manifest = ElementTree.fromstring(manifest_string)\n nodes = manifest.findall('uses-permission[@android:name=\"%s\"]' % permission, namespaces={'android': ANDROID})\n self.assertEqual(1, len(nodes))\n ", "context": "class StubifyTest(unittest.TestCase):\n def assertHasPermission(self, manifest_string, permission): ...\n def GetApplication(self, manifest_string): ...\n def testReplacesOldApplication(self): ...\n def testAddsNewAplication(self): ...\n def testRemovesHasCode(self): ...\n def testAddsPermission(self): ...\n def testDoesNotDuplicatePermission(self): ...\n def testBadManifest(self): ...\n def testTooManyApplications(self): ...\n", "repository": "shiningstarpxx/marvel", "test_name": "testAddsPermission", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000395.py"} {"focal_file": "tools/jdk/proguard_whitelister_test.py", "focal_class": null, "focal_method": "_TestInvalidConfig", "tests": "import unittest\n\nclass Test_TestInvalidConfig(unittest.TestCase):\n def testInvalidNoteConfig(self):\n self._TestInvalidConfig(['-dontnote'], '# We don\"t want libraries disabling notes globally.\\n-dontnote')\n\n def testInvalidWarnConfig(self):\n self._TestInvalidConfig(['-dontwarn'], '# We don\"t want libraries disabling warnings globally.\\n-dontwarn')\n\n def testInvalidOptimizationConfig(self):\n self._TestInvalidConfig(['-optimizations'], '# We don\"t want libraries disabling global optimizations.\\n-optimizations !class/merging/*,!code/allocation/variable')\n", "method_code": " def _TestInvalidConfig(self, invalid_args, config):\n tmpdir = os.environ['TEST_TMPDIR']\n input_path = os.path.join(tmpdir, 'proguard_whitelister_test_input.cfg')\n with open(input_path, 'w') as f:\n f.write(config)\n output_path = os.path.join(tmpdir, 'proguard_whitelister_test_output.cfg')\n validator = self._CreateValidator(input_path, output_path)\n try:\n validator.ValidateAndWriteOutput()\n self.fail()\n except RuntimeError as e:\n for invalid_arg in invalid_args:\n self.assertTrue(invalid_arg in str(e))\n ", "context": "class ProguardConfigValidatorTest(unittest.TestCase):\n def _TestInvalidConfig(self, invalid_args, config): ...\n def _CreateValidator(self, input_path, output_path): ...\n def testValidConfig(self): ...\n def testInvalidNoteConfig(self): ...\n def testInvalidWarnConfig(self): ...\n def testInvalidOptimizationConfig(self): ...\n def testMultipleInvalidArgs(self): ...\n", "repository": "shiningstarpxx/marvel", "test_name": "testInvalidNoteConfig", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000396.py"} {"focal_file": "functions/lib/model/slack.py", "focal_class": "SlackResponseMessage", "focal_method": "build", "tests": "import unittest\n\nclass Test_SlackResponseMessage_build(unittest.TestCase):\n def test_slack_response_message_invalid_channel(self):\n message = 'some text'\n response_message = SlackResponseMessage(message).build()\n self.assertEqual({'response_type': 'ephemeral', 'text': message}, response_message)\n", "method_code": " def build(self):\n return {'response_type': self.response_type, 'text': self.text}\n ", "context": "class SlackResponseMessage(object):\n def build(self): ...\n def __init__(self, text, response_type=SlackResponseType.ephemeral): ...\n\n self.text = text\n", "repository": "bennybauer/Shhh", "test_name": "test_slack_response_message_invalid_channel", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000397.py"} {"focal_file": "test/test_base_config.py", "focal_class": null, "focal_method": "_get_json_config", "tests": "import unittest\n\nclass Test_get_json_config(unittest.TestCase):\n def test_json_config(self):\n c = config.BaseConfig(initial_config_file='test/test.json')\n content_dict = self._get_json_config()\n for key in content_dict.keys():\n self.assertEqual(content_dict[key], c._config[key])\n", "method_code": " def _get_json_config(self, filename=os.path.join(MH_DIR, 'configs', 'test', 'test.json'), output='dict'):\n fh = open(filename)\n contents = json.load(fh)\n fh.close()\n if 'output' == 'dict':\n return dict(contents)\n else:\n return contents\n ", "context": "class TestParseConfigFile(unittest.TestCase):\n def _get_json_config(self, filename=os.path.join(MH_DIR, 'configs', 'test', 'test.json'), output='dict'): ...\n def _get_python_config(self, filename=os.path.join(MH_DIR, 'configs', 'test', 'test.py'), output='dict'): ...\n def test_json_config(self): ...\n def test_python_config(self): ...\n def test_illegal_config(self): ...\n def test_illegal_suffix(self): ...\n def test_malformed_json(self): ...\n def test_malformed_python(self): ...\n def test_multiple_config_files_override_string(self): ...\n def test_multiple_config_files_override_list(self): ...\n def test_multiple_config_files_override_dict(self): ...\n def test_multiple_config_files_keep_string(self): ...\n def test_optional_config_files_override_value(self): ...\n def test_optional_config_files_missing_config(self): ...\n def test_optional_config_files_keep_string(self): ...\n", "repository": "escapewindow/mozharness", "test_name": "test_json_config", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000398.py"} {"focal_file": "test/test_base_config.py", "focal_class": null, "focal_method": "_get_python_config", "tests": "import unittest\n\nclass Test_get_python_config(unittest.TestCase):\n def test_python_config(self):\n c = config.BaseConfig(initial_config_file='test/test.py')\n config_dict = self._get_python_config()\n for key in config_dict.keys():\n self.assertEqual(config_dict[key], c._config[key])\n", "method_code": " def _get_python_config(self, filename=os.path.join(MH_DIR, 'configs', 'test', 'test.py'), output='dict'):\n global_dict = {}\n local_dict = {}\n execfile(filename, global_dict, local_dict)\n return local_dict['config']\n ", "context": "class TestParseConfigFile(unittest.TestCase):\n def _get_python_config(self, filename=os.path.join(MH_DIR, 'configs', 'test', 'test.py'), output='dict'): ...\n def _get_json_config(self, filename=os.path.join(MH_DIR, 'configs', 'test', 'test.json'), output='dict'): ...\n def test_json_config(self): ...\n def test_python_config(self): ...\n def test_illegal_config(self): ...\n def test_illegal_suffix(self): ...\n def test_malformed_json(self): ...\n def test_malformed_python(self): ...\n def test_multiple_config_files_override_string(self): ...\n def test_multiple_config_files_override_list(self): ...\n def test_multiple_config_files_override_dict(self): ...\n def test_multiple_config_files_keep_string(self): ...\n def test_optional_config_files_override_value(self): ...\n def test_optional_config_files_missing_config(self): ...\n def test_optional_config_files_keep_string(self): ...\n", "repository": "escapewindow/mozharness", "test_name": "test_python_config", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000399.py"} {"focal_file": "test/test_base_config.py", "focal_class": null, "focal_method": "get_locked_ROD", "tests": "import unittest\n\nclass Test_get_locked_ROD(unittest.TestCase):\n def test_locked_set(self):\n r = self.get_locked_ROD()\n try:\n r['e'] = 2\n except:\n pass\n else:\n self.assertEqual(0, 1, msg=\"can set r['e'] when locked\")\n\n def test_locked_del(self):\n r = self.get_locked_ROD()\n try:\n del r['e']\n except:\n pass\n else:\n self.assertEqual(0, 1, \"can del r['e'] when locked\")\n\n def test_locked_popitem(self):\n r = self.get_locked_ROD()\n self.assertRaises(AssertionError, r.popitem)\n\n def test_locked_update(self):\n r = self.get_locked_ROD()\n self.assertRaises(AssertionError, r.update, {})\n\n def test_locked_pop(self):\n r = self.get_locked_ROD()\n self.assertRaises(AssertionError, r.pop)\n\n def test_locked_clear(self):\n r = self.get_locked_ROD()\n self.assertRaises(AssertionError, r.clear)\n", "method_code": " def get_locked_ROD(self):\n r = config.ReadOnlyDict(self.control_dict)\n r.lock()\n return r\n ", "context": "class TestReadOnlyDict(unittest.TestCase):\n def get_locked_ROD(self): ...\n def get_unlocked_ROD(self): ...\n def test_create_ROD(self): ...\n def test_pop_item(self): ...\n def test_pop(self): ...\n def test_set(self): ...\n def test_del(self): ...\n def test_clear(self): ...\n def test_set_default(self): ...\n def test_locked_set(self): ...\n def test_locked_del(self): ...\n def test_locked_popitem(self): ...\n def test_locked_update(self): ...\n def test_locked_set_default(self): ...\n def test_locked_pop(self): ...\n def test_locked_clear(self): ...\n def test_locked_second_level_dict_pop(self): ...\n def test_locked_second_level_list_pop(self): ...\n def test_locked_third_level_mutate(self): ...\n def test_locked_object_in_tuple_mutate(self): ...\n def test_locked_second_level_dict_pop2(self): ...\n def test_locked_second_level_list_pop2(self): ...\n def test_locked_third_level_mutate2(self): ...\n def test_locked_object_in_tuple_mutate2(self): ...\n def test_locked_deepcopy_set(self): ...\n\n control_dict = {'b': '2', 'c': {'d': '4'}, 'e': ['f', 'g'], 'e': ['f', 'g', {'turtles': ['turtle1']}], 'd': {'turtles': ['turtle1']}}\n", "repository": "escapewindow/mozharness", "test_name": "test_locked_set", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000400.py"} {"focal_file": "test/test_base_log.py", "focal_class": null, "focal_method": "get_log_file_path", "tests": "import unittest\n\nclass Test_get_log_file_path(unittest.TestCase):\n def test_log_dir(self):\n fh = open(tmp_dir, 'w')\n fh.write('foo')\n fh.close()\n l = log.SimpleFileLogger(log_dir=tmp_dir, log_name=log_name, log_to_console=False)\n self.assertTrue(os.path.exists(tmp_dir))\n l.log_message('blah')\n self.assertTrue(os.path.exists(get_log_file_path()))\n del l\n", "method_code": "def get_log_file_path(level=None):\n if level:\n return os.path.join(tmp_dir, '%s_%s.log' % (log_name, level))\n return os.path.join(tmp_dir, '%s.log' % log_name)", "context": "def get_log_file_path(level=None): ...\ndef clean_log_dir(): ...\ndef get_log_file_path(level=None): ...\n", "repository": "escapewindow/mozharness", "test_name": "test_log_dir", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000401.py"} {"focal_file": "mozharness/base/python.py", "focal_class": null, "focal_method": "package_versions", "tests": "import unittest\n\nclass Test_package_versions(unittest.TestCase):\n def test_package_versions(self):\n example = os.path.join(here, 'pip-freeze.example.txt')\n output = file(example).read()\n mixin = python.VirtualenvMixin()\n packages = mixin.package_versions(output)\n expected = {'MakeItSo': '0.2.6', 'PyYAML': '3.10', 'Tempita': '0.5.1', 'WebOb': '1.2b3', 'coverage': '3.5.1', 'logilab-astng': '0.23.1', 'logilab-common': '0.57.1', 'mozdevice': '0.2', 'mozhttpd': '0.3', 'mozinfo': '0.3.3', 'nose': '1.1.2', 'pyflakes': '0.5.0', 'pylint': '0.25.1', 'virtualenv': '1.7.1.2', 'wsgiref': '0.1.2'}\n self.assertEqual(packages, expected)\n", "method_code": " def package_versions(self, pip_freeze_output=None, error_level=WARNING, log_output=False):\n \"\"\"\n reads packages from `pip freeze` output and returns a dict of\n {package_name: 'version'}\n \"\"\"\n packages = {}\n if pip_freeze_output is None:\n pip = self.query_python_path('pip')\n if not pip:\n self.log('package_versions: Program pip not in path', level=error_level)\n return {}\n pip_freeze_output = self.get_output_from_command([pip, 'freeze'], silent=True)\n if not isinstance(pip_freeze_output, basestring):\n self.fatal('package_versions: Error encountered running `pip freeze`: %s' % pip_freeze_output)\n for line in pip_freeze_output.splitlines():\n line = line.strip()\n if not line:\n continue\n if line.startswith('-'):\n continue\n if '==' not in line:\n self.fatal('pip_freeze_packages: Unrecognized output line: %s' % line)\n package, version = line.split('==', 1)\n packages[package] = version\n if log_output:\n self.info('Current package versions:')\n for package in packages:\n self.info(' %s == %s' % (package, packages[package]))\n return packages\n ", "context": "class VirtualenvMixin(object):\n def package_versions(self, pip_freeze_output=None, error_level=WARNING, log_output=False): ...\n def __init__(self, *args, **kwargs): ...\n def register_virtualenv_module(self, name=None, url=None, method=None, requirements=None, optional=False, two_pass=False, editable=False): ...\n def query_virtualenv_path(self): ...\n def query_python_path(self, binary='python'): ...\n def query_python_site_packages_path(self): ...\n def is_python_package_installed(self, package_name, error_level=WARNING): ...\n def install_module(self, module=None, module_url=None, install_method=None, requirements=(), optional=False, global_options=[], no_deps=False, editable=False): ...\n def create_virtualenv(self, modules=(), requirements=()): ...\n def activate_virtualenv(self): ...\n\n self._virtualenv_modules = []\n\n python_paths = {}\n site_packages_path = None\n", "repository": "escapewindow/mozharness", "test_name": "test_package_versions", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000402.py"} {"focal_file": "mozharness/mozilla/l10n/locales.py", "focal_class": null, "focal_method": "query_locales", "tests": "import unittest\n\nclass Test_query_locales(unittest.TestCase):\n def test_query_locales_locales(self):\n l = LocalesTest()\n l.locales = ['a', 'b', 'c']\n self.assertEqual(l.locales, l.query_locales())\n\n def test_query_locales_ignore_locales(self):\n l = LocalesTest()\n l.config['locales'] = ['a', 'b', 'c']\n l.config['ignore_locales'] = ['a', 'c']\n self.assertEqual(['b'], l.query_locales())\n\n def test_query_locales_config(self):\n l = LocalesTest()\n l.config['locales'] = ['a', 'b', 'c']\n self.assertEqual(l.config['locales'], l.query_locales())\n\n def test_query_locales_json(self):\n l = LocalesTest()\n l.config['locales_file'] = os.path.join(MH_DIR, 'test/helper_files/locales.json')\n l.config['base_work_dir'] = '.'\n l.config['work_dir'] = '.'\n locales = l.query_locales()\n locales.sort()\n self.assertEqual(ALL_LOCALES, locales)\n", "method_code": " def query_locales(self):\n if self.locales is not None:\n return self.locales\n c = self.config\n locales = c.get('locales', None)\n ignore_locales = c.get('ignore_locales', [])\n additional_locales = c.get('additional_locales', [])\n if locales is None:\n locales = []\n if 'locales_file' in c:\n locales_file = os.path.join(c['base_work_dir'], c['work_dir'], c['locales_file'])\n locales = self.parse_locales_file(locales_file)\n else:\n self.fatal('No way to determine locales!')\n for locale in ignore_locales:\n if locale in locales:\n self.debug('Ignoring locale %s.' % locale)\n locales.remove(locale)\n for locale in additional_locales:\n if locale not in locales:\n self.debug('Adding locale %s.' % locale)\n locales.append(locale)\n if locales is None:\n return\n if 'total_locale_chunks' and 'this_locale_chunk' in c:\n self.debug('Pre-chunking locale list: %s' % str(locales))\n locales = self.query_chunked_list(locales, c['this_locale_chunk'], c['total_locale_chunks'], sort=True)\n self.debug('Post-chunking locale list: %s' % locales)\n self.locales = locales\n return self.locales\n ", "context": "class LocalesMixin(ChunkingMixin):\n def query_locales(self): ...\n def __init__(self, **kwargs): ...\n def list_locales(self): ...\n def parse_locales_file(self, locales_file): ...\n def run_compare_locales(self, locale, halt_on_failure=False): ...\n def query_abs_dirs(self): ...\n def pull_locale_source(self, hg_l10n_base=None, parent_dir=None, vcs='hg'): ...\n\n self.abs_dirs = None\n self.locales = None\n self.gecko_locale_revisions = None\n", "repository": "escapewindow/mozharness", "test_name": "test_query_locales_locales", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000403.py"} {"focal_file": "mozharness/mozilla/l10n/locales.py", "focal_class": null, "focal_method": "parse_locales_file", "tests": "import unittest\n\nclass Test_parse_locales_file(unittest.TestCase):\n def test_parse_locales_file(self):\n l = LocalesTest()\n self.assertEqual(ALL_LOCALES, l.parse_locales_file(os.path.join(MH_DIR, 'test/helper_files/locales.txt')))\n", "method_code": " def parse_locales_file(self, locales_file):\n locales = []\n c = self.config\n platform = c.get('locales_platform', None)\n if locales_file.endswith('json'):\n locales_json = parse_config_file(locales_file)\n self.locale_dict = {}\n for locale in locales_json.keys():\n if isinstance(locales_json[locale], dict):\n if platform and platform not in locales_json[locale]['platforms']:\n continue\n self.locale_dict[locale] = locales_json[locale]['revision']\n else:\n self.locale_dict[locale] = 'default'\n locales.append(locale)\n else:\n locales = self.read_from_file(locales_file).split()\n return locales\n ", "context": "class LocalesMixin(ChunkingMixin):\n def parse_locales_file(self, locales_file): ...\n def __init__(self, **kwargs): ...\n def query_locales(self): ...\n def list_locales(self): ...\n def run_compare_locales(self, locale, halt_on_failure=False): ...\n def query_abs_dirs(self): ...\n def pull_locale_source(self, hg_l10n_base=None, parent_dir=None, vcs='hg'): ...\n\n self.abs_dirs = None\n self.locales = None\n self.gecko_locale_revisions = None\n", "repository": "escapewindow/mozharness", "test_name": "test_parse_locales_file", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000404.py"} {"focal_file": "mozharness/mozilla/l10n/locales.py", "focal_class": null, "focal_method": "query_abs_dirs", "tests": "import unittest\n\nclass Test_query_abs_dirs(unittest.TestCase):\n def test_query_abs_dirs_l10n(self):\n l = self._get_query_abs_dirs_obj()\n l.config['l10n_dir'] = 'l10n_dir'\n dirs = l.query_abs_dirs().keys()\n dirs.sort()\n expected_dirs = self.BASE_ABS_DIRS + ['abs_l10n_dir']\n expected_dirs.sort()\n self.assertEqual(dirs, expected_dirs)\n", "method_code": " def query_abs_dirs(self):\n if self.abs_dirs:\n return self.abs_dirs\n abs_dirs = super(LocalesMixin, self).query_abs_dirs()\n c = self.config\n dirs = {}\n dirs['abs_work_dir'] = os.path.join(c['base_work_dir'], c['work_dir'])\n if 'l10n_dir' in c:\n dirs['abs_l10n_dir'] = os.path.join(dirs['abs_work_dir'], c['l10n_dir'])\n if 'mozilla_dir' in c:\n dirs['abs_mozilla_dir'] = os.path.join(dirs['abs_work_dir'], c['mozilla_dir'])\n dirs['abs_locales_src_dir'] = os.path.join(dirs['abs_mozilla_dir'], c['locales_dir'])\n dirs['abs_l10n_dir'] = os.path.join(dirs['abs_work_dir'], c['l10n_dir'])\n if 'objdir' in c:\n if os.path.isabs(c['objdir']):\n dirs['abs_objdir'] = c['objdir']\n else:\n dirs['abs_objdir'] = os.path.join(dirs['abs_mozilla_dir'], c['objdir'])\n dirs['abs_merge_dir'] = os.path.join(dirs['abs_objdir'], 'merged')\n dirs['abs_locales_dir'] = os.path.join(dirs['abs_objdir'], c['locales_dir'])\n dirs['abs_compare_locales_dir'] = os.path.join(dirs['abs_work_dir'], 'compare-locales')\n for key in dirs.keys():\n if key not in abs_dirs:\n abs_dirs[key] = dirs[key]\n self.abs_dirs = abs_dirs\n return self.abs_dirs\n ", "context": "class LocalesMixin(ChunkingMixin):\n def query_abs_dirs(self): ...\n def __init__(self, **kwargs): ...\n def query_locales(self): ...\n def list_locales(self): ...\n def parse_locales_file(self, locales_file): ...\n def run_compare_locales(self, locale, halt_on_failure=False): ...\n def pull_locale_source(self, hg_l10n_base=None, parent_dir=None, vcs='hg'): ...\n\n self.abs_dirs = None\n self.locales = None\n self.gecko_locale_revisions = None\n", "repository": "escapewindow/mozharness", "test_name": "test_query_abs_dirs_l10n", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000405.py"} {"focal_file": "exporter/mutations.py", "focal_class": "ManifestMutation", "focal_method": "map_field", "tests": "import unittest\n\nclass Test_ManifestMutation_map_field(unittest.TestCase):\n def test_map_field(self):\n source_dict = {'name': 'resource_name', 'property': 'value', 'none_property': None}\n dest_dict = {}\n tm = ManifestMutation(source_dict)\n tm.map_field('name', dest_dict, source_dict)\n self.assertIn('name', dest_dict)\n self.assertEqual(dest_dict['name'], 'resource_name')\n tm.map_field('mutated_name', dest_dict, source_dict, source_field='name')\n self.assertIn('mutated_name', dest_dict)\n self.assertEqual(dest_dict['mutated_name'], 'resource_name')\n with self.assertRaises(FieldNotOptionalException):\n tm.map_field('not_existent', dest_dict, source_dict, optional=False)\n tm.map_field('not_existent', dest_dict, source_dict, optional=True)\n self.assertNotIn('not_existent', dest_dict)\n tm.map_field('not_existent_w_default', dest_dict, source_dict, source_field='not_existent', optional=True, default='default')\n self.assertIn('not_existent_w_default', dest_dict)\n self.assertEqual(dest_dict['not_existent_w_default'], 'default')\n tm.map_field('mapped_property', dest_dict, source_dict, source_field='property', mapping={'value': 'mapped_value'})\n self.assertIn('mapped_property', dest_dict)\n self.assertEqual(dest_dict['mapped_property'], 'mapped_value')\n tm.map_field('none_property', dest_dict, source_dict)\n self.assertNotIn('none_property', dest_dict)\n", "method_code": " def map_field(self, dest_field, dest_dict, source_dict, source_field=None, optional=False, mapping={}, default=None):\n if not source_field:\n source_field = dest_field\n if source_field in source_dict and source_dict[source_field] in mapping:\n dest_dict[dest_field] = mapping[source_dict[source_field]]\n elif source_field in source_dict:\n if source_dict[source_field] != None:\n dest_dict[dest_field] = source_dict[source_field]\n elif default:\n dest_dict[dest_field] = default\n elif not optional:\n raise FieldNotOptionalException('Field {} is not optional'.format(dest_field))\n ", "context": "class ManifestMutation(object):\n def map_field(self, dest_field, dest_dict, source_dict, source_field=None, optional=False, mapping={}, default=None): ...\n def __init__(self, cf_dict): ...\n def mutate_manifest(self): ...\n def map_flags(self, flags, source_flags): ...\n def map_fields(self, dest_dict, source_dict, fields): ...\n def map_list_fields(self, dest_dict, source_dict, fields): ...\n def map_list_field(self, dest_field, dest_dict, source_dict, source_field=None, key_fn=lambda x: x, fmt=None): ...\n\n self.cf_dict = cf_dict\n", "repository": "SpringerPE/cf-configuration-exporter", "test_name": "test_map_field", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000406.py"} {"focal_file": "exporter/mutations.py", "focal_class": "ManifestMutation", "focal_method": "map_list_field", "tests": "import unittest\n\nclass Test_ManifestMutation_map_list_field(unittest.TestCase):\n def test_map_list_field(self):\n source_dict = {'name': 'resource_name', 'list_item': ['value1', 'value2']}\n dest_dict = {}\n tm = ManifestMutation(source_dict)\n tm.map_list_field('list_item', dest_dict, source_dict)\n self.assertIn('list_item', dest_dict)\n self.assertEqual(['value1', 'value2'], dest_dict['list_item'])\n tm.map_list_field('list_item', dest_dict, source_dict, fmt='fmt_{}')\n self.assertIn('list_item', dest_dict)\n self.assertEqual(['fmt_value1', 'fmt_value2'], dest_dict['list_item'])\n tm.map_list_field('list_item', dest_dict, source_dict, key_fn=lambda x: 'mapped')\n self.assertIn('list_item', dest_dict)\n self.assertEqual(['mapped', 'mapped'], dest_dict['list_item'])\n", "method_code": " def map_list_field(self, dest_field, dest_dict, source_dict, source_field=None, key_fn=lambda x: x, fmt=None):\n if not source_field:\n source_field = dest_field\n dest_dict[dest_field] = []\n if not source_field in source_dict:\n return\n for elem in source_dict[source_field]:\n elem = fmt.format(key_fn(elem)) if fmt else key_fn(elem)\n dest_dict[dest_field].append(elem)\n ", "context": "class ManifestMutation(object):\n def map_list_field(self, dest_field, dest_dict, source_dict, source_field=None, key_fn=lambda x: x, fmt=None): ...\n def __init__(self, cf_dict): ...\n def mutate_manifest(self): ...\n def map_flags(self, flags, source_flags): ...\n def map_fields(self, dest_dict, source_dict, fields): ...\n def map_list_fields(self, dest_dict, source_dict, fields): ...\n def map_field(self, dest_field, dest_dict, source_dict, source_field=None, optional=False, mapping={}, default=None): ...\n\n self.cf_dict = cf_dict\n", "repository": "SpringerPE/cf-configuration-exporter", "test_name": "test_map_list_field", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000407.py"} {"focal_file": "plot/plot/items.py", "focal_class": null, "focal_method": "notifyProperty", "tests": "import unittest\n\nclass Test_notifyProperty(unittest.TestCase):\n def testNotifyProperty(self):\n \"\"\"Property without type casting with notification.\n\n Init property, register listener, set the same value,\n set a different value, unregister listener.\n \"\"\"\n\n class TestItem(items.PlotItem):\n tester = items.notifyProperty('_tester', doc='Test')\n testItem = TestItem()\n self.assertEqual(TestItem.tester.__doc__, 'Test')\n testItem.tester = 1\n self.assertEqual(testItem.tester, 1)\n testItem.addListener(self.listener)\n testItem.tester = 1\n testItem.tester = 2\n testItem.removeListener(self.listener)\n self.assertEqual(len(self.notifications), 2)\n self.assertEqual(self.notifications[0], (testItem, 'set', {'attr': 'tester', 'value': 2}))\n self.assertEqual(self.notifications[1], (testItem, 'needRedisplay', {}))\n\n def testNotifyPropertyWithType(self):\n \"\"\"Property with type casting with notification.\n\n Init property, register listener, set the same value,\n set a different value, unregister listener.\n \"\"\"\n\n class TestItem(items.PlotItem):\n tester = items.notifyProperty('_tester', str, doc='Test')\n testItem = TestItem()\n testItem.tester = 1\n self.assertEqual(testItem.tester, '1')\n testItem.addListener(self.listener)\n testItem.tester = 1\n testItem.tester = 2\n testItem.removeListener(self.listener)\n self.assertEqual(len(self.notifications), 2)\n self.assertEqual(self.notifications[0], (testItem, 'set', {'attr': 'tester', 'value': '2'}))\n self.assertEqual(self.notifications[1], (testItem, 'needRedisplay', {}))\n", "method_code": "def notifyProperty(name, type_=None, doc=None):\n \"\"\"Property calling :method:`_notifySet` upon changes.\n\n Intended to be used by :class:`PlotItem' and derived classes.\n\n :param str name: The name of the attribute to wrap.\n :param type type_: Type of the attribute.\n :return: A property\n \"\"\"\n\n def getter(self):\n return getattr(self, name)\n if type_ is not None:\n\n def setter(self, value):\n value = type_(value)\n if not hasattr(self, name) or value != getattr(self, name):\n setattr(self, name, value)\n self._notifySet(name.lstrip('_'), value)\n else:\n\n def setter(self, value):\n if not hasattr(self, name) or value != getattr(self, name):\n setattr(self, name, value)\n self._notifySet(name.lstrip('_'), value)\n return property(getter, setter, doc=doc)", "context": "def notifyProperty(name, type_=None, doc=None): ...\ndef notifyProperty(name, type_=None, doc=None): ...\n", "repository": "t20100/sandbox", "test_name": "testNotifyProperty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000408.py"} {"focal_file": "plot/plot/utils.py", "focal_class": null, "focal_method": "proxyProperty", "tests": "import unittest\n\nclass Test_proxyProperty(unittest.TestCase):\n def testProxyProperty(self):\n \"\"\"Test proxyProperty over attribute and property\"\"\"\n\n class Leaf(object):\n \"\"\"The class that is wrapped\"\"\"\n\n def __init__(self):\n self._prop = 'value prop'\n self.instanceAttribute = 'value attribute'\n\n @property\n def prop(self):\n return self._prop\n\n @prop.setter\n def prop(self, value):\n self._prop = value\n\n class Composite(object):\n \"\"\"The wrapping class\"\"\"\n\n def __init__(self):\n self.leaf = Leaf()\n testAttribute = utils.proxyProperty('leaf', 'instanceAttribute')\n testPropertyRO = utils.proxyProperty('leaf', 'prop', setter=False)\n testProperty = utils.proxyProperty('leaf', 'prop', setter=True)\n test = Composite()\n self.assertEqual(test.testAttribute, 'value attribute')\n self.assertEqual(test.testPropertyRO, 'value prop')\n with self.assertRaises(AttributeError):\n test.testPropertyRO = None\n self.assertEqual(test.testProperty, 'value prop')\n test.testProperty = 'new value'\n self.assertEqual(test.testProperty, 'new value')\n", "method_code": "def proxyProperty(component, attribute, setter=True, doc=None):\n \"\"\"Create a property that wraps an attribute of an attribute.\n\n Useful for composition.\n\n :param str component: The name of the component attribute.\n :param str attribute: The name of attribute of the attribute to wrap.\n :param bool setter: True to provide a setter, False for read-only property.\n :param str doc: The docstring of the property.\n :return: A property\n \"\"\"\n\n def getter(self):\n instance = getattr(self, component)\n return getattr(instance, attribute)\n if not setter:\n return property(getter, doc=doc)\n else:\n\n def setter(self, value):\n instance = getattr(self, component)\n setattr(instance, attribute, value)\n return property(getter, setter, doc=doc)", "context": "def proxyProperty(component, attribute, setter=True, doc=None): ...\ndef proxyProperty(component, attribute, setter=True, doc=None): ...\n", "repository": "t20100/sandbox", "test_name": "testProxyProperty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000409.py"} {"focal_file": "lib/matplotlib/transforms.py", "focal_class": "mtrans.Affine2D", "focal_method": "transform_affine", "tests": "import unittest\n\nclass Test_mtrans_Affine2D_transform_affine(unittest.TestCase):\n def test_transform_single_point():\n t = mtrans.Affine2D()\n r = t.transform_affine((1, 1))\n assert r.shape == (2,)\n", "method_code": "def transform_affine(self, points):\n if not ma.isMaskedArray(points) and (not isinstance(points, np.ndarray)):\n warnings.warn(('A non-numpy array of type %s was passed in for ' + 'transformation. Please correct this.') % type(points))\n return self._transform_affine(points)", "context": "def transform_affine(self, points): ...\ndef blended_transform_factory(x_transform, y_transform): ...\ndef composite_transform_factory(a, b): ...\ndef nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): ...\ndef interval_contains(interval, val): ...\ndef interval_contains_open(interval, val): ...\ndef offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'): ...\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_transform_single_point", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000410.py"} {"focal_file": "lib/matplotlib/transforms.py", "focal_class": null, "focal_method": "transform", "tests": "import unittest\n\nclass Test_transform(unittest.TestCase):\n @cleanup\n def test_log_transform():\n fig, ax = plt.subplots()\n ax.set_yscale('log')\n ax.transData.transform((1, 1))\n", "method_code": " def transform(self, values):\n \"\"\"\n Performs the transformation on the given array of values.\n \n Accepts a numpy array of shape (N x :attr:`input_dims`) and\n returns a numpy array of shape (N x :attr:`output_dims`).\n \n Alternatively, accepts a numpy array of length :attr:`input_dims`\n and returns a numpy array of length :attr:`output_dims`.\n \"\"\"\n values = np.asanyarray(values)\n ndim = values.ndim\n values = values.reshape((-1, self.input_dims))\n res = self.transform_affine(self.transform_non_affine(values))\n if ndim == 0:\n assert not np.ma.is_masked(res)\n return res[0, 0]\n if ndim == 1:\n return res.reshape(-1)\n elif ndim == 2:\n return res\n else:\n raise ValueError('Input values must have shape (N x {dims}) or ({dims}).'.format(dims=self.input_dims))\n return res\n ", "context": "class Transform(TransformNode):\n def transform(self, values): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __eq__(self, other): ...\n def _iter_break_from_left_to_right(self): ...\n def depth(self): ...\n def contains_branch(self, other): ...\n def contains_branch_seperately(self, other_transform): ...\n def __sub__(self, other): ...\n def __array__(self, *args, **kwargs): ...\n def transform_affine(self, values): ...\n def transform_non_affine(self, values): ...\n def transform_bbox(self, bbox): ...\n def get_affine(self): ...\n def get_matrix(self): ...\n def transform_point(self, point): ...\n def transform_path(self, path): ...\n def transform_path_affine(self, path): ...\n def transform_path_non_affine(self, path): ...\n def transform_angles(self, angles, pts, radians=False, pushoff=1e-05): ...\n def inverted(self): ...\n\n input_dims = None\n output_dims = None\n has_inverse = False\n is_separable = False\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000411.py"} {"focal_file": "lib/matplotlib/transforms.py", "focal_class": "Bbox", "focal_method": "overlaps", "tests": "import unittest\n\nclass Test_Bbox_overlaps(unittest.TestCase):\n @cleanup\n def test_nan_overlap():\n a = Bbox([[0, 0], [1, 1]])\n b = Bbox([[0, 0], [1, np.nan]])\n assert not a.overlaps(b)\n", "method_code": " def overlaps(self, other):\n \"\"\"\n Returns True if this bounding box overlaps with the given\n bounding box *other*.\n \"\"\"\n ax1, ay1, ax2, ay2 = self._get_extents()\n bx1, by1, bx2, by2 = other._get_extents()\n if any((np.isnan(v) for v in [ax1, ay1, ax2, ay2, bx1, by1, bx2, by2])):\n return False\n if ax2 < ax1:\n ax2, ax1 = (ax1, ax2)\n if ay2 < ay1:\n ay2, ay1 = (ay1, ay2)\n if bx2 < bx1:\n bx2, bx1 = (bx1, bx2)\n if by2 < by1:\n by2, by1 = (by1, by2)\n return not (bx2 < ax1 or by2 < ay1 or bx1 > ax2 or (by1 > ay2))\n ", "context": "class BboxBase(TransformNode):\n def overlaps(self, other): ...\n def frozen(self): ...\n def __array__(self, *args, **kwargs): ...\n def is_unit(self): ...\n def _get_x0(self): ...\n def _get_y0(self): ...\n def _get_x1(self): ...\n def _get_y1(self): ...\n def _get_p0(self): ...\n def _get_p1(self): ...\n def _get_xmin(self): ...\n def _get_ymin(self): ...\n def _get_xmax(self): ...\n def _get_ymax(self): ...\n def _get_min(self): ...\n def _get_max(self): ...\n def _get_intervalx(self): ...\n def _get_intervaly(self): ...\n def _get_width(self): ...\n def _get_height(self): ...\n def _get_size(self): ...\n def _get_bounds(self): ...\n def _get_extents(self): ...\n def get_points(self): ...\n def containsx(self, x): ...\n def containsy(self, y): ...\n def contains(self, x, y): ...\n def fully_containsx(self, x): ...\n def fully_containsy(self, y): ...\n def fully_contains(self, x, y): ...\n def fully_overlaps(self, other): ...\n def transformed(self, transform): ...\n def inverse_transformed(self, transform): ...\n def anchored(self, c, container=None): ...\n def shrunk(self, mx, my): ...\n def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0): ...\n def splitx(self, *args): ...\n def splity(self, *args): ...\n def count_contains(self, vertices): ...\n def count_overlaps(self, bboxes): ...\n def expanded(self, sw, sh): ...\n def padded(self, p): ...\n def translated(self, tx, ty): ...\n def corners(self): ...\n def rotated(self, radians): ...\n def union(bboxes): ...\n def intersection(bbox1, bbox2): ...\n\n is_bbox = True\n is_affine = True\n frozen.__doc__ = TransformNode.__doc__\n x0 = property(_get_x0, None, None, '\\n (property) :attr:`x0` is the first of the pair of *x* coordinates that\\n define the bounding box. :attr:`x0` is not guaranteed to be\\n less than :attr:`x1`. If you require that, use :attr:`xmin`.')\n y0 = property(_get_y0, None, None, '\\n (property) :attr:`y0` is the first of the pair of *y* coordinates that\\n define the bounding box. :attr:`y0` is not guaranteed to be\\n less than :attr:`y1`. If you require that, use :attr:`ymin`.')\n x1 = property(_get_x1, None, None, '\\n (property) :attr:`x1` is the second of the pair of *x* coordinates\\n that define the bounding box. :attr:`x1` is not guaranteed to be\\n greater than :attr:`x0`. If you require that, use :attr:`xmax`.')\n y1 = property(_get_y1, None, None, '\\n (property) :attr:`y1` is the second of the pair of *y* coordinates\\n that define the bounding box. :attr:`y1` is not guaranteed to be\\n greater than :attr:`y0`. If you require that, use :attr:`ymax`.')\n p0 = property(_get_p0, None, None, '\\n (property) :attr:`p0` is the first pair of (*x*, *y*) coordinates\\n that define the bounding box. It is not guaranteed to be the\\n bottom-left corner. For that, use :attr:`min`.')\n p1 = property(_get_p1, None, None, '\\n (property) :attr:`p1` is the second pair of (*x*, *y*) coordinates\\n that define the bounding box. It is not guaranteed to be the\\n top-right corner. For that, use :attr:`max`.')\n xmin = property(_get_xmin, None, None, '\\n (property) :attr:`xmin` is the left edge of the bounding box.')\n ymin = property(_get_ymin, None, None, '\\n (property) :attr:`ymin` is the bottom edge of the bounding box.')\n xmax = property(_get_xmax, None, None, '\\n (property) :attr:`xmax` is the right edge of the bounding box.')\n ymax = property(_get_ymax, None, None, '\\n (property) :attr:`ymax` is the top edge of the bounding box.')\n min = property(_get_min, None, None, '\\n (property) :attr:`min` is the bottom-left corner of the bounding\\n box.')\n max = property(_get_max, None, None, '\\n (property) :attr:`max` is the top-right corner of the bounding box.')\n intervalx = property(_get_intervalx, None, None, '\\n (property) :attr:`intervalx` is the pair of *x* coordinates that define\\n the bounding box. It is not guaranteed to be sorted from left to\\n right.')\n intervaly = property(_get_intervaly, None, None, '\\n (property) :attr:`intervaly` is the pair of *y* coordinates that define\\n the bounding box. It is not guaranteed to be sorted from bottom to\\n top.')\n width = property(_get_width, None, None, '\\n (property) The width of the bounding box. It may be negative if\\n :attr:`x1` < :attr:`x0`.')\n height = property(_get_height, None, None, '\\n (property) The height of the bounding box. It may be negative if\\n :attr:`y1` < :attr:`y0`.')\n size = property(_get_size, None, None, '\\n (property) The width and height of the bounding box. May be negative,\\n in the same way as :attr:`width` and :attr:`height`.')\n bounds = property(_get_bounds, None, None, '\\n (property) Returns (:attr:`x0`, :attr:`y0`, :attr:`width`,\\n :attr:`height`).')\n extents = property(_get_extents, None, None, '\\n (property) Returns (:attr:`x0`, :attr:`y0`, :attr:`x1`,\\n :attr:`y1`).')\n coefs = {'C': (0.5, 0.5), 'SW': (0, 0), 'S': (0.5, 0), 'SE': (1.0, 0), 'E': (1.0, 0.5), 'NE': (1.0, 1.0), 'N': (0.5, 1.0), 'NW': (0, 1.0), 'W': (0, 0.5)}\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000412.py"} {"focal_file": "lib/matplotlib/transforms.py", "focal_class": "mtrans.Affine2D", "focal_method": "transform_angles", "tests": "import unittest\n\nclass Test_mtrans_Affine2D_transform_angles(unittest.TestCase):\n def test_transform_angles():\n t = mtrans.Affine2D()\n angles = np.array([20, 45, 60])\n points = np.array([[0, 0], [1, 1], [2, 2]])\n new_angles = t.transform_angles(angles, points)\n assert_array_almost_equal(angles, new_angles)\n assert_raises(ValueError, t.transform_angles, angles, points[0:2, 0:1])\n assert_raises(ValueError, t.transform_angles, angles, points[0:2, :])\n", "method_code": " def transform_angles(self, angles, pts, radians=False, pushoff=1e-05):\n \"\"\"\n Performs transformation on a set of angles anchored at\n specific locations.\n \n The *angles* must be a column vector (i.e., numpy array).\n \n The *pts* must be a two-column numpy array of x,y positions\n (angle transforms currently only work in 2D). This array must\n have the same number of rows as *angles*.\n \n *radians* indicates whether or not input angles are given in\n radians (True) or degrees (False; the default).\n \n *pushoff* is the distance to move away from *pts* for\n determining transformed angles (see discussion of method\n below).\n \n The transformed angles are returned in an array with the same\n size as *angles*.\n \n The generic version of this method uses a very generic\n algorithm that transforms *pts*, as well as locations very\n close to *pts*, to find the angle in the transformed system.\n \"\"\"\n if self.input_dims != 2 or self.output_dims != 2:\n raise NotImplementedError('Only defined in 2D')\n if pts.shape[1] != 2:\n raise ValueError(\"'pts' must be array with 2 columns for x,y\")\n if angles.ndim != 1 or angles.shape[0] != pts.shape[0]:\n msg = \"'angles' must be a column vector and have same number of\"\n msg += \" rows as 'pts'\"\n raise ValueError(msg)\n if not radians:\n angles = angles / 180.0 * np.pi\n pts2 = pts + pushoff * np.c_[np.cos(angles), np.sin(angles)]\n tpts = self.transform(pts)\n tpts2 = self.transform(pts2)\n d = tpts2 - tpts\n a = np.arctan2(d[:, 1], d[:, 0])\n if not radians:\n a = a * 180.0 / np.pi\n return a\n ", "context": "class Transform(TransformNode):\n def transform_angles(self, angles, pts, radians=False, pushoff=1e-05): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __eq__(self, other): ...\n def _iter_break_from_left_to_right(self): ...\n def depth(self): ...\n def contains_branch(self, other): ...\n def contains_branch_seperately(self, other_transform): ...\n def __sub__(self, other): ...\n def __array__(self, *args, **kwargs): ...\n def transform(self, values): ...\n def transform_affine(self, values): ...\n def transform_non_affine(self, values): ...\n def transform_bbox(self, bbox): ...\n def get_affine(self): ...\n def get_matrix(self): ...\n def transform_point(self, point): ...\n def transform_path(self, path): ...\n def transform_path_affine(self, path): ...\n def transform_path_non_affine(self, path): ...\n def inverted(self): ...\n\n input_dims = None\n output_dims = None\n has_inverse = False\n is_separable = False\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_transform_angles", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000413.py"} {"focal_file": "lib/matplotlib/transforms.py", "focal_class": null, "focal_method": "nonsingular", "tests": "import unittest\n\nclass Test_nonsingular(unittest.TestCase):\n def test_nonsingular():\n zero_expansion = np.array([-0.001, 0.001])\n cases = [(0, np.nan), (0, 0), (0, 7.9e-317)]\n for args in cases:\n out = np.array(mtrans.nonsingular(*args))\n assert_array_equal(out, zero_expansion)\n", "method_code": "def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):\n \"\"\"\n Modify the endpoints of a range as needed to avoid singularities.\n\n *vmin*, *vmax*\n the initial endpoints.\n\n *tiny*\n threshold for the ratio of the interval to the maximum absolute\n value of its endpoints. If the interval is smaller than\n this, it will be expanded. This value should be around\n 1e-15 or larger; otherwise the interval will be approaching\n the double precision resolution limit.\n\n *expander*\n fractional amount by which *vmin* and *vmax* are expanded if\n the original interval is too small, based on *tiny*.\n\n *increasing*: [True | False]\n If True (default), swap *vmin*, *vmax* if *vmin* > *vmax*\n\n Returns *vmin*, *vmax*, expanded and/or swapped if necessary.\n\n If either input is inf or NaN, or if both inputs are 0 or very\n close to zero, it returns -*expander*, *expander*.\n \"\"\"\n if not np.isfinite(vmin) or not np.isfinite(vmax):\n return (-expander, expander)\n swapped = False\n if vmax < vmin:\n vmin, vmax = (vmax, vmin)\n swapped = True\n maxabsvalue = max(abs(vmin), abs(vmax))\n if maxabsvalue < 1000000.0 / tiny * MINFLOAT:\n vmin = -expander\n vmax = expander\n elif vmax - vmin <= maxabsvalue * tiny:\n if vmax == 0 and vmin == 0:\n vmin = -expander\n vmax = expander\n else:\n vmin -= expander * abs(vmin)\n vmax += expander * abs(vmax)\n if swapped and (not increasing):\n vmin, vmax = (vmax, vmin)\n return (vmin, vmax)", "context": "def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): ...\ndef blended_transform_factory(x_transform, y_transform): ...\ndef composite_transform_factory(a, b): ...\ndef nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): ...\ndef interval_contains(interval, val): ...\ndef interval_contains_open(interval, val): ...\ndef offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'): ...\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_nonsingular", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000414.py"} {"focal_file": "lib/matplotlib/transforms.py", "focal_class": null, "focal_method": "contains_branch", "tests": "import unittest\n\nclass Test_contains_branch(unittest.TestCase):\n def test_contains_branch(self):\n r1 = self.ta2 + self.ta1\n r2 = self.ta2 + self.ta1\n self.assertEqual(r1, r2)\n self.assertNotEqual(r1, self.ta1)\n self.assertTrue(r1.contains_branch(r2))\n self.assertTrue(r1.contains_branch(self.ta1))\n self.assertFalse(r1.contains_branch(self.ta2))\n self.assertFalse(r1.contains_branch(self.ta2 + self.ta2))\n self.assertEqual(r1, r2)\n self.assertTrue(self.stack1.contains_branch(self.ta3))\n self.assertTrue(self.stack2.contains_branch(self.ta3))\n self.assertTrue(self.stack1.contains_branch(self.stack2_subset))\n self.assertTrue(self.stack2.contains_branch(self.stack2_subset))\n self.assertFalse(self.stack2_subset.contains_branch(self.stack1))\n self.assertFalse(self.stack2_subset.contains_branch(self.stack2))\n self.assertTrue(self.stack1.contains_branch(self.ta2 + self.ta3))\n self.assertTrue(self.stack2.contains_branch(self.ta2 + self.ta3))\n self.assertFalse(self.stack1.contains_branch(self.tn1 + self.ta2))\n", "method_code": " def contains_branch(self, other):\n \"\"\"\n Return whether the given transform is a sub-tree of this transform.\n \n This routine uses transform equality to identify sub-trees, therefore\n in many situations it is object id which will be used.\n \n For the case where the given transform represents the whole\n of this transform, returns True.\n \n \"\"\"\n if self.depth < other.depth:\n return False\n for _, sub_tree in self._iter_break_from_left_to_right():\n if sub_tree == other:\n return True\n return False\n ", "context": "class Transform(TransformNode):\n def contains_branch(self, other): ...\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __eq__(self, other): ...\n def _iter_break_from_left_to_right(self): ...\n def depth(self): ...\n def contains_branch_seperately(self, other_transform): ...\n def __sub__(self, other): ...\n def __array__(self, *args, **kwargs): ...\n def transform(self, values): ...\n def transform_affine(self, values): ...\n def transform_non_affine(self, values): ...\n def transform_bbox(self, bbox): ...\n def get_affine(self): ...\n def get_matrix(self): ...\n def transform_point(self, point): ...\n def transform_path(self, path): ...\n def transform_path_affine(self, path): ...\n def transform_path_non_affine(self, path): ...\n def transform_angles(self, angles, pts, radians=False, pushoff=1e-05): ...\n def inverted(self): ...\n\n input_dims = None\n output_dims = None\n has_inverse = False\n is_separable = False\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_contains_branch", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000415.py"} {"focal_file": "lib/google/cloud/vision/_gax.py", "focal_class": null, "focal_method": "annotate", "tests": "import unittest\n\nclass Test_annotate(unittest.TestCase):\n def test_annotation(self):\n from google.cloud.vision.feature import Feature\n from google.cloud.vision.feature import FeatureTypes\n from google.cloud.vision.image import Image\n client = mock.Mock(spec_set=['_credentials'])\n feature = Feature(FeatureTypes.LABEL_DETECTION, 5)\n image_content = b'abc 1 2 3'\n image = Image(client, content=image_content)\n with mock.patch('google.cloud.vision._gax.image_annotator_client.ImageAnnotatorClient'):\n gax_api = self._make_one(client)\n mock_response = {'batch_annotate_images.return_value': mock.Mock(responses=['mock response data'])}\n gax_api._annotator_client = mock.Mock(spec_set=['batch_annotate_images'], **mock_response)\n with mock.patch('google.cloud.vision._gax.Annotations') as mock_anno:\n images = ((image, [feature]),)\n gax_api.annotate(images)\n mock_anno.from_pb.assert_called_with('mock response data')\n gax_api._annotator_client.batch_annotate_images.assert_called()\n", "method_code": " def annotate(self, images=None, requests_pb=None):\n \"\"\"Annotate images through GAX.\n \n :type images: list\n :param images: List containing pairs of\n :class:`~google.cloud.vision.image.Image` and\n :class:`~google.cloud.vision.feature.Feature`.\n e.g. [(image, [feature_one, feature_two]),]\n \n :type requests_pb: list\n :param requests_pb: List of :class:`google.cloud.proto.vision.v1. image_annotator_pb2.AnnotateImageRequest`\n \n :rtype: list\n :returns: List of\n :class:`~google.cloud.vision.annotations.Annotations`.\n \"\"\"\n if any([images, requests_pb]) is False:\n return []\n if requests_pb is None:\n requests = []\n for image, features in images:\n gapic_features = [_to_gapic_feature(feature) for feature in features]\n gapic_image = _to_gapic_image(image)\n request = image_annotator_pb2.AnnotateImageRequest(image=gapic_image, features=gapic_features)\n requests.append(request)\n else:\n requests = requests_pb\n annotator_client = self._annotator_client\n responses = annotator_client.batch_annotate_images(requests).responses\n return [Annotations.from_pb(response) for response in responses]\n ", "context": "class _GAPICVisionAPI(object):\n def annotate(self, images=None, requests_pb=None): ...\n def __init__(self, client=None): ...\n\n self._client = client\n self._annotator_client = image_annotator_client.ImageAnnotatorClient(credentials=client._credentials, lib_name='gccl', lib_version=__version__)\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_annotation", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000416.py"} {"focal_file": "lib/pytz/__init__.py", "focal_class": null, "focal_method": "dst", "tests": "import unittest\n\nclass Test_dst(unittest.TestCase):\n def test_dst(self):\n import datetime\n tz = self._make_one()\n self.assertEqual(tz.dst(None), datetime.timedelta(0))\n", "method_code": " def dst(self, dt):\n return ZERO\n ", "context": "class UTC(datetime.tzinfo):\n def dst(self, dt): ...\n def fromutc(self, dt): ...\n def utcoffset(self, dt): ...\n def tzname(self, dt): ...\n def __reduce__(self): ...\n def localize(self, dt, is_dst=False): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n zone = 'UTC'\n _utcoffset = ZERO\n _dst = ZERO\n _tzname = zone\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_dst", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000417.py"} {"focal_file": "lib/pytz/__init__.py", "focal_class": null, "focal_method": "fromutc", "tests": "import unittest\n\nclass Test_fromutc(unittest.TestCase):\n def test_fromutc(self):\n import datetime\n naive_epoch = datetime.datetime.utcfromtimestamp(0)\n self.assertIsNone(naive_epoch.tzinfo)\n tz = self._make_one()\n epoch = tz.fromutc(naive_epoch)\n self.assertEqual(epoch.tzinfo, tz)\n", "method_code": " def fromutc(self, dt):\n if dt.tzinfo is None:\n return self.localize(dt)\n return super(utc.__class__, self).fromutc(dt)\n ", "context": "class UTC(datetime.tzinfo):\n def fromutc(self, dt): ...\n def utcoffset(self, dt): ...\n def tzname(self, dt): ...\n def dst(self, dt): ...\n def __reduce__(self): ...\n def localize(self, dt, is_dst=False): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n zone = 'UTC'\n _utcoffset = ZERO\n _dst = ZERO\n _tzname = zone\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_fromutc", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000418.py"} {"focal_file": "lib/pytz/__init__.py", "focal_class": null, "focal_method": "tzname", "tests": "import unittest\n\nclass Test_tzname(unittest.TestCase):\n def test_tzname(self):\n tz = self._make_one()\n self.assertEqual(tz.tzname(None), 'UTC')\n", "method_code": " def tzname(self, dt):\n return 'UTC'\n ", "context": "class UTC(datetime.tzinfo):\n def tzname(self, dt): ...\n def fromutc(self, dt): ...\n def utcoffset(self, dt): ...\n def dst(self, dt): ...\n def __reduce__(self): ...\n def localize(self, dt, is_dst=False): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n zone = 'UTC'\n _utcoffset = ZERO\n _dst = ZERO\n _tzname = zone\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_tzname", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000419.py"} {"focal_file": "lib/pytz/__init__.py", "focal_class": null, "focal_method": "utcoffset", "tests": "import unittest\n\nclass Test_utcoffset(unittest.TestCase):\n def test_utcoffset(self):\n import datetime\n tz = self._make_one()\n self.assertEqual(tz.utcoffset(None), datetime.timedelta(0))\n", "method_code": " def utcoffset(self, dt):\n return ZERO\n ", "context": "class UTC(datetime.tzinfo):\n def utcoffset(self, dt): ...\n def fromutc(self, dt): ...\n def tzname(self, dt): ...\n def dst(self, dt): ...\n def __reduce__(self): ...\n def localize(self, dt, is_dst=False): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n zone = 'UTC'\n _utcoffset = ZERO\n _dst = ZERO\n _tzname = zone\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_utcoffset", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000420.py"} {"focal_file": "lib/google/cloud/vision/annotations.py", "focal_class": null, "focal_method": "from_pb", "tests": "import unittest\n\nclass Test_from_pb(unittest.TestCase):\n def test_from_pb(self):\n from google.cloud.vision.likelihood import Likelihood\n from google.cloud.vision.safe_search import SafeSearchAnnotation\n from google.cloud.proto.vision.v1 import image_annotator_pb2\n image_response = image_annotator_pb2.AnnotateImageResponse()\n annotations = self._make_one().from_pb(image_response)\n self.assertEqual(annotations.labels, [])\n self.assertEqual(annotations.logos, [])\n self.assertEqual(annotations.faces, [])\n self.assertEqual(annotations.landmarks, [])\n self.assertEqual(annotations.texts, [])\n self.assertIsNone(annotations.properties)\n self.assertIsInstance(annotations.safe_searches, SafeSearchAnnotation)\n safe_search = annotations.safe_searches\n unknown = Likelihood.UNKNOWN\n self.assertIs(safe_search.adult, unknown)\n self.assertIs(safe_search.spoof, unknown)\n self.assertIs(safe_search.medical, unknown)\n self.assertIs(safe_search.violence, unknown)\n", "method_code": " def from_pb(cls, response):\n \"\"\"Factory: construct an instance of ``Annotations`` from protobuf.\n \n :type response: :class:`~google.cloud.proto.vision.v1. image_annotator_pb2.AnnotateImageResponse`\n :param response: ``AnnotateImageResponse`` from protobuf call.\n \n :rtype: :class:`~google.cloud.vision.annotations.Annotations`\n :returns: ``Annotations`` instance populated from gRPC response.\n \"\"\"\n annotations = _process_image_annotations(response)\n return cls(**annotations)\n ", "context": "class Annotations(object):\n @classmethod\n def from_pb(cls, response): ...\n def __init__(self, crop_hints=(), faces=(), full_texts=(), properties=(), labels=(), landmarks=(), logos=(), safe_searches=(), texts=(), web=()): ...\n def from_api_repr(cls, response): ...\n\n self.crop_hints = crop_hints\n self.faces = faces\n self.full_texts = full_texts\n self.properties = properties\n self.labels = labels\n self.landmarks = landmarks\n self.logos = logos\n self.safe_searches = safe_searches\n self.texts = texts\n self.web = web\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_from_pb", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000421.py"} {"focal_file": "lib/google/cloud/vision/color.py", "focal_class": null, "focal_method": "from_pb", "tests": "import unittest\n\nclass Test_from_pb(unittest.TestCase):\n def test_image_properties_annotation_from_pb(self):\n from google.cloud.proto.vision.v1 import image_annotator_pb2\n from google.protobuf.wrappers_pb2 import FloatValue\n from google.type.color_pb2 import Color\n alpha = FloatValue(value=1.0)\n color_pb = Color(red=1.0, green=2.0, blue=3.0, alpha=alpha)\n color_info_pb = image_annotator_pb2.ColorInfo(color=color_pb, score=1.0, pixel_fraction=1.0)\n dominant_colors = image_annotator_pb2.DominantColorsAnnotation(colors=[color_info_pb])\n image_properties_pb = image_annotator_pb2.ImageProperties(dominant_colors=dominant_colors)\n color_info = self._get_target_class()\n image_properties = color_info.from_pb(image_properties_pb)\n self.assertEqual(image_properties.colors[0].pixel_fraction, 1.0)\n self.assertEqual(image_properties.colors[0].score, 1.0)\n self.assertEqual(image_properties.colors[0].color.red, 1.0)\n self.assertEqual(image_properties.colors[0].color.green, 2.0)\n self.assertEqual(image_properties.colors[0].color.blue, 3.0)\n self.assertEqual(image_properties.colors[0].color.alpha, 1.0)\n\n def test_empty_image_properties_annotation_from_pb(self):\n from google.cloud.proto.vision.v1 import image_annotator_pb2\n image_properties_pb = image_annotator_pb2.ImageProperties()\n color_info = self._get_target_class()\n image_properties = color_info.from_pb(image_properties_pb)\n self.assertIsNone(image_properties)\n", "method_code": " def from_pb(cls, image_properties):\n \"\"\"Factory: construct ``ImagePropertiesAnnotation`` from a response.\n \n :type image_properties: :class:`~google.cloud.proto.vision.v1. image_annotator_pb2.ImageProperties`\n :param image_properties: Protobuf response from Vision API with image\n properties data.\n \n :rtype: list of\n :class:`~google.cloud.vision.color.ImagePropertiesAnnotation`\n :returns: List of ``ImagePropertiesAnnotation``.\n \"\"\"\n colors = getattr(image_properties.dominant_colors, 'colors', ())\n if len(colors) > 0:\n return cls([ColorInformation.from_pb(color) for color in colors])\n ", "context": "class ImagePropertiesAnnotation(object):\n @classmethod\n def from_pb(cls, image_properties): ...\n def __init__(self, colors): ...\n def from_api_repr(cls, image_properties): ...\n def colors(self): ...\n\n self._colors = colors\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_image_properties_annotation_from_pb", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000422.py"} {"focal_file": "lib/google/cloud/vision/crop_hint.py", "focal_class": null, "focal_method": "from_api_repr", "tests": "import unittest\n\nclass Test_from_api_repr(unittest.TestCase):\n def test_crop_hint_annotation(self):\n from tests.unit._fixtures import CROP_HINTS_RESPONSE\n from google.cloud.vision.geometry import Bounds\n response = CROP_HINTS_RESPONSE['responses'][0]['cropHintsAnnotation']\n crop_hints_dict = response['cropHints'][0]\n crop_hints_class = self._get_target_class()\n crop_hints = crop_hints_class.from_api_repr(crop_hints_dict)\n self.assertIsInstance(crop_hints.bounds, Bounds)\n self.assertEqual(len(crop_hints.bounds.vertices), 4)\n self.assertEqual(crop_hints.confidence, 0.5)\n self.assertEqual(crop_hints.importance_fraction, 1.22)\n", "method_code": " def from_api_repr(cls, response):\n \"\"\"Factory: construct ``CropHint`` from Vision API response.\n \n :type response: dict\n :param response: Dictionary response from Vision API with entity data.\n \n :rtype: :class:`~google.cloud.vision.crop_hint.CropHint`\n :returns: Instance of ``CropHint``.\n \"\"\"\n bounds = Bounds.from_api_repr(response.get('boundingPoly'))\n confidence = response.get('confidence', 0.0)\n importance_fraction = response.get('importanceFraction', 0.0)\n return cls(bounds, confidence, importance_fraction)\n ", "context": "class CropHint(object):\n @classmethod\n def from_api_repr(cls, response): ...\n def __init__(self, bounds, confidence, importance_fraction): ...\n def from_pb(cls, response): ...\n def bounds(self): ...\n def confidence(self): ...\n def importance_fraction(self): ...\n\n self._bounds = bounds\n self._confidence = confidence\n self._importance_fraction = importance_fraction\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_crop_hint_annotation", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000423.py"} {"focal_file": "lib/google/cloud/vision/crop_hint.py", "focal_class": null, "focal_method": "from_pb", "tests": "import unittest\n\nclass Test_from_pb(unittest.TestCase):\n def test_crop_hint_annotation_pb(self):\n from google.cloud.proto.vision.v1 import geometry_pb2\n from google.cloud.proto.vision.v1 import image_annotator_pb2\n vertex = geometry_pb2.Vertex(x=1, y=2)\n bounds = geometry_pb2.BoundingPoly(vertices=[vertex])\n crop_hint_pb = image_annotator_pb2.CropHint(bounding_poly=bounds, confidence=1.23, importance_fraction=4.56)\n crop_hints_class = self._get_target_class()\n crop_hint = crop_hints_class.from_pb(crop_hint_pb)\n self.assertEqual(len(crop_hint.bounds.vertices), 1)\n vertex = crop_hint.bounds.vertices[0]\n self.assertEqual(vertex.x_coordinate, 1)\n self.assertEqual(vertex.y_coordinate, 2)\n self.assertAlmostEqual(crop_hint.confidence, 1.23, 4)\n self.assertAlmostEqual(crop_hint.importance_fraction, 4.56, 4)\n", "method_code": " def from_pb(cls, response):\n \"\"\"Factory: construct ``CropHint`` from Vision gRPC response.\n \n :type response: :class:`google.cloud.proto.vision.v1. image_annotator_pb2.CropHint`\n :param response: gRPC response from Vision API with entity data.\n \n :rtype: :class:`~google.cloud.vision.crop_hint.CropHint`\n :returns: Instance of ``CropHint``.\n \"\"\"\n bounds = Bounds.from_pb(response.bounding_poly)\n return cls(bounds, response.confidence, response.importance_fraction)\n ", "context": "class CropHint(object):\n @classmethod\n def from_pb(cls, response): ...\n def __init__(self, bounds, confidence, importance_fraction): ...\n def from_api_repr(cls, response): ...\n def bounds(self): ...\n def confidence(self): ...\n def importance_fraction(self): ...\n\n self._bounds = bounds\n self._confidence = confidence\n self._importance_fraction = importance_fraction\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_crop_hint_annotation_pb", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000424.py"} {"focal_file": "lib/google/cloud/vision/feature.py", "focal_class": null, "focal_method": "as_dict", "tests": "import unittest\n\nclass Test_as_dict(unittest.TestCase):\n def test_feature_as_dict(self):\n from google.cloud.vision.feature import FeatureTypes\n feature = self._make_one(FeatureTypes.FACE_DETECTION, max_results=5)\n expected = {'type': 'FACE_DETECTION', 'maxResults': 5}\n self.assertEqual(feature.as_dict(), expected)\n", "method_code": " def as_dict(self):\n \"\"\"Generate dictionary for Feature request format.\n \n :rtype: dict\n :returns: Dictionary representation of a\n :class:`~google.cloud.vision.feature.FeatureType`.\n \"\"\"\n return {'type': self.feature_type, 'maxResults': self.max_results}\n ", "context": "class Feature(object):\n def as_dict(self): ...\n def __init__(self, feature_type, max_results=1): ...\n def feature_type(self): ...\n def max_results(self): ...\n\n self._max_results = int(max_results)\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_feature_as_dict", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000425.py"} {"focal_file": "lib/google/cloud/iterator.py", "focal_class": null, "focal_method": "_items_iter", "tests": "import unittest\n\nclass Test_items_iter(unittest.TestCase):\n def test__items_iter(self):\n import types\n import six\n from google.cloud.iterator import Page\n item1 = 17\n item2 = 100\n item3 = 211\n parent = object()\n page1 = Page(parent, (item1, item2), self._do_nothing)\n page2 = Page(parent, (item3,), self._do_nothing)\n iterator = self._make_one(None, None)\n incremented = []\n\n def page_iter(increment):\n incremented.append(increment)\n return iter((page1, page2))\n iterator._page_iter = page_iter\n items_iter = iterator._items_iter()\n self.assertIsInstance(items_iter, types.GeneratorType)\n self.assertEqual(iterator.num_results, 0)\n self.assertEqual(six.next(items_iter), (parent, item1))\n self.assertEqual(iterator.num_results, 1)\n self.assertEqual(six.next(items_iter), (parent, item2))\n self.assertEqual(iterator.num_results, 2)\n self.assertEqual(six.next(items_iter), (parent, item3))\n self.assertEqual(iterator.num_results, 3)\n with self.assertRaises(StopIteration):\n six.next(items_iter)\n self.assertEqual(incremented, [False])\n", "method_code": " def _items_iter(self):\n \"\"\"Iterator for each item returned.\"\"\"\n for page in self._page_iter(increment=False):\n for item in page:\n self.num_results += 1\n yield item\n ", "context": "class Iterator(object):\n def _items_iter(self): ...\n def __init__(self, client, item_to_value, page_token=None, max_results=None): ...\n def pages(self): ...\n def __iter__(self): ...\n def _page_iter(self, increment): ...\n def _next_page(): ...\n\n self._started = False\n self.client = client\n self._item_to_value = item_to_value\n self.max_results = max_results\n self.page_number = 0\n self.next_page_token = page_token\n self.num_results = 0\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__items_iter", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000426.py"} {"focal_file": "lib/google/cloud/iterator.py", "focal_class": null, "focal_method": "_next_page", "tests": "import unittest\n\nclass Test_next_page(unittest.TestCase):\n def test__next_page_virtual(self):\n iterator = self._make_one(None, None)\n with self.assertRaises(NotImplementedError):\n iterator._next_page()\n\n def test__next_page(self):\n from google.cloud._testing import _GAXPageIterator\n from google.cloud.iterator import Page\n page_items = (29, 31)\n page_token = '2sde98ds2s0hh'\n page_iter = _GAXPageIterator(page_items, page_token=page_token)\n iterator = self._make_one(None, page_iter, self._do_nothing)\n page = iterator._next_page()\n self.assertEqual(iterator.next_page_token, page_token)\n self.assertIsInstance(page, Page)\n expected = zip((iterator, iterator), page_items)\n self.assertEqual(list(page), list(expected))\n\n def test__next_page_empty(self):\n from google.cloud._testing import _GAXPageIterator\n page_iter = _GAXPageIterator()\n iterator = self._make_one(None, page_iter, self._do_nothing)\n page = iterator._next_page()\n self.assertIsNone(page)\n self.assertIsNone(iterator.next_page_token)\n", "method_code": " def _next_page():\n \"\"\"Get the next page in the iterator.\n \n This does nothing and is intended to be over-ridden by subclasses\n to return the next :class:`Page`.\n \n :raises NotImplementedError: Always.\n \"\"\"\n raise NotImplementedError\n ", "context": "class Iterator(object):\n @staticmethod\n def _next_page(): ...\n def __init__(self, client, item_to_value, page_token=None, max_results=None): ...\n def pages(self): ...\n def _items_iter(self): ...\n def __iter__(self): ...\n def _page_iter(self, increment): ...\n\n self._started = False\n self.client = client\n self._item_to_value = item_to_value\n self.max_results = max_results\n self.page_number = 0\n self.next_page_token = page_token\n self.num_results = 0\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__next_page_virtual", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000427.py"} {"focal_file": "lib/google/cloud/iterator.py", "focal_class": null, "focal_method": "_has_next_page", "tests": "import unittest\n\nclass Test_has_next_page(unittest.TestCase):\n def test__has_next_page_new(self):\n connection = _Connection()\n client = _Client(connection)\n path = '/foo'\n iterator = self._make_one(client, path, None)\n self.assertTrue(iterator._has_next_page())\n\n def test__has_next_page_w_number_no_token(self):\n connection = _Connection()\n client = _Client(connection)\n path = '/foo'\n iterator = self._make_one(client, path, None)\n iterator.page_number = 1\n self.assertFalse(iterator._has_next_page())\n\n def test__has_next_page_w_number_w_token(self):\n connection = _Connection()\n client = _Client(connection)\n path = '/foo'\n token = 'token'\n iterator = self._make_one(client, path, None)\n iterator.page_number = 1\n iterator.next_page_token = token\n self.assertTrue(iterator._has_next_page())\n\n def test__has_next_page_w_max_results_not_done(self):\n iterator = self._make_one(None, None, None, max_results=3, page_token='definitely-not-none')\n iterator.page_number = 1\n self.assertLess(iterator.num_results, iterator.max_results)\n self.assertTrue(iterator._has_next_page())\n\n def test__has_next_page_w_max_results_done(self):\n iterator = self._make_one(None, None, None, max_results=3)\n iterator.page_number = 1\n iterator.num_results = iterator.max_results\n self.assertFalse(iterator._has_next_page())\n", "method_code": " def _has_next_page(self):\n \"\"\"Determines whether or not there are more pages with results.\n \n :rtype: bool\n :returns: Whether the iterator has more pages.\n \"\"\"\n if self.page_number == 0:\n return True\n if self.max_results is not None:\n if self.num_results >= self.max_results:\n return False\n return self.next_page_token is not None\n ", "context": "class HTTPIterator(Iterator):\n def _has_next_page(self): ...\n def __init__(self, client, path, item_to_value, items_key=DEFAULT_ITEMS_KEY, page_token=None, max_results=None, extra_params=None, page_start=_do_nothing_page_start): ...\n def _verify_params(self): ...\n def _next_page(self): ...\n def _get_query_params(self): ...\n def _get_next_page_response(self): ...\n\n self.path = path\n self._items_key = items_key\n self.extra_params = extra_params\n self._page_start = page_start\n\n _PAGE_TOKEN = 'pageToken'\n _MAX_RESULTS = 'maxResults'\n _NEXT_TOKEN = 'nextPageToken'\n _RESERVED_PARAMS = frozenset([_PAGE_TOKEN, _MAX_RESULTS])\n _HTTP_METHOD = 'GET'\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__has_next_page_new", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000428.py"} {"focal_file": "lib/google/cloud/iterator.py", "focal_class": null, "focal_method": "_get_query_params", "tests": "import unittest\n\nclass Test_get_query_params(unittest.TestCase):\n def test__get_query_params_no_token(self):\n connection = _Connection()\n client = _Client(connection)\n path = '/foo'\n iterator = self._make_one(client, path, None)\n self.assertEqual(iterator._get_query_params(), {})\n\n def test__get_query_params_w_token(self):\n connection = _Connection()\n client = _Client(connection)\n path = '/foo'\n token = 'token'\n iterator = self._make_one(client, path, None)\n iterator.next_page_token = token\n self.assertEqual(iterator._get_query_params(), {'pageToken': token})\n\n def test__get_query_params_w_max_results(self):\n connection = _Connection()\n client = _Client(connection)\n path = '/foo'\n max_results = 3\n iterator = self._make_one(client, path, None, max_results=max_results)\n iterator.num_results = 1\n local_max = max_results - iterator.num_results\n self.assertEqual(iterator._get_query_params(), {'maxResults': local_max})\n\n def test__get_query_params_extra_params(self):\n connection = _Connection()\n client = _Client(connection)\n path = '/foo'\n extra_params = {'key': 'val'}\n iterator = self._make_one(client, path, None, extra_params=extra_params)\n self.assertEqual(iterator._get_query_params(), extra_params)\n\n def test__get_query_params_w_token_and_extra_params(self):\n connection = _Connection()\n client = _Client(connection)\n path = '/foo'\n token = 'token'\n extra_params = {'key': 'val'}\n iterator = self._make_one(client, path, None, extra_params=extra_params)\n iterator.next_page_token = token\n expected_query = extra_params.copy()\n expected_query.update({'pageToken': token})\n self.assertEqual(iterator._get_query_params(), expected_query)\n", "method_code": " def _get_query_params(self):\n \"\"\"Getter for query parameters for the next request.\n \n :rtype: dict\n :returns: A dictionary of query parameters.\n \"\"\"\n result = {}\n if self.next_page_token is not None:\n result[self._PAGE_TOKEN] = self.next_page_token\n if self.max_results is not None:\n result[self._MAX_RESULTS] = self.max_results - self.num_results\n result.update(self.extra_params)\n return result\n ", "context": "class HTTPIterator(Iterator):\n def _get_query_params(self): ...\n def __init__(self, client, path, item_to_value, items_key=DEFAULT_ITEMS_KEY, page_token=None, max_results=None, extra_params=None, page_start=_do_nothing_page_start): ...\n def _verify_params(self): ...\n def _next_page(self): ...\n def _has_next_page(self): ...\n def _get_next_page_response(self): ...\n\n self.path = path\n self._items_key = items_key\n self.extra_params = extra_params\n self._page_start = page_start\n\n _PAGE_TOKEN = 'pageToken'\n _MAX_RESULTS = 'maxResults'\n _NEXT_TOKEN = 'nextPageToken'\n _RESERVED_PARAMS = frozenset([_PAGE_TOKEN, _MAX_RESULTS])\n _HTTP_METHOD = 'GET'\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__get_query_params_no_token", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000429.py"} {"focal_file": "lib/google/cloud/iterator.py", "focal_class": null, "focal_method": "_get_next_page_response", "tests": "import unittest\n\nclass Test_get_next_page_response(unittest.TestCase):\n def test__get_next_page_response_new_no_token_in_response(self):\n path = '/foo'\n token = 'token'\n key1 = 'key1'\n key2 = 'key2'\n connection = _Connection({'items': [{'name': key1}, {'name': key2}], 'nextPageToken': token})\n client = _Client(connection)\n iterator = self._make_one(client, path, None)\n response = iterator._get_next_page_response()\n self.assertEqual(response['items'], [{'name': key1}, {'name': key2}])\n kw, = connection._requested\n self.assertEqual(kw['method'], 'GET')\n self.assertEqual(kw['path'], path)\n self.assertEqual(kw['query_params'], {})\n\n def test__get_next_page_response_with_post(self):\n path = '/foo'\n returned = {'green': 'eggs', 'ham': 55}\n connection = _Connection(returned)\n client = _Client(connection)\n iterator = self._make_one(client, path, None)\n iterator._HTTP_METHOD = 'POST'\n response = iterator._get_next_page_response()\n self.assertEqual(response, returned)\n self.assertEqual(len(connection._requested), 1)\n called_kwargs = connection._requested[0]\n self.assertEqual(called_kwargs, {'method': iterator._HTTP_METHOD, 'path': path, 'data': {}})\n\n def test__get_next_page_bad_http_method(self):\n path = '/foo'\n client = _Client(None)\n iterator = self._make_one(client, path, None)\n iterator._HTTP_METHOD = 'NOT-A-VERB'\n with self.assertRaises(ValueError):\n iterator._get_next_page_response()\n", "method_code": " def _get_next_page_response(self):\n \"\"\"Requests the next page from the path provided.\n \n :rtype: dict\n :returns: The parsed JSON response of the next page's contents.\n \"\"\"\n params = self._get_query_params()\n if self._HTTP_METHOD == 'GET':\n return self.client._connection.api_request(method=self._HTTP_METHOD, path=self.path, query_params=params)\n elif self._HTTP_METHOD == 'POST':\n return self.client._connection.api_request(method=self._HTTP_METHOD, path=self.path, data=params)\n else:\n raise ValueError('Unexpected HTTP method', self._HTTP_METHOD)\n ", "context": "class HTTPIterator(Iterator):\n def _get_next_page_response(self): ...\n def __init__(self, client, path, item_to_value, items_key=DEFAULT_ITEMS_KEY, page_token=None, max_results=None, extra_params=None, page_start=_do_nothing_page_start): ...\n def _verify_params(self): ...\n def _next_page(self): ...\n def _has_next_page(self): ...\n def _get_query_params(self): ...\n\n self.path = path\n self._items_key = items_key\n self.extra_params = extra_params\n self._page_start = page_start\n\n _PAGE_TOKEN = 'pageToken'\n _MAX_RESULTS = 'maxResults'\n _NEXT_TOKEN = 'nextPageToken'\n _RESERVED_PARAMS = frozenset([_PAGE_TOKEN, _MAX_RESULTS])\n _HTTP_METHOD = 'GET'\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__get_next_page_response_new_no_token_in_response", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000430.py"} {"focal_file": "lib/google/cloud/operation.py", "focal_class": null, "focal_method": "from_dict", "tests": "import unittest\n\nclass Test_from_dict(unittest.TestCase):\n def test_from_dict(self):\n from google.protobuf.struct_pb2 import Struct\n from google.cloud._testing import _Monkey\n from google.cloud import operation as MUT\n type_url = 'type.googleapis.com/%s' % (Struct.DESCRIPTOR.full_name,)\n api_response = {'name': self.OPERATION_NAME, 'metadata': {'@type': type_url, 'value': {'foo': 'Bar'}}}\n client = _Client()\n klass = self._get_target_class()\n with _Monkey(MUT, _TYPE_URL_MAP={type_url: Struct}):\n operation = klass.from_dict(api_response, client)\n self.assertEqual(operation.name, self.OPERATION_NAME)\n self.assertIs(operation.client, client)\n self.assertIsNone(operation.target)\n self.assertIsNone(operation.response)\n self.assertIsNone(operation.error)\n self.assertIsInstance(operation.metadata, Struct)\n self.assertEqual(len(operation.metadata.fields), 1)\n self.assertEqual(operation.metadata.fields['foo'].string_value, 'Bar')\n self.assertEqual(operation.caller_metadata, {})\n self.assertFalse(operation._from_grpc)\n", "method_code": " def from_dict(cls, operation, client, **caller_metadata):\n \"\"\"Factory: construct an instance from a dictionary.\n \n :type operation: dict\n :param operation: Operation as a JSON object.\n \n :type client: :class:`~google.cloud.client.Client`\n :param client: The client used to poll for the status of the operation.\n \n :type caller_metadata: dict\n :param caller_metadata: caller-assigned metadata about the operation\n \n :rtype: :class:`Operation`\n :returns: new instance, with attributes based on the protobuf.\n \"\"\"\n operation_pb = json_format.ParseDict(operation, operations_pb2.Operation())\n result = cls(operation_pb.name, client, **caller_metadata)\n result._update_state(operation_pb)\n result._from_grpc = False\n return result\n ", "context": "class Operation(object):\n @classmethod\n def from_dict(cls, operation, client, **caller_metadata): ...\n def __init__(self, name, client, **caller_metadata): ...\n def from_pb(cls, operation_pb, client, **caller_metadata): ...\n def complete(self): ...\n def _get_operation_rpc(self): ...\n def _get_operation_http(self): ...\n def _get_operation(self): ...\n def _update_state(self, operation_pb): ...\n def poll(self): ...\n\n self.name = name\n self.client = client\n self.caller_metadata = caller_metadata.copy()\n self._complete = False\n\n target = None\n response = None\n error = None\n metadata = None\n _from_grpc = True\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_from_dict", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000431.py"} {"focal_file": "lib/google/cloud/operation.py", "focal_class": null, "focal_method": "_update_state", "tests": "import unittest\n\nclass Test_update_state(unittest.TestCase):\n def test__update_state_done(self):\n from google.longrunning import operations_pb2\n operation = self._make_one(None, None)\n self.assertFalse(operation.complete)\n operation_pb = operations_pb2.Operation(done=True)\n operation._update_state(operation_pb)\n self.assertTrue(operation.complete)\n\n def test__update_state_metadata(self):\n from google.longrunning import operations_pb2\n from google.protobuf.any_pb2 import Any\n from google.protobuf.struct_pb2 import Value\n from google.cloud._testing import _Monkey\n from google.cloud import operation as MUT\n operation = self._make_one(None, None)\n self.assertIsNone(operation.metadata)\n val_pb = Value(number_value=1337)\n type_url = 'type.googleapis.com/%s' % (Value.DESCRIPTOR.full_name,)\n val_any = Any(type_url=type_url, value=val_pb.SerializeToString())\n operation_pb = operations_pb2.Operation(metadata=val_any)\n with _Monkey(MUT, _TYPE_URL_MAP={type_url: Value}):\n operation._update_state(operation_pb)\n self.assertEqual(operation.metadata, val_pb)\n\n def test__update_state_error(self):\n from google.longrunning import operations_pb2\n from google.rpc.status_pb2 import Status\n operation = self._make_one(None, None)\n self.assertIsNone(operation.error)\n self.assertIsNone(operation.response)\n error_pb = Status(code=1)\n operation_pb = operations_pb2.Operation(error=error_pb)\n operation._update_state(operation_pb)\n self.assertEqual(operation.error, error_pb)\n self.assertIsNone(operation.response)\n\n def test__update_state_response(self):\n from google.longrunning import operations_pb2\n from google.protobuf.any_pb2 import Any\n from google.protobuf.struct_pb2 import Value\n from google.cloud._testing import _Monkey\n from google.cloud import operation as MUT\n operation = self._make_one(None, None)\n self.assertIsNone(operation.error)\n self.assertIsNone(operation.response)\n response_pb = Value(string_value='totes a response')\n type_url = 'type.googleapis.com/%s' % (Value.DESCRIPTOR.full_name,)\n response_any = Any(type_url=type_url, value=response_pb.SerializeToString())\n operation_pb = operations_pb2.Operation(response=response_any)\n with _Monkey(MUT, _TYPE_URL_MAP={type_url: Value}):\n operation._update_state(operation_pb)\n self.assertIsNone(operation.error)\n self.assertEqual(operation.response, response_pb)\n\n def test__update_state_no_result(self):\n from google.longrunning import operations_pb2\n operation = self._make_one(None, None)\n self.assertIsNone(operation.error)\n self.assertIsNone(operation.response)\n operation_pb = operations_pb2.Operation()\n operation._update_state(operation_pb)\n self.assertIsNone(operation.error)\n self.assertIsNone(operation.response)\n", "method_code": " def _update_state(self, operation_pb):\n \"\"\"Update the state of the current object based on operation.\n \n :type operation_pb:\n :class:`~google.longrunning.operations_pb2.Operation`\n :param operation_pb: Protobuf to be parsed.\n \"\"\"\n if operation_pb.done:\n self._complete = True\n if operation_pb.HasField('metadata'):\n self.metadata = _from_any(operation_pb.metadata)\n result_type = operation_pb.WhichOneof('result')\n if result_type == 'error':\n self.error = operation_pb.error\n elif result_type == 'response':\n self.response = _from_any(operation_pb.response)\n ", "context": "class Operation(object):\n def _update_state(self, operation_pb): ...\n def __init__(self, name, client, **caller_metadata): ...\n def from_pb(cls, operation_pb, client, **caller_metadata): ...\n def from_dict(cls, operation, client, **caller_metadata): ...\n def complete(self): ...\n def _get_operation_rpc(self): ...\n def _get_operation_http(self): ...\n def _get_operation(self): ...\n def poll(self): ...\n\n self.name = name\n self.client = client\n self.caller_metadata = caller_metadata.copy()\n self._complete = False\n\n target = None\n response = None\n error = None\n metadata = None\n _from_grpc = True\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__update_state_done", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000432.py"} {"focal_file": "lib/google/cloud/vision/web.py", "focal_class": null, "focal_method": "from_api_repr", "tests": "import unittest\n\nclass Test_from_api_repr(unittest.TestCase):\n def test_web_detection_from_api_repr(self):\n from google.cloud.vision.web import WebEntity\n from google.cloud.vision.web import WebImage\n from google.cloud.vision.web import WebPage\n web_detection_dict = {'partialMatchingImages': [{'url': 'https://cloud.google.com/vision', 'score': 0.92234}], 'fullMatchingImages': [{'url': 'https://cloud.google.com/vision', 'score': 0.92234}], 'webEntities': [{'entityId': '/m/05_5t0l', 'score': 0.9468027, 'description': 'Landmark'}], 'pagesWithMatchingImages': [{'url': 'https://cloud.google.com/vision', 'score': 0.92234}]}\n web_detection = self._get_target_class().from_api_repr(web_detection_dict)\n self.assertEqual(len(web_detection.partial_matching_images), 1)\n self.assertEqual(len(web_detection.full_matching_images), 1)\n self.assertEqual(len(web_detection.web_entities), 1)\n self.assertEqual(len(web_detection.pages_with_matching_images), 1)\n self.assertIsInstance(web_detection.partial_matching_images[0], WebImage)\n self.assertIsInstance(web_detection.full_matching_images[0], WebImage)\n self.assertIsInstance(web_detection.web_entities[0], WebEntity)\n self.assertIsInstance(web_detection.pages_with_matching_images[0], WebPage)\n\n def test_web_entity_from_api_repr(self):\n entity_dict = {'entityId': '/m/019dvv', 'score': 1470.4435, 'description': 'Mount Rushmore National Memorial'}\n web_entity = self._get_target_class().from_api_repr(entity_dict)\n self.assertEqual(web_entity.entity_id, entity_dict['entityId'])\n self.assertAlmostEqual(web_entity.score, entity_dict['score'], 4)\n self.assertEqual(web_entity.description, entity_dict['description'])\n\n def test_web_image_from_api_repr(self):\n web_image_dict = {'url': 'http://cloud.google.com/vision', 'score': 1234.23}\n web_image = self._get_target_class().from_api_repr(web_image_dict)\n self.assertEqual(web_image.url, web_image_dict['url'])\n self.assertAlmostEqual(web_image.score, web_image_dict['score'])\n\n def test_web_page_from_api_repr(self):\n web_page_dict = {'url': 'http://cloud.google.com/vision', 'score': 1234.23}\n web_page = self._get_target_class().from_api_repr(web_page_dict)\n self.assertEqual(web_page.url, web_page_dict['url'])\n self.assertAlmostEqual(web_page.score, web_page_dict['score'], 4)\n", "method_code": " def from_api_repr(cls, detection):\n \"\"\"Factory: construct ``WebDetection`` from Vision API response.\n \n :type detection: dict\n :param detection: Dictionary representing a ``WebDetection``.\n \n :rtype: :class:`~google.cloud.vision.web.WebDetection`\n :returns: Populated instance of ``WebDetection``.\n \"\"\"\n web_entities = detection.get('webEntities')\n full_matching_images = detection.get('fullMatchingImages')\n partial_matching_images = detection.get('partialMatchingImages')\n pages_with_matching_images = detection.get('pagesWithMatchingImages')\n web_detection = {'web_entities': [WebEntity.from_api_repr(web_entity) for web_entity in web_entities], 'full_matching_images': [WebImage.from_api_repr(web_image) for web_image in full_matching_images], 'partial_matching_images': [WebImage.from_api_repr(web_image) for web_image in partial_matching_images], 'pages_with_matching_images': [WebPage.from_api_repr(web_page) for web_page in pages_with_matching_images]}\n return cls(**web_detection)\n ", "context": "class WebDetection(object):\n @classmethod\n def from_api_repr(cls, detection): ...\n def __init__(self, web_entities=(), full_matching_images=(), partial_matching_images=(), pages_with_matching_images=()): ...\n def from_pb(cls, detection): ...\n def web_entities(self): ...\n def full_matching_images(self): ...\n def partial_matching_images(self): ...\n def pages_with_matching_images(self): ...\n\n self._web_entities = web_entities\n self._full_matching_images = full_matching_images\n self._partial_matching_images = partial_matching_images\n self._pages_with_matching_images = pages_with_matching_images\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_web_detection_from_api_repr", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000433.py"} {"focal_file": "lib/google/cloud/vision/web.py", "focal_class": null, "focal_method": "from_pb", "tests": "import unittest\n\nclass Test_from_pb(unittest.TestCase):\n def test_web_detection_from_pb(self):\n from google.cloud.proto.vision.v1 import web_detection_pb2\n from google.cloud.vision.web import WebEntity\n from google.cloud.vision.web import WebImage\n from google.cloud.vision.web import WebPage\n description = 'Some images like the image you have.'\n entity_id = '/m/019dvv'\n score = 1470.4435\n url = 'http://cloud.google.com/vision'\n web_entity_pb = web_detection_pb2.WebDetection.WebEntity(entity_id=entity_id, score=score, description=description)\n web_image_pb = web_detection_pb2.WebDetection.WebImage(url=url, score=score)\n web_page_pb = web_detection_pb2.WebDetection.WebPage(url=url, score=score)\n web_detection_pb = web_detection_pb2.WebDetection(web_entities=[web_entity_pb], full_matching_images=[web_image_pb], partial_matching_images=[web_image_pb], pages_with_matching_images=[web_page_pb])\n web_detection = self._get_target_class().from_pb(web_detection_pb)\n self.assertEqual(len(web_detection.web_entities), 1)\n self.assertEqual(len(web_detection.full_matching_images), 1)\n self.assertEqual(len(web_detection.partial_matching_images), 1)\n self.assertEqual(len(web_detection.pages_with_matching_images), 1)\n self.assertIsInstance(web_detection.web_entities[0], WebEntity)\n self.assertIsInstance(web_detection.full_matching_images[0], WebImage)\n self.assertIsInstance(web_detection.partial_matching_images[0], WebImage)\n self.assertIsInstance(web_detection.pages_with_matching_images[0], WebPage)\n\n def test_web_entity_from_pb(self):\n from google.cloud.proto.vision.v1 import web_detection_pb2\n entity_id = '/m/019dvv'\n score = 1470.4435\n description = 'Some images like the image you have.'\n web_entity_pb = web_detection_pb2.WebDetection.WebEntity(entity_id=entity_id, score=score, description=description)\n web_entity = self._get_target_class().from_pb(web_entity_pb)\n self.assertEqual(web_entity.entity_id, entity_id)\n self.assertAlmostEqual(web_entity.score, score, 4)\n self.assertEqual(web_entity.description, description)\n\n def test_web_image_from_pb(self):\n from google.cloud.proto.vision.v1 import web_detection_pb2\n url = 'http://cloud.google.com/vision'\n score = 1234.23\n web_image_pb = web_detection_pb2.WebDetection.WebImage(url=url, score=score)\n web_image = self._get_target_class().from_pb(web_image_pb)\n self.assertEqual(web_image.url, url)\n self.assertAlmostEqual(web_image.score, score, 4)\n\n def test_web_page_from_pb(self):\n from google.cloud.proto.vision.v1 import web_detection_pb2\n url = 'http://cloud.google.com/vision'\n score = 1234.23\n web_page_pb = web_detection_pb2.WebDetection.WebPage(url=url, score=score)\n web_page = self._get_target_class().from_pb(web_page_pb)\n self.assertEqual(web_page.url, url)\n self.assertAlmostEqual(web_page.score, score, 4)\n", "method_code": " def from_pb(cls, detection):\n \"\"\"Factory: construct ``WebDetection`` from Vision API response.\n \n :type detection: :class:`~google.cloud.proto.vision.v1. web_detection_pb2.WebDetection`\n :param detection: Dictionary representing a ``WebDetection``.\n \n :rtype: :class:`~google.cloud.vision.web.WebDetection`\n :returns: Populated instance of ``WebDetection``.\n \"\"\"\n web_entities = [WebEntity.from_pb(web_entity) for web_entity in detection.web_entities]\n full_image_matches = [WebImage.from_pb(web_image) for web_image in detection.full_matching_images]\n partial_image_matches = [WebImage.from_pb(web_image) for web_image in detection.partial_matching_images]\n pages_with_images = [WebPage.from_pb(web_page) for web_page in detection.pages_with_matching_images]\n return cls(web_entities, full_image_matches, partial_image_matches, pages_with_images)\n ", "context": "class WebDetection(object):\n @classmethod\n def from_pb(cls, detection): ...\n def __init__(self, web_entities=(), full_matching_images=(), partial_matching_images=(), pages_with_matching_images=()): ...\n def from_api_repr(cls, detection): ...\n def web_entities(self): ...\n def full_matching_images(self): ...\n def partial_matching_images(self): ...\n def pages_with_matching_images(self): ...\n\n self._web_entities = web_entities\n self._full_matching_images = full_matching_images\n self._partial_matching_images = partial_matching_images\n self._pages_with_matching_images = pages_with_matching_images\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_web_detection_from_pb", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000434.py"} {"focal_file": "lib/google/cloud/streaming/buffered_stream.py", "focal_class": null, "focal_method": "read", "tests": "import unittest\n\nclass Test_read(unittest.TestCase):\n def test_read_exhausted(self):\n from io import BytesIO\n CONTENT = b'CONTENT GOES HERE'\n START = len(CONTENT)\n BUFSIZE = 10\n stream = BytesIO(CONTENT)\n stream.read(START)\n bufstream = self._make_one(stream, START, BUFSIZE)\n self.assertTrue(bufstream.stream_exhausted)\n self.assertEqual(bufstream.stream_end_position, len(CONTENT))\n self.assertEqual(bufstream._bytes_remaining, 0)\n self.assertEqual(bufstream.read(10), b'')\n", "method_code": " def read(self, size=None):\n \"\"\"Read bytes from the buffer.\n \n :type size: int\n :param size:\n (Optional) How many bytes to read (defaults to all remaining\n bytes).\n \n :rtype: str\n :returns: The data read from the stream.\n \"\"\"\n if size is None or size < 0:\n raise ValueError('Illegal read of size %s requested on BufferedStream. Wrapped stream %s is at position %s-%s, %s bytes remaining.' % (size, self._stream, self._start_pos, self._end_pos, self._bytes_remaining))\n if not self._bytes_remaining:\n return b''\n size = min(size, self._bytes_remaining)\n data = self._buffered_data[self._buffer_pos:self._buffer_pos + size]\n self._buffer_pos += size\n return data\n ", "context": "class BufferedStream(object):\n def read(self, size=None): ...\n def __init__(self, stream, start, size): ...\n def __repr__(self): ...\n def __len__(self): ...\n def stream_exhausted(self): ...\n def stream_end_position(self): ...\n def _bytes_remaining(self): ...\n\n self._stream = stream\n self._start_pos = start\n self._buffer_pos = 0\n self._stream_at_end = len(self._buffered_data) < size\n self._end_pos = self._start_pos + len(self._buffered_data)\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_read_exhausted", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000435.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_ensure_initialized", "tests": "import unittest\n\nclass Test_ensure_initialized(unittest.TestCase):\n def test__ensure_initialized_hit(self):\n HTTP = object()\n stream = _Stream()\n xfer = self._make_one(stream)\n xfer._initialize(HTTP, self.URL)\n xfer._ensure_initialized()\n\n def test__ensure_initialized_miss(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n stream = _Stream()\n xfer = self._make_one(stream)\n with self.assertRaises(TransferInvalidError):\n xfer._ensure_initialized()\n", "method_code": " def _ensure_initialized(self):\n \"\"\"Helper: assert that the instance is initialized.\n \n :raises: :exc:`google.cloud.streaming.exceptions.TransferInvalidError`\n if the instance is not initialized.\n \"\"\"\n if not self.initialized:\n raise TransferInvalidError('Cannot use uninitialized %s', type(self).__name__)\n ", "context": "class _Transfer(object):\n def _ensure_initialized(self): ...\n def __init__(self, stream, close_stream=False, chunksize=_DEFAULT_CHUNKSIZE, auto_transfer=True, http=None, num_retries=5): ...\n def __repr__(self): ...\n def close_stream(self): ...\n def http(self): ...\n def bytes_http(self): ...\n def bytes_http(self, value): ...\n def num_retries(self): ...\n def num_retries(self, value): ...\n def stream(self): ...\n def url(self): ...\n def _initialize(self, http, url): ...\n def initialized(self): ...\n def _ensure_uninitialized(self): ...\n def __del__(self): ...\n\n self._bytes_http = None\n self._close_stream = close_stream\n self._http = http\n self._stream = stream\n self._url = None\n self.num_retries = num_retries\n self.auto_transfer = auto_transfer\n self.chunksize = chunksize\n\n _num_retries = None\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__ensure_initialized_hit", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000436.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_ensure_uninitialized", "tests": "import unittest\n\nclass Test_ensure_uninitialized(unittest.TestCase):\n def test__ensure_uninitialized_hit(self):\n stream = _Stream()\n xfer = self._make_one(stream)\n xfer._ensure_uninitialized()\n\n def test__ensure_uninitialized_miss(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n stream = _Stream()\n HTTP = object()\n xfer = self._make_one(stream)\n xfer._initialize(HTTP, self.URL)\n with self.assertRaises(TransferInvalidError):\n xfer._ensure_uninitialized()\n", "method_code": " def _ensure_uninitialized(self):\n \"\"\"Helper: assert that the instance is not initialized.\n \n :raises: :exc:`google.cloud.streaming.exceptions.TransferInvalidError`\n if the instance is already initialized.\n \"\"\"\n if self.initialized:\n raise TransferInvalidError('Cannot re-initialize %s', type(self).__name__)\n ", "context": "class _Transfer(object):\n def _ensure_uninitialized(self): ...\n def __init__(self, stream, close_stream=False, chunksize=_DEFAULT_CHUNKSIZE, auto_transfer=True, http=None, num_retries=5): ...\n def __repr__(self): ...\n def close_stream(self): ...\n def http(self): ...\n def bytes_http(self): ...\n def bytes_http(self, value): ...\n def num_retries(self): ...\n def num_retries(self, value): ...\n def stream(self): ...\n def url(self): ...\n def _initialize(self, http, url): ...\n def initialized(self): ...\n def _ensure_initialized(self): ...\n def __del__(self): ...\n\n self._bytes_http = None\n self._close_stream = close_stream\n self._http = http\n self._stream = stream\n self._url = None\n self.num_retries = num_retries\n self.auto_transfer = auto_transfer\n self.chunksize = chunksize\n\n _num_retries = None\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__ensure_uninitialized_hit", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000437.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "from_stream", "tests": "import unittest\n\nclass Test_from_stream(unittest.TestCase):\n def test_from_stream_defaults(self):\n klass = self._get_target_class()\n stream = _Stream()\n upload = klass.from_stream(stream, mime_type=self.MIME_TYPE)\n self.assertEqual(upload.mime_type, self.MIME_TYPE)\n self.assertTrue(upload.auto_transfer)\n self.assertIsNone(upload.total_size)\n\n def test_from_stream_explicit(self):\n klass = self._get_target_class()\n stream = _Stream()\n SIZE = 10\n CHUNK_SIZE = 3\n upload = klass.from_stream(stream, mime_type=self.MIME_TYPE, auto_transfer=False, total_size=SIZE, chunksize=CHUNK_SIZE)\n self.assertEqual(upload.mime_type, self.MIME_TYPE)\n self.assertFalse(upload.auto_transfer)\n self.assertEqual(upload.total_size, SIZE)\n self.assertEqual(upload.chunksize, CHUNK_SIZE)\n\n def test_from_stream_wo_mimetype(self):\n klass = self._get_target_class()\n stream = _Stream()\n with self.assertRaises(ValueError):\n klass.from_stream(stream, mime_type=None)\n", "method_code": " def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds):\n \"\"\"Create a new Download object from a stream.\n \n :type stream: writable file-like object\n :param stream: the target file\n \n :type total_size: int\n :param total_size: (Optional) total size of the file to be downloaded\n \n :type auto_transfer: bool\n :param auto_transfer: should the transfer be started immediately\n \n :type kwds: dict\n :param kwds: keyword arguments: passed\n through to :meth:`_Transfer.__init__()`.\n \n :rtype: :class:`Download`\n :returns: The download initiated from the stream passed.\n \"\"\"\n return cls(stream, auto_transfer=auto_transfer, total_size=total_size, **kwds)\n ", "context": "class Download(_Transfer):\n @classmethod\n def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds): ...\n def __init__(self, stream, **kwds): ...\n def from_file(cls, filename, overwrite=False, auto_transfer=True, **kwds): ...\n def progress(self): ...\n def total_size(self): ...\n def encoding(self): ...\n def __repr__(self): ...\n def configure_request(self, http_request, url_builder): ...\n def _set_total(self, info): ...\n def initialize_download(self, http_request, http): ...\n def _normalize_start_end(self, start, end=None): ...\n def _set_range_header(request, start, end=None): ...\n def _compute_end_byte(self, start, end=None, use_chunks=True): ...\n def _get_chunk(self, start, end, headers=None): ...\n def _process_response(self, response): ...\n def get_range(self, start, end=None, use_chunks=True): ...\n def stream_file(self, use_chunks=True, headers=None): ...\n\n self._initial_response = None\n self._progress = 0\n self._total_size = total_size\n self._encoding = None\n\n _ACCEPTABLE_STATUSES = set((http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_from_stream_defaults", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000438.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "configure_request", "tests": "import unittest\n\nclass Test_configure_request(unittest.TestCase):\n def test_configure_request(self):\n CHUNK_SIZE = 100\n download = self._make_one(_Stream(), chunksize=CHUNK_SIZE)\n request = _Dummy(headers={})\n url_builder = _Dummy(query_params={})\n download.configure_request(request, url_builder)\n self.assertEqual(request.headers, {'Range': 'bytes=0-99'})\n self.assertEqual(url_builder.query_params, {'alt': 'media'})\n\n def test_configure_request_w_invalid_mimetype(self):\n config = _UploadConfig()\n config.accept = ('text/*',)\n request = _Request()\n url_builder = _Dummy()\n upload = self._make_one(_Stream())\n with self.assertRaises(ValueError):\n upload.configure_request(config, request, url_builder)\n\n def test_configure_request_w_simple_wo_body(self):\n from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n CONTENT = b'CONTENT'\n config = _UploadConfig()\n request = _Request()\n url_builder = _Dummy(query_params={})\n upload = self._make_one(_Stream(CONTENT))\n upload.strategy = SIMPLE_UPLOAD\n upload.configure_request(config, request, url_builder)\n self.assertEqual(url_builder.query_params, {'uploadType': 'media'})\n self.assertEqual(url_builder.relative_path, config.simple_path)\n self.assertEqual(request.headers, {'content-type': self.MIME_TYPE})\n self.assertEqual(request.body, CONTENT)\n self.assertEqual(request.loggable_body, '')\n\n def test_configure_request_w_simple_w_body(self):\n from google.cloud._helpers import _to_bytes\n from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n CONTENT = b'CONTENT'\n BODY = b'BODY'\n config = _UploadConfig()\n request = _Request(body=BODY)\n request.headers['content-type'] = 'text/plain'\n url_builder = _Dummy(query_params={})\n upload = self._make_one(_Stream(CONTENT))\n upload.strategy = SIMPLE_UPLOAD\n upload.configure_request(config, request, url_builder)\n self.assertEqual(url_builder.query_params, {'uploadType': 'multipart'})\n self.assertEqual(url_builder.relative_path, config.simple_path)\n self.assertEqual(list(request.headers), ['content-type'])\n ctype, boundary = [x.strip() for x in request.headers['content-type'].split(';')]\n self.assertEqual(ctype, 'multipart/related')\n self.assertTrue(boundary.startswith('boundary=\"=='))\n self.assertTrue(boundary.endswith('==\"'))\n divider = b'--' + _to_bytes(boundary[len('boundary=\"'):-1])\n chunks = request.body.split(divider)[1:-1]\n self.assertEqual(len(chunks), 2)\n parse_chunk = _email_chunk_parser()\n text_msg = parse_chunk(chunks[0].strip())\n self.assertEqual(dict(text_msg._headers), {'Content-Type': 'text/plain', 'MIME-Version': '1.0'})\n self.assertEqual(text_msg._payload, BODY.decode('ascii'))\n app_msg = parse_chunk(chunks[1].strip())\n self.assertEqual(dict(app_msg._headers), {'Content-Type': self.MIME_TYPE, 'Content-Transfer-Encoding': 'binary', 'MIME-Version': '1.0'})\n self.assertEqual(app_msg._payload, CONTENT.decode('ascii'))\n self.assertTrue(b'' in request.loggable_body)\n", "method_code": " def configure_request(self, http_request, url_builder):\n \"\"\"Update http_request/url_builder with download-appropriate values.\n \n :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: the request to be updated\n \n :type url_builder: instance with settable 'query_params' attribute.\n :param url_builder: transfer policy object to be updated\n \"\"\"\n url_builder.query_params['alt'] = 'media'\n http_request.headers['Range'] = 'bytes=0-%d' % (self.chunksize - 1,)\n ", "context": "class Download(_Transfer):\n def configure_request(self, http_request, url_builder): ...\n def __init__(self, stream, **kwds): ...\n def from_file(cls, filename, overwrite=False, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds): ...\n def progress(self): ...\n def total_size(self): ...\n def encoding(self): ...\n def __repr__(self): ...\n def _set_total(self, info): ...\n def initialize_download(self, http_request, http): ...\n def _normalize_start_end(self, start, end=None): ...\n def _set_range_header(request, start, end=None): ...\n def _compute_end_byte(self, start, end=None, use_chunks=True): ...\n def _get_chunk(self, start, end, headers=None): ...\n def _process_response(self, response): ...\n def get_range(self, start, end=None, use_chunks=True): ...\n def stream_file(self, use_chunks=True, headers=None): ...\n\n self._initial_response = None\n self._progress = 0\n self._total_size = total_size\n self._encoding = None\n\n _ACCEPTABLE_STATUSES = set((http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_configure_request", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000439.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_initialize", "tests": "import unittest\n\nclass Test_initialize(unittest.TestCase):\n def test_initialize_download_already_initialized(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n request = _Request()\n download = self._make_one(_Stream())\n download._initialize(None, self.URL)\n with self.assertRaises(TransferInvalidError):\n download.initialize_download(request, http=object())\n", "method_code": " def _initialize(self, http, url):\n \"\"\"Initialize this download by setting :attr:`http` and :attr`url`.\n \n Allow the user to be able to pre-initialize :attr:`http` by setting\n the value in the constructor; in that case, we ignore the provided\n http.\n \n :type http: :class:`httplib2.Http` (or a worklike) or None.\n :param http: the Http instance to use to make requests.\n \n :type url: str\n :param url: The url for this transfer.\n \"\"\"\n self._ensure_uninitialized()\n if self.http is None:\n self._http = http or httplib2.Http()\n self._url = url\n ", "context": "class _Transfer(object):\n def _initialize(self, http, url): ...\n def __init__(self, stream, close_stream=False, chunksize=_DEFAULT_CHUNKSIZE, auto_transfer=True, http=None, num_retries=5): ...\n def __repr__(self): ...\n def close_stream(self): ...\n def http(self): ...\n def bytes_http(self): ...\n def bytes_http(self, value): ...\n def num_retries(self): ...\n def num_retries(self, value): ...\n def stream(self): ...\n def url(self): ...\n def initialized(self): ...\n def _ensure_initialized(self): ...\n def _ensure_uninitialized(self): ...\n def __del__(self): ...\n\n self._bytes_http = None\n self._close_stream = close_stream\n self._http = http\n self._stream = stream\n self._url = None\n self.num_retries = num_retries\n self.auto_transfer = auto_transfer\n self.chunksize = chunksize\n\n _num_retries = None\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_initialize_download_already_initialized", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000440.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "initialize_download", "tests": "import unittest\n\nclass Test_initialize_download(unittest.TestCase):\n def test_initialize_download_wo_autotransfer(self):\n request = _Request()\n http = object()\n download = self._make_one(_Stream(), auto_transfer=False)\n download.initialize_download(request, http)\n self.assertIs(download.http, http)\n self.assertEqual(download.url, request.url)\n\n def test_initialize_download_w_autotransfer_failing(self):\n from six.moves import http_client\n from google.cloud._testing import _Monkey\n from google.cloud.streaming import transfer as MUT\n from google.cloud.streaming.exceptions import HttpError\n request = _Request()\n http = object()\n download = self._make_one(_Stream(), auto_transfer=True)\n response = _makeResponse(http_client.BAD_REQUEST)\n requester = _MakeRequest(response)\n with _Monkey(MUT, make_api_request=requester):\n with self.assertRaises(HttpError):\n download.initialize_download(request, http)\n self.assertTrue(len(requester._requested), 1)\n self.assertIs(requester._requested[0][0], request)\n", "method_code": " def initialize_download(self, http_request, http):\n \"\"\"Initialize this download.\n \n If the instance has :attr:`auto_transfer` enabled, begins the\n download immediately.\n \n :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: the request to use to initialize this download.\n \n :type http: :class:`httplib2.Http` (or workalike)\n :param http: Http instance for this request.\n \"\"\"\n self._ensure_uninitialized()\n url = http_request.url\n if self.auto_transfer:\n end_byte = self._compute_end_byte(0)\n self._set_range_header(http_request, 0, end_byte)\n response = make_api_request(self.bytes_http or http, http_request)\n if response.status_code not in self._ACCEPTABLE_STATUSES:\n raise HttpError.from_response(response)\n self._initial_response = response\n self._set_total(response.info)\n url = response.info.get('content-location', response.request_url)\n self._initialize(http, url)\n if self.auto_transfer:\n self.stream_file(use_chunks=True, headers=http_request.headers)\n ", "context": "class Download(_Transfer):\n def initialize_download(self, http_request, http): ...\n def __init__(self, stream, **kwds): ...\n def from_file(cls, filename, overwrite=False, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds): ...\n def progress(self): ...\n def total_size(self): ...\n def encoding(self): ...\n def __repr__(self): ...\n def configure_request(self, http_request, url_builder): ...\n def _set_total(self, info): ...\n def _normalize_start_end(self, start, end=None): ...\n def _set_range_header(request, start, end=None): ...\n def _compute_end_byte(self, start, end=None, use_chunks=True): ...\n def _get_chunk(self, start, end, headers=None): ...\n def _process_response(self, response): ...\n def get_range(self, start, end=None, use_chunks=True): ...\n def stream_file(self, use_chunks=True, headers=None): ...\n\n self._initial_response = None\n self._progress = 0\n self._total_size = total_size\n self._encoding = None\n\n _ACCEPTABLE_STATUSES = set((http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_initialize_download_wo_autotransfer", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000441.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_normalize_start_end", "tests": "import unittest\n\nclass Test_normalize_start_end(unittest.TestCase):\n def test__normalize_start_end_w_end_w_start_lt_0(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._make_one(_Stream())\n with self.assertRaises(TransferInvalidError):\n download._normalize_start_end(-1, 0)\n\n def test__normalize_start_end_w_end_w_start_gt_total(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._make_one(_Stream())\n download._set_total({'content-range': 'bytes 0-1/2'})\n with self.assertRaises(TransferInvalidError):\n download._normalize_start_end(3, 0)\n\n def test__normalize_start_end_w_end_lt_start(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n download = self._make_one(_Stream())\n download._set_total({'content-range': 'bytes 0-1/2'})\n with self.assertRaises(TransferInvalidError):\n download._normalize_start_end(1, 0)\n\n def test__normalize_start_end_w_end_gt_start(self):\n download = self._make_one(_Stream())\n download._set_total({'content-range': 'bytes 0-1/2'})\n self.assertEqual(download._normalize_start_end(1, 2), (1, 1))\n\n def test__normalize_start_end_wo_end_w_start_lt_0(self):\n download = self._make_one(_Stream())\n download._set_total({'content-range': 'bytes 0-1/2'})\n self.assertEqual(download._normalize_start_end(-2), (0, 1))\n self.assertEqual(download._normalize_start_end(-1), (1, 1))\n\n def test__normalize_start_end_wo_end_w_start_ge_0(self):\n download = self._make_one(_Stream())\n download._set_total({'content-range': 'bytes 0-1/100'})\n self.assertEqual(download._normalize_start_end(0), (0, 99))\n self.assertEqual(download._normalize_start_end(1), (1, 99))\n", "method_code": " def _normalize_start_end(self, start, end=None):\n \"\"\"Validate / fix up byte range.\n \n :type start: int\n :param start: start byte of the range: if negative, used as an\n offset from the end.\n \n :type end: int\n :param end: end byte of the range.\n \n :rtype: tuple, (start, end)\n :returns: the normalized start, end pair.\n :raises: :exc:`google.cloud.streaming.exceptions.TransferInvalidError`\n for invalid combinations of start, end.\n \"\"\"\n if end is not None:\n if start < 0:\n raise TransferInvalidError('Cannot have end index with negative start index')\n elif start >= self.total_size:\n raise TransferInvalidError('Cannot have start index greater than total size')\n end = min(end, self.total_size - 1)\n if end < start:\n raise TransferInvalidError('Range requested with end[%s] < start[%s]' % (end, start))\n return (start, end)\n else:\n if start < 0:\n start = max(0, start + self.total_size)\n return (start, self.total_size - 1)\n ", "context": "class Download(_Transfer):\n def _normalize_start_end(self, start, end=None): ...\n def __init__(self, stream, **kwds): ...\n def from_file(cls, filename, overwrite=False, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds): ...\n def progress(self): ...\n def total_size(self): ...\n def encoding(self): ...\n def __repr__(self): ...\n def configure_request(self, http_request, url_builder): ...\n def _set_total(self, info): ...\n def initialize_download(self, http_request, http): ...\n def _set_range_header(request, start, end=None): ...\n def _compute_end_byte(self, start, end=None, use_chunks=True): ...\n def _get_chunk(self, start, end, headers=None): ...\n def _process_response(self, response): ...\n def get_range(self, start, end=None, use_chunks=True): ...\n def stream_file(self, use_chunks=True, headers=None): ...\n\n self._initial_response = None\n self._progress = 0\n self._total_size = total_size\n self._encoding = None\n\n _ACCEPTABLE_STATUSES = set((http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__normalize_start_end_w_end_w_start_lt_0", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000442.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_set_range_header", "tests": "import unittest\n\nclass Test_set_range_header(unittest.TestCase):\n def test__set_range_header_w_start_lt_0(self):\n request = _Request()\n download = self._make_one(_Stream())\n download._set_range_header(request, -1)\n self.assertEqual(request.headers['range'], 'bytes=-1')\n\n def test__set_range_header_w_start_ge_0_w_end(self):\n request = _Request()\n download = self._make_one(_Stream())\n download._set_range_header(request, 0, 1)\n self.assertEqual(request.headers['range'], 'bytes=0-1')\n", "method_code": " def _set_range_header(request, start, end=None):\n \"\"\"Update the 'Range' header in a request to match a byte range.\n \n :type request: :class:`google.cloud.streaming.http_wrapper.Request`\n :param request: the request to update\n \n :type start: int\n :param start: start byte of the range: if negative, used as an\n offset from the end.\n \n :type end: int\n :param end: end byte of the range.\n \"\"\"\n if start < 0:\n request.headers['range'] = 'bytes=%d' % start\n elif end is None:\n request.headers['range'] = 'bytes=%d-' % start\n else:\n request.headers['range'] = 'bytes=%d-%d' % (start, end)\n ", "context": "class Download(_Transfer):\n @staticmethod\n def _set_range_header(request, start, end=None): ...\n def __init__(self, stream, **kwds): ...\n def from_file(cls, filename, overwrite=False, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds): ...\n def progress(self): ...\n def total_size(self): ...\n def encoding(self): ...\n def __repr__(self): ...\n def configure_request(self, http_request, url_builder): ...\n def _set_total(self, info): ...\n def initialize_download(self, http_request, http): ...\n def _normalize_start_end(self, start, end=None): ...\n def _compute_end_byte(self, start, end=None, use_chunks=True): ...\n def _get_chunk(self, start, end, headers=None): ...\n def _process_response(self, response): ...\n def get_range(self, start, end=None, use_chunks=True): ...\n def stream_file(self, use_chunks=True, headers=None): ...\n\n self._initial_response = None\n self._progress = 0\n self._total_size = total_size\n self._encoding = None\n\n _ACCEPTABLE_STATUSES = set((http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__set_range_header_w_start_lt_0", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000443.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_compute_end_byte", "tests": "import unittest\n\nclass Test_compute_end_byte(unittest.TestCase):\n def test__compute_end_byte_w_start_lt_0_w_end(self):\n download = self._make_one(_Stream())\n self.assertEqual(download._compute_end_byte(-1, 1), 1)\n", "method_code": " def _compute_end_byte(self, start, end=None, use_chunks=True):\n \"\"\"Compute the last byte to fetch for this request.\n \n Based on the HTTP spec for Range and Content-Range.\n \n .. note::\n This is potentially confusing in several ways:\n - the value for the last byte is 0-based, eg \"fetch 10 bytes\n from the beginning\" would return 9 here.\n - if we have no information about size, and don't want to\n use the chunksize, we'll return None.\n \n :type start: int\n :param start: start byte of the range.\n \n :type end: int\n :param end: (Optional) suggested last byte of the range.\n \n :type use_chunks: bool\n :param use_chunks: If False, ignore :attr:`chunksize`.\n \n :rtype: str\n :returns: Last byte to use in a 'Range' header, or None.\n \"\"\"\n end_byte = end\n if start < 0 and (not self.total_size):\n return end_byte\n if use_chunks:\n alternate = start + self.chunksize - 1\n if end_byte is not None:\n end_byte = min(end_byte, alternate)\n else:\n end_byte = alternate\n if self.total_size:\n alternate = self.total_size - 1\n if end_byte is not None:\n end_byte = min(end_byte, alternate)\n else:\n end_byte = alternate\n return end_byte\n ", "context": "class Download(_Transfer):\n def _compute_end_byte(self, start, end=None, use_chunks=True): ...\n def __init__(self, stream, **kwds): ...\n def from_file(cls, filename, overwrite=False, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds): ...\n def progress(self): ...\n def total_size(self): ...\n def encoding(self): ...\n def __repr__(self): ...\n def configure_request(self, http_request, url_builder): ...\n def _set_total(self, info): ...\n def initialize_download(self, http_request, http): ...\n def _normalize_start_end(self, start, end=None): ...\n def _set_range_header(request, start, end=None): ...\n def _get_chunk(self, start, end, headers=None): ...\n def _process_response(self, response): ...\n def get_range(self, start, end=None, use_chunks=True): ...\n def stream_file(self, use_chunks=True, headers=None): ...\n\n self._initial_response = None\n self._progress = 0\n self._total_size = total_size\n self._encoding = None\n\n _ACCEPTABLE_STATUSES = set((http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__compute_end_byte_w_start_lt_0_w_end", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000444.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_get_chunk", "tests": "import unittest\n\nclass Test_get_chunk(unittest.TestCase):\n def test__get_chunk(self):\n from six.moves import http_client\n from google.cloud._testing import _Monkey\n from google.cloud.streaming import transfer as MUT\n http = object()\n download = self._make_one(_Stream())\n download._initialize(http, self.URL)\n response = _makeResponse(http_client.OK)\n requester = _MakeRequest(response)\n with _Monkey(MUT, Request=_Request, make_api_request=requester):\n found = download._get_chunk(0, 10)\n self.assertIs(found, response)\n self.assertTrue(len(requester._requested), 1)\n request = requester._requested[0][0]\n self.assertEqual(request.headers['range'], 'bytes=0-10')\n", "method_code": " def _get_chunk(self, start, end, headers=None):\n \"\"\"Retrieve a chunk of the file.\n \n :type start: int\n :param start: start byte of the range.\n \n :type end: int\n :param end: (Optional) end byte of the range.\n \n :type headers: dict\n :param headers: (Optional) Headers to be used for the ``Request``.\n \n :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: response from the chunk request.\n \"\"\"\n self._ensure_initialized()\n request = Request(url=self.url, headers=headers)\n self._set_range_header(request, start, end=end)\n return make_api_request(self.bytes_http, request, retries=self.num_retries)\n ", "context": "class Download(_Transfer):\n def _get_chunk(self, start, end, headers=None): ...\n def __init__(self, stream, **kwds): ...\n def from_file(cls, filename, overwrite=False, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds): ...\n def progress(self): ...\n def total_size(self): ...\n def encoding(self): ...\n def __repr__(self): ...\n def configure_request(self, http_request, url_builder): ...\n def _set_total(self, info): ...\n def initialize_download(self, http_request, http): ...\n def _normalize_start_end(self, start, end=None): ...\n def _set_range_header(request, start, end=None): ...\n def _compute_end_byte(self, start, end=None, use_chunks=True): ...\n def _process_response(self, response): ...\n def get_range(self, start, end=None, use_chunks=True): ...\n def stream_file(self, use_chunks=True, headers=None): ...\n\n self._initial_response = None\n self._progress = 0\n self._total_size = total_size\n self._encoding = None\n\n _ACCEPTABLE_STATUSES = set((http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__get_chunk", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000445.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_process_response", "tests": "import unittest\n\nclass Test_process_response(unittest.TestCase):\n def test__process_response_w_FORBIDDEN(self):\n from google.cloud.streaming.exceptions import HttpError\n from six.moves import http_client\n download = self._make_one(_Stream())\n response = _makeResponse(http_client.FORBIDDEN)\n with self.assertRaises(HttpError):\n download._process_response(response)\n\n def test__process_response_w_NOT_FOUND(self):\n from google.cloud.streaming.exceptions import HttpError\n from six.moves import http_client\n download = self._make_one(_Stream())\n response = _makeResponse(http_client.NOT_FOUND)\n with self.assertRaises(HttpError):\n download._process_response(response)\n\n def test__process_response_w_other_error(self):\n from google.cloud.streaming.exceptions import TransferRetryError\n from six.moves import http_client\n download = self._make_one(_Stream())\n response = _makeResponse(http_client.BAD_REQUEST)\n with self.assertRaises(TransferRetryError):\n download._process_response(response)\n\n def test__process_response_w_OK_wo_encoding(self):\n from six.moves import http_client\n stream = _Stream()\n download = self._make_one(stream)\n response = _makeResponse(http_client.OK, content='OK')\n found = download._process_response(response)\n self.assertIs(found, response)\n self.assertEqual(stream._written, ['OK'])\n self.assertEqual(download.progress, 2)\n self.assertIsNone(download.encoding)\n\n def test__process_response_w_NO_CONTENT(self):\n from six.moves import http_client\n stream = _Stream()\n download = self._make_one(stream)\n response = _makeResponse(status_code=http_client.NO_CONTENT)\n found = download._process_response(response)\n self.assertIs(found, response)\n self.assertEqual(stream._written, [''])\n self.assertEqual(download.progress, 0)\n self.assertIsNone(download.encoding)\n", "method_code": " def _process_response(self, response):\n \"\"\"Update attribtes and writing stream, based on response.\n \n :type response: :class:`google.cloud.streaming.http_wrapper.Response`\n :param response: response from a download request.\n \n :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: the response\n :raises: :exc:`google.cloud.streaming.exceptions.HttpError` for\n missing / unauthorized responses;\n :exc:`google.cloud.streaming.exceptions.TransferRetryError`\n for other error responses.\n \"\"\"\n if response.status_code not in self._ACCEPTABLE_STATUSES:\n if response.status_code in (http_client.FORBIDDEN, http_client.NOT_FOUND):\n raise HttpError.from_response(response)\n else:\n raise TransferRetryError(response.content)\n if response.status_code in (http_client.OK, http_client.PARTIAL_CONTENT):\n self.stream.write(response.content)\n self._progress += response.length\n if response.info and 'content-encoding' in response.info:\n self._encoding = response.info['content-encoding']\n elif response.status_code == http_client.NO_CONTENT:\n self.stream.write('')\n return response\n ", "context": "class Download(_Transfer):\n def _process_response(self, response): ...\n def __init__(self, stream, **kwds): ...\n def from_file(cls, filename, overwrite=False, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, auto_transfer=True, total_size=None, **kwds): ...\n def progress(self): ...\n def total_size(self): ...\n def encoding(self): ...\n def __repr__(self): ...\n def configure_request(self, http_request, url_builder): ...\n def _set_total(self, info): ...\n def initialize_download(self, http_request, http): ...\n def _normalize_start_end(self, start, end=None): ...\n def _set_range_header(request, start, end=None): ...\n def _compute_end_byte(self, start, end=None, use_chunks=True): ...\n def _get_chunk(self, start, end, headers=None): ...\n def get_range(self, start, end=None, use_chunks=True): ...\n def stream_file(self, use_chunks=True, headers=None): ...\n\n self._initial_response = None\n self._progress = 0\n self._total_size = total_size\n self._encoding = None\n\n _ACCEPTABLE_STATUSES = set((http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__process_response_w_FORBIDDEN", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000446.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_set_default_strategy", "tests": "import unittest\n\nclass Test_set_default_strategy(unittest.TestCase):\n def test__set_default_strategy_w_existing_strategy(self):\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n config = _Dummy(resumable_path='/resumable/endpoint', simple_multipart=True, simple_path='/upload/endpoint')\n request = _Request()\n upload = self._make_one(_Stream)\n upload.strategy = RESUMABLE_UPLOAD\n upload._set_default_strategy(config, request)\n self.assertEqual(upload.strategy, RESUMABLE_UPLOAD)\n\n def test__set_default_strategy_wo_resumable_path(self):\n from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n config = _Dummy(resumable_path=None, simple_multipart=True, simple_path='/upload/endpoint')\n request = _Request()\n upload = self._make_one(_Stream())\n upload._set_default_strategy(config, request)\n self.assertEqual(upload.strategy, SIMPLE_UPLOAD)\n\n def test__set_default_strategy_w_total_size_gt_threshhold(self):\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD_THRESHOLD\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n config = _UploadConfig()\n request = _Request()\n upload = self._make_one(_Stream(), total_size=RESUMABLE_UPLOAD_THRESHOLD + 1)\n upload._set_default_strategy(config, request)\n self.assertEqual(upload.strategy, RESUMABLE_UPLOAD)\n\n def test__set_default_strategy_w_body_wo_multipart(self):\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n config = _UploadConfig()\n config.simple_multipart = False\n request = _Request(body=CONTENT)\n upload = self._make_one(_Stream(), total_size=len(CONTENT))\n upload._set_default_strategy(config, request)\n self.assertEqual(upload.strategy, RESUMABLE_UPLOAD)\n", "method_code": " def _set_default_strategy(self, upload_config, http_request):\n \"\"\"Determine and set the default upload strategy for this upload.\n \n We generally prefer simple or multipart, unless we're forced to\n use resumable. This happens when any of (1) the upload is too\n large, (2) the simple endpoint doesn't support multipart requests\n and we have metadata, or (3) there is no simple upload endpoint.\n \n :type upload_config: instance w/ ``max_size`` and ``accept``\n attributes\n :param upload_config: Configuration for the upload endpoint.\n \n :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: The associated http request.\n \"\"\"\n if upload_config.resumable_path is None:\n self.strategy = SIMPLE_UPLOAD\n if self.strategy is not None:\n return\n strategy = SIMPLE_UPLOAD\n if self.total_size is not None and self.total_size > RESUMABLE_UPLOAD_THRESHOLD:\n strategy = RESUMABLE_UPLOAD\n if http_request.body and (not upload_config.simple_multipart):\n strategy = RESUMABLE_UPLOAD\n if not upload_config.simple_path:\n strategy = RESUMABLE_UPLOAD\n self.strategy = strategy\n ", "context": "class Upload(_Transfer):\n def _set_default_strategy(self, upload_config, http_request): ...\n def __init__(self, stream, mime_type, total_size=None, http=None, close_stream=False, auto_transfer=True, **kwds): ...\n def from_file(cls, filename, mime_type=None, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, mime_type, total_size=None, auto_transfer=True, **kwds): ...\n def complete(self): ...\n def mime_type(self): ...\n def progress(self): ...\n def strategy(self): ...\n def strategy(self, value): ...\n def total_size(self): ...\n def total_size(self, value): ...\n def __repr__(self): ...\n def configure_request(self, upload_config, http_request, url_builder): ...\n def _configure_media_request(self, http_request): ...\n def _configure_multipart_request(self, http_request): ...\n def _configure_resumable_request(self, http_request): ...\n def refresh_upload_state(self): ...\n def _get_range_header(response): ...\n def initialize_upload(self, http_request, http): ...\n def _last_byte(range_header): ...\n def _validate_chunksize(self, chunksize=None): ...\n def stream_file(self, use_chunks=True): ...\n def _send_media_request(self, request, end): ...\n def _send_media_body(self, start): ...\n def _send_chunk(self, start): ...\n\n self._final_response = None\n self._server_chunk_granularity = None\n self._complete = False\n self._mime_type = mime_type\n self._progress = 0\n self._strategy = None\n self._total_size = total_size\n\n _REQUIRED_SERIALIZATION_KEYS = set(('auto_transfer', 'mime_type', 'total_size', 'url'))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__set_default_strategy_w_existing_strategy", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000447.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "refresh_upload_state", "tests": "import unittest\n\nclass Test_refresh_upload_state(unittest.TestCase):\n def test_refresh_upload_state_w_simple_strategy(self):\n from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n upload = self._make_one(_Stream())\n upload.strategy = SIMPLE_UPLOAD\n upload.refresh_upload_state()\n\n def test_refresh_upload_state_not_initialized(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n upload = self._make_one(_Stream())\n upload.strategy = RESUMABLE_UPLOAD\n with self.assertRaises(TransferInvalidError):\n upload.refresh_upload_state()\n\n def test_refresh_upload_state_w_OK(self):\n from six.moves import http_client\n from google.cloud._testing import _Monkey\n from google.cloud.streaming import transfer as MUT\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN)\n http = object()\n stream = _Stream()\n upload = self._make_one(stream, total_size=LEN)\n upload.strategy = RESUMABLE_UPLOAD\n upload._initialize(http, _Request.URL)\n info = {'content-range': RESP_RANGE}\n response = _makeResponse(http_client.OK, info, CONTENT)\n requester = _MakeRequest(response)\n with _Monkey(MUT, Request=_Request, make_api_request=requester):\n upload.refresh_upload_state()\n self.assertTrue(upload.complete)\n self.assertEqual(upload.progress, LEN)\n self.assertEqual(stream.tell(), LEN)\n self.assertIs(upload._final_response, response)\n\n def test_refresh_upload_state_w_CREATED(self):\n from six.moves import http_client\n from google.cloud._testing import _Monkey\n from google.cloud.streaming import transfer as MUT\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n RESP_RANGE = 'bytes 0-%d/%d' % (LEN - 1, LEN)\n http = object()\n stream = _Stream()\n upload = self._make_one(stream, total_size=LEN)\n upload.strategy = RESUMABLE_UPLOAD\n upload._initialize(http, _Request.URL)\n info = {'content-range': RESP_RANGE}\n response = _makeResponse(http_client.CREATED, info, CONTENT)\n requester = _MakeRequest(response)\n with _Monkey(MUT, Request=_Request, make_api_request=requester):\n upload.refresh_upload_state()\n self.assertTrue(upload.complete)\n self.assertEqual(upload.progress, LEN)\n self.assertEqual(stream.tell(), LEN)\n self.assertIs(upload._final_response, response)\n\n def test_refresh_upload_state_w_error(self):\n from six.moves import http_client\n from google.cloud._testing import _Monkey\n from google.cloud.streaming import transfer as MUT\n from google.cloud.streaming.exceptions import HttpError\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n LEN = len(CONTENT)\n http = object()\n stream = _Stream()\n upload = self._make_one(stream, total_size=LEN)\n upload.strategy = RESUMABLE_UPLOAD\n upload._initialize(http, _Request.URL)\n response = _makeResponse(http_client.FORBIDDEN)\n requester = _MakeRequest(response)\n with _Monkey(MUT, Request=_Request, make_api_request=requester):\n with self.assertRaises(HttpError):\n upload.refresh_upload_state()\n", "method_code": " def refresh_upload_state(self):\n \"\"\"Refresh the state of a resumable upload via query to the back-end.\n \"\"\"\n if self.strategy != RESUMABLE_UPLOAD:\n return\n self._ensure_initialized()\n refresh_request = Request(url=self.url, http_method='PUT', headers={'Content-Range': 'bytes */*'})\n refresh_response = make_api_request(self.http, refresh_request, redirections=0, retries=self.num_retries)\n range_header = self._get_range_header(refresh_response)\n if refresh_response.status_code in (http_client.OK, http_client.CREATED):\n self._complete = True\n self._progress = self.total_size\n self.stream.seek(self.progress)\n self._final_response = refresh_response\n elif refresh_response.status_code == RESUME_INCOMPLETE:\n if range_header is None:\n self._progress = 0\n else:\n self._progress = self._last_byte(range_header) + 1\n self.stream.seek(self.progress)\n else:\n raise HttpError.from_response(refresh_response)\n ", "context": "class Upload(_Transfer):\n def refresh_upload_state(self): ...\n def __init__(self, stream, mime_type, total_size=None, http=None, close_stream=False, auto_transfer=True, **kwds): ...\n def from_file(cls, filename, mime_type=None, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, mime_type, total_size=None, auto_transfer=True, **kwds): ...\n def complete(self): ...\n def mime_type(self): ...\n def progress(self): ...\n def strategy(self): ...\n def strategy(self, value): ...\n def total_size(self): ...\n def total_size(self, value): ...\n def __repr__(self): ...\n def _set_default_strategy(self, upload_config, http_request): ...\n def configure_request(self, upload_config, http_request, url_builder): ...\n def _configure_media_request(self, http_request): ...\n def _configure_multipart_request(self, http_request): ...\n def _configure_resumable_request(self, http_request): ...\n def _get_range_header(response): ...\n def initialize_upload(self, http_request, http): ...\n def _last_byte(range_header): ...\n def _validate_chunksize(self, chunksize=None): ...\n def stream_file(self, use_chunks=True): ...\n def _send_media_request(self, request, end): ...\n def _send_media_body(self, start): ...\n def _send_chunk(self, start): ...\n\n self._final_response = None\n self._server_chunk_granularity = None\n self._complete = False\n self._mime_type = mime_type\n self._progress = 0\n self._strategy = None\n self._total_size = total_size\n\n _REQUIRED_SERIALIZATION_KEYS = set(('auto_transfer', 'mime_type', 'total_size', 'url'))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_refresh_upload_state_w_simple_strategy", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000448.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_get_range_header", "tests": "import unittest\n\nclass Test_get_range_header(unittest.TestCase):\n def test__get_range_header_miss(self):\n upload = self._make_one(_Stream())\n response = _makeResponse(None)\n self.assertIsNone(upload._get_range_header(response))\n\n def test__get_range_header_w_Range(self):\n upload = self._make_one(_Stream())\n response = _makeResponse(None, {'Range': '123'})\n self.assertEqual(upload._get_range_header(response), '123')\n\n def test__get_range_header_w_range(self):\n upload = self._make_one(_Stream())\n response = _makeResponse(None, {'range': '123'})\n self.assertEqual(upload._get_range_header(response), '123')\n", "method_code": " def _get_range_header(response):\n \"\"\"Return a 'Range' header from a response.\n \n :type response: :class:`google.cloud.streaming.http_wrapper.Response`\n :param response: response to be queried\n \n :rtype: str\n :returns: The header used to determine the bytes range.\n \"\"\"\n return response.info.get('Range', response.info.get('range'))\n ", "context": "class Upload(_Transfer):\n @staticmethod\n def _get_range_header(response): ...\n def __init__(self, stream, mime_type, total_size=None, http=None, close_stream=False, auto_transfer=True, **kwds): ...\n def from_file(cls, filename, mime_type=None, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, mime_type, total_size=None, auto_transfer=True, **kwds): ...\n def complete(self): ...\n def mime_type(self): ...\n def progress(self): ...\n def strategy(self): ...\n def strategy(self, value): ...\n def total_size(self): ...\n def total_size(self, value): ...\n def __repr__(self): ...\n def _set_default_strategy(self, upload_config, http_request): ...\n def configure_request(self, upload_config, http_request, url_builder): ...\n def _configure_media_request(self, http_request): ...\n def _configure_multipart_request(self, http_request): ...\n def _configure_resumable_request(self, http_request): ...\n def refresh_upload_state(self): ...\n def initialize_upload(self, http_request, http): ...\n def _last_byte(range_header): ...\n def _validate_chunksize(self, chunksize=None): ...\n def stream_file(self, use_chunks=True): ...\n def _send_media_request(self, request, end): ...\n def _send_media_body(self, start): ...\n def _send_chunk(self, start): ...\n\n self._final_response = None\n self._server_chunk_granularity = None\n self._complete = False\n self._mime_type = mime_type\n self._progress = 0\n self._strategy = None\n self._total_size = total_size\n\n _REQUIRED_SERIALIZATION_KEYS = set(('auto_transfer', 'mime_type', 'total_size', 'url'))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__get_range_header_miss", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000449.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "initialize_upload", "tests": "import unittest\n\nclass Test_initialize_upload(unittest.TestCase):\n def test_initialize_upload_no_strategy(self):\n request = _Request()\n upload = self._make_one(_Stream())\n with self.assertRaises(ValueError):\n upload.initialize_upload(request, http=object())\n\n def test_initialize_upload_simple_w_http(self):\n from google.cloud.streaming.transfer import SIMPLE_UPLOAD\n request = _Request()\n upload = self._make_one(_Stream())\n upload.strategy = SIMPLE_UPLOAD\n upload.initialize_upload(request, http=object())\n", "method_code": " def initialize_upload(self, http_request, http):\n \"\"\"Initialize this upload from the given http_request.\n \n :type http_request: :class:`~.streaming.http_wrapper.Request`\n :param http_request: the request to be used\n \n :type http: :class:`httplib2.Http` (or workalike)\n :param http: Http instance for this request.\n \n :raises: :exc:`ValueError` if the instance has not been configured\n with a strategy.\n :rtype: :class:`~google.cloud.streaming.http_wrapper.Response`\n :returns: The response if the upload is resumable and auto transfer\n is not used.\n \"\"\"\n if self.strategy is None:\n raise ValueError('No upload strategy set; did you call configure_request?')\n if self.strategy != RESUMABLE_UPLOAD:\n return\n self._ensure_uninitialized()\n http_response = make_api_request(http, http_request, retries=self.num_retries)\n if http_response.status_code != http_client.OK:\n raise HttpError.from_response(http_response)\n granularity = http_response.info.get('X-Goog-Upload-Chunk-Granularity')\n if granularity is not None:\n granularity = int(granularity)\n self._server_chunk_granularity = granularity\n url = http_response.info['location']\n self._initialize(http, url)\n if self.auto_transfer:\n return self.stream_file(use_chunks=True)\n else:\n return http_response\n ", "context": "class Upload(_Transfer):\n def initialize_upload(self, http_request, http): ...\n def __init__(self, stream, mime_type, total_size=None, http=None, close_stream=False, auto_transfer=True, **kwds): ...\n def from_file(cls, filename, mime_type=None, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, mime_type, total_size=None, auto_transfer=True, **kwds): ...\n def complete(self): ...\n def mime_type(self): ...\n def progress(self): ...\n def strategy(self): ...\n def strategy(self, value): ...\n def total_size(self): ...\n def total_size(self, value): ...\n def __repr__(self): ...\n def _set_default_strategy(self, upload_config, http_request): ...\n def configure_request(self, upload_config, http_request, url_builder): ...\n def _configure_media_request(self, http_request): ...\n def _configure_multipart_request(self, http_request): ...\n def _configure_resumable_request(self, http_request): ...\n def refresh_upload_state(self): ...\n def _get_range_header(response): ...\n def _last_byte(range_header): ...\n def _validate_chunksize(self, chunksize=None): ...\n def stream_file(self, use_chunks=True): ...\n def _send_media_request(self, request, end): ...\n def _send_media_body(self, start): ...\n def _send_chunk(self, start): ...\n\n self._final_response = None\n self._server_chunk_granularity = None\n self._complete = False\n self._mime_type = mime_type\n self._progress = 0\n self._strategy = None\n self._total_size = total_size\n\n _REQUIRED_SERIALIZATION_KEYS = set(('auto_transfer', 'mime_type', 'total_size', 'url'))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test_initialize_upload_no_strategy", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000450.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_last_byte", "tests": "import unittest\n\nclass Test_last_byte(unittest.TestCase):\n def test__last_byte(self):\n upload = self._make_one(_Stream())\n self.assertEqual(upload._last_byte('123-456'), 456)\n", "method_code": " def _last_byte(range_header):\n \"\"\"Parse the last byte from a 'Range' header.\n \n :type range_header: str\n :param range_header: 'Range' header value per RFC 2616/7233\n \n :rtype: int\n :returns: The last byte from a range header.\n \"\"\"\n _, _, end = range_header.partition('-')\n return int(end)\n ", "context": "class Upload(_Transfer):\n @staticmethod\n def _last_byte(range_header): ...\n def __init__(self, stream, mime_type, total_size=None, http=None, close_stream=False, auto_transfer=True, **kwds): ...\n def from_file(cls, filename, mime_type=None, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, mime_type, total_size=None, auto_transfer=True, **kwds): ...\n def complete(self): ...\n def mime_type(self): ...\n def progress(self): ...\n def strategy(self): ...\n def strategy(self, value): ...\n def total_size(self): ...\n def total_size(self, value): ...\n def __repr__(self): ...\n def _set_default_strategy(self, upload_config, http_request): ...\n def configure_request(self, upload_config, http_request, url_builder): ...\n def _configure_media_request(self, http_request): ...\n def _configure_multipart_request(self, http_request): ...\n def _configure_resumable_request(self, http_request): ...\n def refresh_upload_state(self): ...\n def _get_range_header(response): ...\n def initialize_upload(self, http_request, http): ...\n def _validate_chunksize(self, chunksize=None): ...\n def stream_file(self, use_chunks=True): ...\n def _send_media_request(self, request, end): ...\n def _send_media_body(self, start): ...\n def _send_chunk(self, start): ...\n\n self._final_response = None\n self._server_chunk_granularity = None\n self._complete = False\n self._mime_type = mime_type\n self._progress = 0\n self._strategy = None\n self._total_size = total_size\n\n _REQUIRED_SERIALIZATION_KEYS = set(('auto_transfer', 'mime_type', 'total_size', 'url'))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__last_byte", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000451.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_send_media_request", "tests": "import unittest\n\nclass Test_send_media_request(unittest.TestCase):\n def test__send_media_request_wo_error(self):\n from google.cloud._testing import _Monkey\n from google.cloud.streaming import transfer as MUT\n from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n CONTENT = b'ABCDEFGHIJ'\n bytes_http = object()\n stream = _Stream(CONTENT)\n upload = self._make_one(stream)\n upload.bytes_http = bytes_http\n headers = {'Content-Range': 'bytes 0-9/10', 'Content-Type': self.MIME_TYPE}\n request = _Request(self.UPLOAD_URL, 'PUT', CONTENT, headers)\n info = {'content-length': '0', 'range': 'bytes=0-4'}\n response = _makeResponse(RESUME_INCOMPLETE, info)\n requester = _MakeRequest(response)\n with _Monkey(MUT, make_api_request=requester):\n upload._send_media_request(request, 9)\n self.assertEqual(len(requester._responses), 0)\n self.assertEqual(len(requester._requested), 1)\n used_request, used_http, _ = requester._requested[0]\n self.assertIs(used_request, request)\n self.assertIs(used_http, bytes_http)\n self.assertEqual(stream.tell(), 4)\n\n def test__send_media_request_w_error(self):\n from six.moves import http_client\n from google.cloud._testing import _Monkey\n from google.cloud.streaming import transfer as MUT\n from google.cloud.streaming.exceptions import HttpError\n from google.cloud.streaming.http_wrapper import RESUME_INCOMPLETE\n from google.cloud.streaming.transfer import RESUMABLE_UPLOAD\n CONTENT = b'ABCDEFGHIJ'\n bytes_http = object()\n http = object()\n stream = _Stream(CONTENT)\n upload = self._make_one(stream)\n upload.strategy = RESUMABLE_UPLOAD\n upload._initialize(http, self.UPLOAD_URL)\n upload.bytes_http = bytes_http\n headers = {'Content-Range': 'bytes 0-9/10', 'Content-Type': self.MIME_TYPE}\n request = _Request(self.UPLOAD_URL, 'PUT', CONTENT, headers)\n info_1 = {'content-length': '0', 'range': 'bytes=0-4'}\n response_1 = _makeResponse(http_client.FORBIDDEN, info_1)\n info_2 = {'Content-Length': '0', 'Range': 'bytes=0-4'}\n response_2 = _makeResponse(RESUME_INCOMPLETE, info_2)\n requester = _MakeRequest(response_1, response_2)\n with _Monkey(MUT, Request=_Request, make_api_request=requester):\n with self.assertRaises(HttpError):\n upload._send_media_request(request, 9)\n self.assertEqual(len(requester._responses), 0)\n self.assertEqual(len(requester._requested), 2)\n first_request, first_http, _ = requester._requested[0]\n self.assertIs(first_request, request)\n self.assertIs(first_http, bytes_http)\n second_request, second_http, _ = requester._requested[1]\n self.assertEqual(second_request.url, self.UPLOAD_URL)\n self.assertEqual(second_request.http_method, 'PUT')\n self.assertEqual(second_request.headers, {'Content-Range': 'bytes */*'})\n self.assertIs(second_http, http)\n", "method_code": " def _send_media_request(self, request, end):\n \"\"\"Peform API upload request.\n \n Helper for _send_media_body & _send_chunk:\n \n :type request: :class:`google.cloud.streaming.http_wrapper.Request`\n :param request: the request to upload\n \n :type end: int\n :param end: end byte of the to be uploaded\n \n :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: the response\n :raises: :exc:`~.streaming.exceptions.HttpError` if the status\n code from the response indicates an error.\n \"\"\"\n response = make_api_request(self.bytes_http, request, retries=self.num_retries)\n if response.status_code not in (http_client.OK, http_client.CREATED, RESUME_INCOMPLETE):\n self.refresh_upload_state()\n raise HttpError.from_response(response)\n if response.status_code == RESUME_INCOMPLETE:\n last_byte = self._last_byte(self._get_range_header(response))\n if last_byte + 1 != end:\n self.stream.seek(last_byte)\n return response\n ", "context": "class Upload(_Transfer):\n def _send_media_request(self, request, end): ...\n def __init__(self, stream, mime_type, total_size=None, http=None, close_stream=False, auto_transfer=True, **kwds): ...\n def from_file(cls, filename, mime_type=None, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, mime_type, total_size=None, auto_transfer=True, **kwds): ...\n def complete(self): ...\n def mime_type(self): ...\n def progress(self): ...\n def strategy(self): ...\n def strategy(self, value): ...\n def total_size(self): ...\n def total_size(self, value): ...\n def __repr__(self): ...\n def _set_default_strategy(self, upload_config, http_request): ...\n def configure_request(self, upload_config, http_request, url_builder): ...\n def _configure_media_request(self, http_request): ...\n def _configure_multipart_request(self, http_request): ...\n def _configure_resumable_request(self, http_request): ...\n def refresh_upload_state(self): ...\n def _get_range_header(response): ...\n def initialize_upload(self, http_request, http): ...\n def _last_byte(range_header): ...\n def _validate_chunksize(self, chunksize=None): ...\n def stream_file(self, use_chunks=True): ...\n def _send_media_body(self, start): ...\n def _send_chunk(self, start): ...\n\n self._final_response = None\n self._server_chunk_granularity = None\n self._complete = False\n self._mime_type = mime_type\n self._progress = 0\n self._strategy = None\n self._total_size = total_size\n\n _REQUIRED_SERIALIZATION_KEYS = set(('auto_transfer', 'mime_type', 'total_size', 'url'))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__send_media_request_wo_error", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000452.py"} {"focal_file": "lib/google/cloud/streaming/transfer.py", "focal_class": null, "focal_method": "_send_media_body", "tests": "import unittest\n\nclass Test_send_media_body(unittest.TestCase):\n def test__send_media_body_not_initialized(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n upload = self._make_one(_Stream())\n with self.assertRaises(TransferInvalidError):\n upload._send_media_body(0)\n\n def test__send_media_body_wo_total_size(self):\n from google.cloud.streaming.exceptions import TransferInvalidError\n http = object()\n upload = self._make_one(_Stream())\n upload._initialize(http, _Request.URL)\n with self.assertRaises(TransferInvalidError):\n upload._send_media_body(0)\n", "method_code": " def _send_media_body(self, start):\n \"\"\"Send the entire stream in a single request.\n \n Helper for :meth:`stream_file`:\n \n :type start: int\n :param start: start byte of the range.\n \n :rtype: :class:`google.cloud.streaming.http_wrapper.Response`\n :returns: The response from the media upload request.\n \"\"\"\n self._ensure_initialized()\n if self.total_size is None:\n raise TransferInvalidError('Total size must be known for SendMediaBody')\n body_stream = StreamSlice(self.stream, self.total_size - start)\n request = Request(url=self.url, http_method='PUT', body=body_stream)\n request.headers['Content-Type'] = self.mime_type\n if start == self.total_size:\n range_string = 'bytes */%s' % self.total_size\n else:\n range_string = 'bytes %s-%s/%s' % (start, self.total_size - 1, self.total_size)\n request.headers['Content-Range'] = range_string\n return self._send_media_request(request, self.total_size)\n ", "context": "class Upload(_Transfer):\n def _send_media_body(self, start): ...\n def __init__(self, stream, mime_type, total_size=None, http=None, close_stream=False, auto_transfer=True, **kwds): ...\n def from_file(cls, filename, mime_type=None, auto_transfer=True, **kwds): ...\n def from_stream(cls, stream, mime_type, total_size=None, auto_transfer=True, **kwds): ...\n def complete(self): ...\n def mime_type(self): ...\n def progress(self): ...\n def strategy(self): ...\n def strategy(self, value): ...\n def total_size(self): ...\n def total_size(self, value): ...\n def __repr__(self): ...\n def _set_default_strategy(self, upload_config, http_request): ...\n def configure_request(self, upload_config, http_request, url_builder): ...\n def _configure_media_request(self, http_request): ...\n def _configure_multipart_request(self, http_request): ...\n def _configure_resumable_request(self, http_request): ...\n def refresh_upload_state(self): ...\n def _get_range_header(response): ...\n def initialize_upload(self, http_request, http): ...\n def _last_byte(range_header): ...\n def _validate_chunksize(self, chunksize=None): ...\n def stream_file(self, use_chunks=True): ...\n def _send_media_request(self, request, end): ...\n def _send_chunk(self, start): ...\n\n self._final_response = None\n self._server_chunk_granularity = None\n self._complete = False\n self._mime_type = mime_type\n self._progress = 0\n self._strategy = None\n self._total_size = total_size\n\n _REQUIRED_SERIALIZATION_KEYS = set(('auto_transfer', 'mime_type', 'total_size', 'url'))\n", "repository": "Owen-Gillespie/HuntMaster", "test_name": "test__send_media_body_not_initialized", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000453.py"} {"focal_file": "jgscm/__init__.py", "focal_class": null, "focal_method": "file_exists", "tests": "import unittest\n\nclass Test_file_exists(unittest.TestCase):\n def test_file_exists(self):\n self.assertFalse(self.contents_manager.file_exists(''))\n self.assertFalse(self.contents_manager.file_exists('/'))\n self.assertFalse(self.contents_manager.file_exists(self.BUCKET))\n self.assertFalse(self.contents_manager.file_exists(self.BUCKET))\n bucket = self.bucket\n blob = bucket.blob('test')\n blob.upload_from_string(b'test')\n try:\n self.assertTrue(self.contents_manager.file_exists(self.path('test')))\n self.assertFalse(self.contents_manager.file_exists(self.path('test_')))\n finally:\n blob.delete()\n blob = bucket.blob('test/other')\n blob.upload_from_string(b'test')\n try:\n self.assertFalse(self.contents_manager.file_exists(self.path('test')))\n self.assertFalse(self.contents_manager.file_exists(self.path('test/')))\n self.assertTrue(self.contents_manager.file_exists(self.path('test/other')))\n self.assertFalse(self.contents_manager.file_exists(self.path('test/other/')))\n finally:\n blob.delete()\n", "method_code": " def file_exists(self, path=''):\n if path == '' or path.endswith('/'):\n return False\n if path.startswith('/'):\n path = path[1:]\n bucket_name, bucket_path = self._parse_path(path)\n if not bucket_path:\n return False\n bucket = self._get_bucket(bucket_name)\n if bucket is None or bucket_path == '':\n return False\n return bucket.blob(bucket_path).exists()\n ", "context": "class GoogleStorageContentManager(ContentsManager):\n @debug_args\n def file_exists(self, path=''): ...\n def __init__(self, *args, **kwargs): ...\n def debug_args(fn): ...\n def is_hidden(self, path): ...\n def dir_exists(self, path): ...\n def get(self, path, content=True, type=None, format=None): ...\n def save(self, model, path): ...\n def delete_file(self, path): ...\n def rename_file(self, old_path, new_path): ...\n def client(self): ...\n def run_post_save_hook(self, model, os_path): ...\n def _checkpoints_class_default(self): ...\n def _resolve_storagetype(self, path, storagetype): ...\n def _get_bucket(self, name, throw=False): ...\n def _parse_path(path): ...\n def _get_blob_path(blob): ...\n def _get_blob_name(blob): ...\n def _get_dir_name(path): ...\n def _fetch(self, path, content=True): ...\n def _base_model(self, blob): ...\n def _read_file(self, blob, format): ...\n def _file_model(self, blob, content=True, format=None): ...\n def _read_notebook(self, blob): ...\n def _notebook_model(self, blob, content=True): ...\n def _dir_model(self, path, members, content=True): ...\n def _save_notebook(self, path, nb): ...\n def _save_file(self, path, content, format): ...\n def _save_directory(self, path, model): ...\n\n self._client = None\n\n project = Unicode('', config=True, help='The name of the project in Google Cloud to use. If you do not set this parameter, google.cloud will pick the default project from the execution context if it exists.')\n keyfile = Unicode('', config=True, help='The path to the Google Cloud API JSON keyfile which is needed for authorization. If you do not set this parameter, google.cloud will be OK if the default project exists.')\n max_list_size = Int(128, config=True, help='list_blobs() limit')\n cache_buckets = Bool(True, config=True, help='Value indicating whether to cache the bucket objects for faster operations.')\n hide_dotted_blobs = Bool(True, config=True, help='Consider blobs which names start with dot as hidden.')\n untitled_directory = Unicode('untitled-folder', config=True, help='The base name used when creating untitled directories.')\n default_path = Unicode('', config=True, help='The default path to open.')\n post_save_hook = Any(None, config=True, help='Python callable or importstring thereof\\n\\n to be called on the path of a file just saved.\\n\\n This can be used to process the file on disk,\\n such as converting the notebook to a script or HTML via nbconvert.\\n\\n It will be called as (all arguments passed by keyword)::\\n\\n hook(os_path=path, model=model, contents_manager=instance)\\n\\n - path: the GCS path to the file just written\\n - model: the model representing the file\\n - contents_manager: this ContentsManager instance\\n ')\n debug_args = staticmethod(debug_args)\n", "repository": "src-d/jgscm", "test_name": "test_file_exists", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000454.py"} {"focal_file": "jgscm/__init__.py", "focal_class": null, "focal_method": "dir_exists", "tests": "import unittest\n\nclass Test_dir_exists(unittest.TestCase):\n def test_dir_exists(self):\n self.assertTrue(self.contents_manager.dir_exists(''))\n self.assertTrue(self.contents_manager.dir_exists('/'))\n self.assertTrue(self.contents_manager.dir_exists('/' + self.BUCKET))\n self.assertTrue(self.contents_manager.dir_exists(self.BUCKET))\n self.assertTrue(self.contents_manager.dir_exists('/' + self.BUCKET + '/'))\n self.assertTrue(self.contents_manager.dir_exists(self.BUCKET + '/'))\n self.assertFalse(self.contents_manager.dir_exists(self.BUCKET + '/' + 'test'))\n self.assertFalse(self.contents_manager.dir_exists('/' + self.BUCKET + '/' + 'test'))\n self.assertFalse(self.contents_manager.dir_exists(self.BUCKET + 'blahblah'))\n self.assertFalse(self.contents_manager.dir_exists('/' + self.BUCKET + 'blahblah'))\n bucket = self.bucket\n blob = bucket.blob('test')\n blob.upload_from_string(b'test')\n try:\n self.assertFalse(self.contents_manager.dir_exists(self.path('wtf')))\n self.assertFalse(self.contents_manager.dir_exists(self.path('test')))\n self.assertFalse(self.contents_manager.dir_exists(self.path('test/')))\n finally:\n blob.delete()\n blob = bucket.blob('test/')\n blob.upload_from_string(b'')\n try:\n self.assertTrue(self.contents_manager.dir_exists(self.path('test')))\n self.assertTrue(self.contents_manager.dir_exists(self.path('test/')))\n finally:\n blob.delete()\n blob = bucket.blob('test/other/')\n blob.upload_from_string(b'')\n try:\n self.assertTrue(self.contents_manager.dir_exists(self.path('test')))\n self.assertTrue(self.contents_manager.dir_exists(self.path('test/')))\n self.assertTrue(self.contents_manager.dir_exists(self.path('test/other')))\n self.assertTrue(self.contents_manager.dir_exists(self.path('test/other/')))\n finally:\n blob.delete()\n blob = bucket.blob('test/other')\n blob.upload_from_string(b'data')\n try:\n self.assertTrue(self.contents_manager.dir_exists(self.path('test')))\n self.assertTrue(self.contents_manager.dir_exists(self.path('test/')))\n self.assertFalse(self.contents_manager.dir_exists(self.path('test/other')))\n self.assertFalse(self.contents_manager.dir_exists(self.path('test/other/')))\n finally:\n blob.delete()\n", "method_code": " def dir_exists(self, path):\n if path.startswith('/'):\n path = path[1:]\n if path == '':\n return True\n if not path.endswith('/'):\n path += '/'\n bucket_name, blob_prefix_name = self._parse_path(path)\n bucket = self._get_bucket(bucket_name)\n if not bucket:\n return False\n if not blob_prefix_name:\n return True\n if list(bucket.list_blobs(prefix=blob_prefix_name, max_results=1)):\n return True\n return False\n ", "context": "class GoogleStorageContentManager(ContentsManager):\n @debug_args\n def dir_exists(self, path): ...\n def __init__(self, *args, **kwargs): ...\n def debug_args(fn): ...\n def is_hidden(self, path): ...\n def file_exists(self, path=''): ...\n def get(self, path, content=True, type=None, format=None): ...\n def save(self, model, path): ...\n def delete_file(self, path): ...\n def rename_file(self, old_path, new_path): ...\n def client(self): ...\n def run_post_save_hook(self, model, os_path): ...\n def _checkpoints_class_default(self): ...\n def _resolve_storagetype(self, path, storagetype): ...\n def _get_bucket(self, name, throw=False): ...\n def _parse_path(path): ...\n def _get_blob_path(blob): ...\n def _get_blob_name(blob): ...\n def _get_dir_name(path): ...\n def _fetch(self, path, content=True): ...\n def _base_model(self, blob): ...\n def _read_file(self, blob, format): ...\n def _file_model(self, blob, content=True, format=None): ...\n def _read_notebook(self, blob): ...\n def _notebook_model(self, blob, content=True): ...\n def _dir_model(self, path, members, content=True): ...\n def _save_notebook(self, path, nb): ...\n def _save_file(self, path, content, format): ...\n def _save_directory(self, path, model): ...\n\n self._client = None\n\n project = Unicode('', config=True, help='The name of the project in Google Cloud to use. If you do not set this parameter, google.cloud will pick the default project from the execution context if it exists.')\n keyfile = Unicode('', config=True, help='The path to the Google Cloud API JSON keyfile which is needed for authorization. If you do not set this parameter, google.cloud will be OK if the default project exists.')\n max_list_size = Int(128, config=True, help='list_blobs() limit')\n cache_buckets = Bool(True, config=True, help='Value indicating whether to cache the bucket objects for faster operations.')\n hide_dotted_blobs = Bool(True, config=True, help='Consider blobs which names start with dot as hidden.')\n untitled_directory = Unicode('untitled-folder', config=True, help='The base name used when creating untitled directories.')\n default_path = Unicode('', config=True, help='The default path to open.')\n post_save_hook = Any(None, config=True, help='Python callable or importstring thereof\\n\\n to be called on the path of a file just saved.\\n\\n This can be used to process the file on disk,\\n such as converting the notebook to a script or HTML via nbconvert.\\n\\n It will be called as (all arguments passed by keyword)::\\n\\n hook(os_path=path, model=model, contents_manager=instance)\\n\\n - path: the GCS path to the file just written\\n - model: the model representing the file\\n - contents_manager: this ContentsManager instance\\n ')\n debug_args = staticmethod(debug_args)\n", "repository": "src-d/jgscm", "test_name": "test_dir_exists", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000455.py"} {"focal_file": "jgscm/__init__.py", "focal_class": null, "focal_method": "is_hidden", "tests": "import unittest\n\nclass Test_is_hidden(unittest.TestCase):\n def test_is_hidden(self):\n self.assertFalse(self.contents_manager.is_hidden(self.BUCKET))\n self.assertFalse(self.contents_manager.is_hidden('/' + self.BUCKET))\n self.assertFalse(self.contents_manager.is_hidden(self.BUCKET + '/'))\n self.assertFalse(self.contents_manager.is_hidden('/' + self.BUCKET + '/'))\n self.assertFalse(self.contents_manager.is_hidden(self.path('something')))\n self.assertTrue(self.contents_manager.is_hidden(self.BUCKET + 'blahblah'))\n self.assertTrue(self.contents_manager.is_hidden(self.BUCKET + 'blahblah/test'))\n self.contents_manager.hide_dotted_blobs = True\n self.assertTrue(self.contents_manager.is_hidden(self.path('.test')))\n self.assertTrue(self.contents_manager.is_hidden(self.path('.test/')))\n self.contents_manager.hide_dotted_blobs = False\n self.assertFalse(self.contents_manager.is_hidden(self.path('.test')))\n self.assertFalse(self.contents_manager.is_hidden(self.path('.test/')))\n self.contents_manager.hide_dotted_blobs = True\n self.assertFalse(self.contents_manager.is_hidden(self.path('.test/other')))\n self.contents_manager.hide_dotted_blobs = False\n self.assertFalse(self.contents_manager.is_hidden(self.path('.test/other')))\n self.contents_manager.hide_dotted_blobs = True\n", "method_code": " def is_hidden(self, path):\n if path == '':\n return False\n if path.startswith('/'):\n path = path[1:]\n bucket_name, bucket_path = self._parse_path(path)\n try:\n bucket = self._get_bucket(bucket_name)\n except Forbidden:\n return True\n if bucket is None:\n return True\n if self.hide_dotted_blobs and self._get_blob_name(bucket_path).startswith('.'):\n return True\n return False\n ", "context": "class GoogleStorageContentManager(ContentsManager):\n @debug_args\n def is_hidden(self, path): ...\n def __init__(self, *args, **kwargs): ...\n def debug_args(fn): ...\n def file_exists(self, path=''): ...\n def dir_exists(self, path): ...\n def get(self, path, content=True, type=None, format=None): ...\n def save(self, model, path): ...\n def delete_file(self, path): ...\n def rename_file(self, old_path, new_path): ...\n def client(self): ...\n def run_post_save_hook(self, model, os_path): ...\n def _checkpoints_class_default(self): ...\n def _resolve_storagetype(self, path, storagetype): ...\n def _get_bucket(self, name, throw=False): ...\n def _parse_path(path): ...\n def _get_blob_path(blob): ...\n def _get_blob_name(blob): ...\n def _get_dir_name(path): ...\n def _fetch(self, path, content=True): ...\n def _base_model(self, blob): ...\n def _read_file(self, blob, format): ...\n def _file_model(self, blob, content=True, format=None): ...\n def _read_notebook(self, blob): ...\n def _notebook_model(self, blob, content=True): ...\n def _dir_model(self, path, members, content=True): ...\n def _save_notebook(self, path, nb): ...\n def _save_file(self, path, content, format): ...\n def _save_directory(self, path, model): ...\n\n self._client = None\n\n project = Unicode('', config=True, help='The name of the project in Google Cloud to use. If you do not set this parameter, google.cloud will pick the default project from the execution context if it exists.')\n keyfile = Unicode('', config=True, help='The path to the Google Cloud API JSON keyfile which is needed for authorization. If you do not set this parameter, google.cloud will be OK if the default project exists.')\n max_list_size = Int(128, config=True, help='list_blobs() limit')\n cache_buckets = Bool(True, config=True, help='Value indicating whether to cache the bucket objects for faster operations.')\n hide_dotted_blobs = Bool(True, config=True, help='Consider blobs which names start with dot as hidden.')\n untitled_directory = Unicode('untitled-folder', config=True, help='The base name used when creating untitled directories.')\n default_path = Unicode('', config=True, help='The default path to open.')\n post_save_hook = Any(None, config=True, help='Python callable or importstring thereof\\n\\n to be called on the path of a file just saved.\\n\\n This can be used to process the file on disk,\\n such as converting the notebook to a script or HTML via nbconvert.\\n\\n It will be called as (all arguments passed by keyword)::\\n\\n hook(os_path=path, model=model, contents_manager=instance)\\n\\n - path: the GCS path to the file just written\\n - model: the model representing the file\\n - contents_manager: this ContentsManager instance\\n ')\n debug_args = staticmethod(debug_args)\n", "repository": "src-d/jgscm", "test_name": "test_is_hidden", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000456.py"} {"focal_file": "jgscm/__init__.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_get(self):\n model = self.contents_manager.get('/')\n self.assertEqual(model['type'], 'directory')\n self.assertEqual(model['mimetype'], 'application/x-directory')\n self.assertEqual(model['name'], '')\n self.assertEqual(model['path'], '')\n self.assertEqual(model['last_modified'], '')\n self.assertEqual(model['created'], '')\n self.assertEqual(model['format'], 'json')\n self.assertEqual(model['writable'], True)\n self.assertIsInstance(model['content'], list)\n self.assertGreaterEqual(len(model['content']), 1)\n for m in model['content']:\n self.assertEqual(m['type'], 'directory')\n self.assertEqual(m['mimetype'], 'application/x-directory')\n if m['name'] == self.BUCKET:\n self.assertEqual(m['path'], self.BUCKET)\n self.assertEqual(m['last_modified'], '')\n self.assertEqual(m['created'], '')\n self.assertIsNone(m['format'])\n self.assertIsNone(m['content'])\n self.assertEqual(m['writable'], True)\n model = self.contents_manager.get(self.path(''))\n self.assertEqual(model['type'], 'directory')\n self.assertEqual(model['mimetype'], 'application/x-directory')\n self.assertEqual(model['name'], self.BUCKET)\n self.assertEqual(model['path'], self.BUCKET)\n self.assertEqual(model['last_modified'], '')\n self.assertEqual(model['created'], '')\n self.assertEqual(model['format'], 'json')\n self.assertEqual(model['content'], [])\n self.assertEqual(model['writable'], True)\n model2 = self.contents_manager.get(self.path(''), type='directory')\n self.assertEqual(model, model2)\n with self.assertRaises(web.HTTPError):\n self.contents_manager.get(self.path(''), type='file')\n with self.assertRaises(web.HTTPError):\n self.contents_manager.get(self.path(''), type='notebook')\n bucket = self.bucket\n blob = bucket.blob('test/other.txt')\n blob.upload_from_string(b'contents')\n try:\n model = self.contents_manager.get(self.path('test/other.txt'))\n self.assertIsInstance(model, dict)\n self.assertEqual(model['type'], 'file')\n self.assertEqual(model['mimetype'], 'text/plain')\n self.assertEqual(model['name'], 'other.txt')\n self.assertEqual(model['path'], self.path('test/other.txt')[1:])\n self.assertEqual(model['last_modified'], blob.updated)\n self.assertIsInstance(model['last_modified'], datetime)\n self.assertEqual(model['created'], blob.updated)\n self.assertIsInstance(model['created'], datetime)\n self.assertEqual(model['content'], u'contents')\n self.assertEqual(model['format'], 'text')\n self.assertEqual(model['writable'], True)\n model2 = self.contents_manager.get(self.path('test/other.txt'), type='file')\n self.assertEqual(model, model2)\n with self.assertRaises(web.HTTPError):\n self.contents_manager.get(self.path('test/other.txt'), type='directory')\n with self.assertRaises(nbformat.reader.NotJSONError):\n self.contents_manager.get(self.path('test/other.txt'), type='notebook')\n except:\n blob.delete()\n raise\n model = self.contents_manager.get(self.path(''))\n self.assertEqual(model['type'], 'directory')\n self.assertEqual(model['mimetype'], 'application/x-directory')\n self.assertEqual(model['name'], self.BUCKET)\n self.assertEqual(model['path'], self.BUCKET)\n self.assertEqual(model['last_modified'], '')\n self.assertEqual(model['created'], '')\n self.assertEqual(model['format'], 'json')\n self.assertEqual(model['writable'], True)\n self.assertIsInstance(model['content'], list)\n self.assertEqual(len(model['content']), 1)\n model = model['content'][0]\n self.assertEqual(model['type'], 'directory')\n self.assertEqual(model['mimetype'], 'application/x-directory')\n self.assertEqual(model['name'], 'test')\n self.assertEqual(model['path'], self.path('test')[1:])\n self.assertEqual(model['last_modified'], '')\n self.assertEqual(model['created'], '')\n self.assertIsNone(model['content'])\n self.assertIsNone(model['format'])\n self.assertEqual(model['writable'], True)\n blob2 = bucket.blob('test/fold/another.txt')\n blob2.upload_from_string(b'contents')\n try:\n model = self.contents_manager.get(self.path('test/'))\n self.assertIsInstance(model, dict)\n self.assertEqual(model['type'], 'directory')\n self.assertEqual(model['mimetype'], 'application/x-directory')\n self.assertEqual(model['name'], 'test')\n self.assertEqual(model['path'], self.path('test')[1:])\n self.assertEqual(model['last_modified'], '')\n self.assertEqual(model['created'], '')\n self.assertEqual(model['format'], 'json')\n self.assertEqual(model['writable'], True)\n self.assertIsInstance(model['content'], list)\n self.assertEqual(len(model['content']), 2)\n fc, dc = model['content']\n finally:\n blob.delete()\n blob2.delete()\n self.assertIsInstance(fc, dict)\n self.assertEqual(fc['type'], 'file')\n self.assertEqual(fc['mimetype'], 'text/plain')\n self.assertEqual(fc['name'], 'other.txt')\n self.assertEqual(fc['path'], self.path('test/other.txt')[1:])\n self.assertIsNone(fc['content'])\n self.assertIsNone(fc['format'])\n self.assertEqual(fc['last_modified'], blob.updated)\n self.assertIsInstance(fc['last_modified'], datetime)\n self.assertEqual(fc['created'], blob.updated)\n self.assertIsInstance(fc['created'], datetime)\n self.assertIsInstance(dc, dict)\n self.assertEqual(dc['type'], 'directory')\n self.assertEqual(dc['mimetype'], 'application/x-directory')\n self.assertEqual(dc['name'], 'fold')\n self.assertEqual(dc['path'], self.path('test/fold')[1:])\n self.assertIsNone(dc['content'])\n self.assertIsNone(dc['format'])\n self.assertEqual(dc['last_modified'], '')\n self.assertEqual(dc['created'], '')\n", "method_code": " def get(self, path, content=True, type=None, format=None):\n if isinstance(path, Blob):\n obj = path\n path = self._get_blob_path(obj)\n elif path.startswith('/'):\n path = path[1:]\n if not path:\n path = self.default_path\n type = self._resolve_storagetype(path, type)\n if type == 'directory':\n if path and (not path.endswith('/')):\n path += '/'\n exists, members = self._fetch(path, content=content)\n if not exists:\n raise web.HTTPError(404, u'No such directory: %s' % path)\n model = self._dir_model(path, members, content=content)\n else:\n exists, blob = self._fetch(path)\n if not exists:\n raise web.HTTPError(404, u'No such file: %s' % path)\n if type == 'notebook' or (type is None and path.endswith('.ipynb')):\n model = self._notebook_model(blob, content=content)\n else:\n model = self._file_model(blob, content=content, format=format)\n return model\n ", "context": "class GoogleStorageContentManager(ContentsManager):\n @debug_args\n def get(self, path, content=True, type=None, format=None): ...\n def __init__(self, *args, **kwargs): ...\n def debug_args(fn): ...\n def is_hidden(self, path): ...\n def file_exists(self, path=''): ...\n def dir_exists(self, path): ...\n def save(self, model, path): ...\n def delete_file(self, path): ...\n def rename_file(self, old_path, new_path): ...\n def client(self): ...\n def run_post_save_hook(self, model, os_path): ...\n def _checkpoints_class_default(self): ...\n def _resolve_storagetype(self, path, storagetype): ...\n def _get_bucket(self, name, throw=False): ...\n def _parse_path(path): ...\n def _get_blob_path(blob): ...\n def _get_blob_name(blob): ...\n def _get_dir_name(path): ...\n def _fetch(self, path, content=True): ...\n def _base_model(self, blob): ...\n def _read_file(self, blob, format): ...\n def _file_model(self, blob, content=True, format=None): ...\n def _read_notebook(self, blob): ...\n def _notebook_model(self, blob, content=True): ...\n def _dir_model(self, path, members, content=True): ...\n def _save_notebook(self, path, nb): ...\n def _save_file(self, path, content, format): ...\n def _save_directory(self, path, model): ...\n\n self._client = None\n\n project = Unicode('', config=True, help='The name of the project in Google Cloud to use. If you do not set this parameter, google.cloud will pick the default project from the execution context if it exists.')\n keyfile = Unicode('', config=True, help='The path to the Google Cloud API JSON keyfile which is needed for authorization. If you do not set this parameter, google.cloud will be OK if the default project exists.')\n max_list_size = Int(128, config=True, help='list_blobs() limit')\n cache_buckets = Bool(True, config=True, help='Value indicating whether to cache the bucket objects for faster operations.')\n hide_dotted_blobs = Bool(True, config=True, help='Consider blobs which names start with dot as hidden.')\n untitled_directory = Unicode('untitled-folder', config=True, help='The base name used when creating untitled directories.')\n default_path = Unicode('', config=True, help='The default path to open.')\n post_save_hook = Any(None, config=True, help='Python callable or importstring thereof\\n\\n to be called on the path of a file just saved.\\n\\n This can be used to process the file on disk,\\n such as converting the notebook to a script or HTML via nbconvert.\\n\\n It will be called as (all arguments passed by keyword)::\\n\\n hook(os_path=path, model=model, contents_manager=instance)\\n\\n - path: the GCS path to the file just written\\n - model: the model representing the file\\n - contents_manager: this ContentsManager instance\\n ')\n debug_args = staticmethod(debug_args)\n", "repository": "src-d/jgscm", "test_name": "test_get", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000457.py"} {"focal_file": "jgscm/__init__.py", "focal_class": null, "focal_method": "delete_file", "tests": "import unittest\n\nclass Test_delete_file(unittest.TestCase):\n def test_delete_file(self):\n bucket = self.bucket\n blob = bucket.blob('test/other.txt')\n blob.upload_from_string(b'contents')\n try:\n self.contents_manager.delete_file(self.path('test/other.txt'))\n self.assertFalse(blob.exists())\n except:\n blob.delete()\n raise\n self.contents_manager.delete_file(self.BUCKET)\n self.assertFalse(bucket.exists())\n bucket.create()\n blob = bucket.blob('test/other/')\n blob.upload_from_string(b'contents')\n try:\n self.contents_manager.delete_file(self.path('test/other/'))\n self.assertFalse(blob.exists())\n self.assertFalse(bucket.blob('test/').exists())\n except:\n blob.delete()\n raise\n blob1 = bucket.blob('test/other.txt')\n blob1.upload_from_string(b'contents')\n blob2 = bucket.blob('test/next/another.txt')\n blob2.upload_from_string(b'contents')\n try:\n self.contents_manager.delete_file(self.path('test/'))\n self.assertFalse(blob1.exists())\n self.assertFalse(blob2.exists())\n self.assertFalse(bucket.blob('test/').exists())\n except:\n try:\n blob1.delete()\n finally:\n blob2.delete()\n raise\n", "method_code": " def delete_file(self, path):\n if path.startswith('/'):\n path = path[1:]\n bucket_name, bucket_path = self._parse_path(path)\n bucket = self._get_bucket(bucket_name, throw=True)\n if bucket_path == '':\n bucket.delete()\n del self._bucket_cache[bucket_name]\n return\n it = bucket.list_blobs(prefix=bucket_path, delimiter='/', max_results=self.max_list_size)\n files = list(islice(it, self.max_list_size))\n folders = it.prefixes\n bucket.delete_blobs(files)\n for folder in folders:\n self.delete_file(bucket_name + '/' + folder)\n ", "context": "class GoogleStorageContentManager(ContentsManager):\n @debug_args\n def delete_file(self, path): ...\n def __init__(self, *args, **kwargs): ...\n def debug_args(fn): ...\n def is_hidden(self, path): ...\n def file_exists(self, path=''): ...\n def dir_exists(self, path): ...\n def get(self, path, content=True, type=None, format=None): ...\n def save(self, model, path): ...\n def rename_file(self, old_path, new_path): ...\n def client(self): ...\n def run_post_save_hook(self, model, os_path): ...\n def _checkpoints_class_default(self): ...\n def _resolve_storagetype(self, path, storagetype): ...\n def _get_bucket(self, name, throw=False): ...\n def _parse_path(path): ...\n def _get_blob_path(blob): ...\n def _get_blob_name(blob): ...\n def _get_dir_name(path): ...\n def _fetch(self, path, content=True): ...\n def _base_model(self, blob): ...\n def _read_file(self, blob, format): ...\n def _file_model(self, blob, content=True, format=None): ...\n def _read_notebook(self, blob): ...\n def _notebook_model(self, blob, content=True): ...\n def _dir_model(self, path, members, content=True): ...\n def _save_notebook(self, path, nb): ...\n def _save_file(self, path, content, format): ...\n def _save_directory(self, path, model): ...\n\n self._client = None\n\n project = Unicode('', config=True, help='The name of the project in Google Cloud to use. If you do not set this parameter, google.cloud will pick the default project from the execution context if it exists.')\n keyfile = Unicode('', config=True, help='The path to the Google Cloud API JSON keyfile which is needed for authorization. If you do not set this parameter, google.cloud will be OK if the default project exists.')\n max_list_size = Int(128, config=True, help='list_blobs() limit')\n cache_buckets = Bool(True, config=True, help='Value indicating whether to cache the bucket objects for faster operations.')\n hide_dotted_blobs = Bool(True, config=True, help='Consider blobs which names start with dot as hidden.')\n untitled_directory = Unicode('untitled-folder', config=True, help='The base name used when creating untitled directories.')\n default_path = Unicode('', config=True, help='The default path to open.')\n post_save_hook = Any(None, config=True, help='Python callable or importstring thereof\\n\\n to be called on the path of a file just saved.\\n\\n This can be used to process the file on disk,\\n such as converting the notebook to a script or HTML via nbconvert.\\n\\n It will be called as (all arguments passed by keyword)::\\n\\n hook(os_path=path, model=model, contents_manager=instance)\\n\\n - path: the GCS path to the file just written\\n - model: the model representing the file\\n - contents_manager: this ContentsManager instance\\n ')\n debug_args = staticmethod(debug_args)\n", "repository": "src-d/jgscm", "test_name": "test_delete_file", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000458.py"} {"focal_file": "jgscm/__init__.py", "focal_class": null, "focal_method": "rename_file", "tests": "import unittest\n\nclass Test_rename_file(unittest.TestCase):\n def test_rename_file(self):\n bucket = self.bucket\n blob = bucket.blob('test/other.txt')\n blob.upload_from_string(b'contents')\n try:\n self.contents_manager.rename_file(self.path('test/other.txt'), self.path('test1/other1.txt'))\n self.assertFalse(blob.exists())\n except:\n blob.delete()\n raise\n blob = bucket.blob('test1/other1.txt')\n self.assertTrue(blob.exists())\n blob.delete()\n blob1 = bucket.blob('test/other.txt')\n blob1.upload_from_string(b'contents')\n blob2 = bucket.blob('test/other1.txt')\n blob2.upload_from_string(b'contents')\n try:\n self.contents_manager.rename_file(self.path('test/'), self.path('test1/'))\n self.assertFalse(blob1.exists())\n self.assertFalse(blob2.exists())\n except:\n try:\n blob1.delete()\n finally:\n blob2.delete()\n raise\n blob = bucket.blob('test1/other.txt')\n self.assertTrue(blob.exists())\n blob.delete()\n blob = bucket.blob('test1/other1.txt')\n self.assertTrue(blob.exists())\n blob.delete()\n blob = bucket.blob('test/dir/other.txt')\n blob.upload_from_string(b'contents')\n try:\n self.contents_manager.rename_file(self.path('test/'), self.path('test1/'))\n self.assertFalse(blob.exists())\n except:\n blob.delete()\n raise\n blob = bucket.blob('test1/dir/other.txt')\n self.assertTrue(blob.exists())\n new_bucket = self.contents_manager.client.bucket('jgscm-%s-new' % uuid.uuid4())\n new_bucket.create()\n try:\n self.contents_manager.rename_file(self.path('test1/'), new_bucket.name + '/' + 'test/')\n self.assertFalse(blob.exists())\n except:\n blob.delete()\n new_bucket.delete(force=True)\n raise\n try:\n self.assertTrue(new_bucket.blob('test/dir/other.txt').exists())\n finally:\n new_bucket.delete(force=True)\n", "method_code": " def rename_file(self, old_path, new_path):\n if old_path.startswith('/'):\n old_path = old_path[1:]\n if new_path.startswith('/'):\n new_path = new_path[1:]\n old_bucket_name, old_bucket_path = self._parse_path(old_path)\n old_bucket = self._get_bucket(old_bucket_name, throw=True)\n new_bucket_name, new_bucket_path = self._parse_path(new_path)\n new_bucket = self._get_bucket(new_bucket_name, throw=True)\n old_blob = old_bucket.get_blob(old_bucket_path)\n if old_bucket_name == new_bucket_name:\n if old_blob is not None:\n old_bucket.rename_blob(old_blob, new_bucket_path)\n return\n if not old_bucket_path.endswith('/'):\n old_bucket_path += '/'\n if not new_bucket_path.endswith('/'):\n new_bucket_path += '/'\n it = old_bucket.list_blobs(prefix=old_bucket_path, delimiter='/', max_results=self.max_list_size)\n old_blobs = list(islice(it, self.max_list_size))\n folders = it.prefixes\n for ob in old_blobs:\n old_bucket.rename_blob(ob, new_bucket_path + self._get_blob_name(ob))\n for f in folders:\n self.rename_file(old_bucket_name + '/' + f, new_bucket_name + '/' + f.replace(old_bucket_path, new_bucket_path, 1))\n return\n if old_blob is not None:\n old_bucket.copy_blob(old_blob, new_bucket, new_bucket_path)\n old_bucket.delete_blob(old_blob)\n return\n if not old_bucket_path.endswith('/'):\n old_bucket_path += '/'\n if not new_bucket_path.endswith('/'):\n new_bucket_path += '/'\n it = old_bucket.list_blobs(prefix=old_bucket_path, delimiter='/', max_results=self.max_list_size)\n old_blobs = list(islice(it, self.max_list_size))\n folders = it.prefixes\n for ob in old_blobs:\n old_bucket.copy_blob(ob, new_bucket, new_bucket_path + self._get_blob_name(ob))\n ob.delete()\n for f in folders:\n self.rename_file(old_bucket_name + '/' + f, new_bucket_name + '/' + f.replace(old_bucket_path, new_bucket_path, 1))\n ", "context": "class GoogleStorageContentManager(ContentsManager):\n @debug_args\n def rename_file(self, old_path, new_path): ...\n def __init__(self, *args, **kwargs): ...\n def debug_args(fn): ...\n def is_hidden(self, path): ...\n def file_exists(self, path=''): ...\n def dir_exists(self, path): ...\n def get(self, path, content=True, type=None, format=None): ...\n def save(self, model, path): ...\n def delete_file(self, path): ...\n def client(self): ...\n def run_post_save_hook(self, model, os_path): ...\n def _checkpoints_class_default(self): ...\n def _resolve_storagetype(self, path, storagetype): ...\n def _get_bucket(self, name, throw=False): ...\n def _parse_path(path): ...\n def _get_blob_path(blob): ...\n def _get_blob_name(blob): ...\n def _get_dir_name(path): ...\n def _fetch(self, path, content=True): ...\n def _base_model(self, blob): ...\n def _read_file(self, blob, format): ...\n def _file_model(self, blob, content=True, format=None): ...\n def _read_notebook(self, blob): ...\n def _notebook_model(self, blob, content=True): ...\n def _dir_model(self, path, members, content=True): ...\n def _save_notebook(self, path, nb): ...\n def _save_file(self, path, content, format): ...\n def _save_directory(self, path, model): ...\n\n self._client = None\n\n project = Unicode('', config=True, help='The name of the project in Google Cloud to use. If you do not set this parameter, google.cloud will pick the default project from the execution context if it exists.')\n keyfile = Unicode('', config=True, help='The path to the Google Cloud API JSON keyfile which is needed for authorization. If you do not set this parameter, google.cloud will be OK if the default project exists.')\n max_list_size = Int(128, config=True, help='list_blobs() limit')\n cache_buckets = Bool(True, config=True, help='Value indicating whether to cache the bucket objects for faster operations.')\n hide_dotted_blobs = Bool(True, config=True, help='Consider blobs which names start with dot as hidden.')\n untitled_directory = Unicode('untitled-folder', config=True, help='The base name used when creating untitled directories.')\n default_path = Unicode('', config=True, help='The default path to open.')\n post_save_hook = Any(None, config=True, help='Python callable or importstring thereof\\n\\n to be called on the path of a file just saved.\\n\\n This can be used to process the file on disk,\\n such as converting the notebook to a script or HTML via nbconvert.\\n\\n It will be called as (all arguments passed by keyword)::\\n\\n hook(os_path=path, model=model, contents_manager=instance)\\n\\n - path: the GCS path to the file just written\\n - model: the model representing the file\\n - contents_manager: this ContentsManager instance\\n ')\n debug_args = staticmethod(debug_args)\n", "repository": "src-d/jgscm", "test_name": "test_rename_file", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000459.py"} {"focal_file": "mklabels/main.py", "focal_class": null, "focal_method": "render", "tests": "import unittest\n\nclass Test_render(unittest.TestCase):\n def test_render(self):\n render(['one'], 15, 261, 174, 2, 1)\n with self.assertRaises(TooManyLabels):\n render(['one', 'two'], 15, 261, 174, 2, 1)\n", "method_code": "def render(labels, margin, width, height, marker_length, marker_sep, debug, style, font_size):\n rows, columns = layout(PAPER_WIDTH_MM, PAPER_HEIGHT_MM, margin, width, height, marker_length, marker_sep)\n if len(labels) > rows * columns:\n raise TooManyLabels('Cannot fit this many labels on the page')\n tex = dedent('\\n \\\\documentclass{standalone}\\n \\\\usepackage[utf8]{inputenc}\\n \\\\usepackage[T1]{fontenc}\\n\\n \\\\usepackage{tikz}\\n \\\\usetikzlibrary{calc}\\n \\\\tikzset{x=1mm,y=1mm}\\n \\\\pgfmathsetmacro{\\\\margin}{%(margin)d}\\n \\\\pgfmathsetmacro{\\\\markerlength}{%(marker_length)d}\\n \\\\pgfmathsetmacro{\\\\markersep}{%(marker_sep)d}\\n \\\\pgfmathsetmacro{\\\\labelwidth}{%(width)d}\\n \\\\pgfmathsetmacro{\\\\labelheight}{%(height)d}\\n\\n \\\\begin{document}\\n \\\\begin{tikzpicture}\\n \\\\useasboundingbox (0,0) rectangle (%(page_width)d,%(page_height)d);\\n ') % {'margin': margin, 'marker_length': marker_length, 'marker_sep': marker_sep, 'width': width, 'height': height, 'page_width': PAPER_WIDTH_MM, 'page_height': PAPER_HEIGHT_MM}\n x = 0\n y = 0\n for label in labels:\n tex += dedent('\\n \\\\pgfmathsetmacro{\\\\xpos}{\\\\margin + %(x)d * (\\n \\\\labelwidth + 2 * \\\\markerlength + 2 * \\\\markersep)};\\n \\\\pgfmathsetmacro{\\\\ypos}{\\\\margin + %(y)d * (\\n \\\\labelheight + 2 * \\\\markerlength + 2 * \\\\markersep)};\\n\\n %(debug)s\\\\draw[red] (\\\\xpos,\\\\ypos) rectangle\\n %(debug)s +(\\\\labelwidth,\\\\labelheight);\\n %(debug)s\\\\draw[blue] ($(\\\\xpos,\\\\ypos + 1/2 * \\\\labelheight)$) --\\n %(debug)s +(\\\\labelwidth,0);\\n\\n ') % {'x': x, 'y': y, 'debug': '' if debug else '%'}\n if style == 'default':\n tex += dedent('\\n \\\\draw (\\\\xpos,\\\\ypos) ++(0,-\\\\markersep) -- ++(0,-\\\\markerlength);\\n \\\\draw (\\\\xpos,\\\\ypos) ++(-\\\\markersep,0) -- ++(-\\\\markerlength,0);\\n\\n \\\\draw ($(\\\\xpos,\\\\ypos + \\\\labelheight)$) ++(0,\\\\markersep) --\\n ++(0,\\\\markerlength);\\n \\\\draw ($(\\\\xpos,\\\\ypos + \\\\labelheight)$) ++(-\\\\markersep,0) --\\n ++(-\\\\markerlength,0);\\n\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos)$) ++(0,-\\\\markersep) --\\n ++(0,-\\\\markerlength);\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos)$) ++(\\\\markersep,0) --\\n ++(\\\\markerlength,0);\\n\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos + \\\\labelheight)$)\\n ++(0,\\\\markersep) -- ++(0,\\\\markerlength);\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos + \\\\labelheight)$)\\n ++(\\\\markersep,0) -- ++(\\\\markerlength,0);\\n ')\n else:\n tex += dedent('\\n \\\\draw (\\\\xpos,\\\\ypos) -- ++(0,-\\\\markersep) --\\n ++(0,-\\\\markerlength);\\n \\\\draw (\\\\xpos,\\\\ypos) -- ++(-\\\\markersep,0) --\\n ++(-\\\\markerlength,0);\\n \\\\draw (\\\\xpos,\\\\ypos)\\n ++(0,\\\\markerlength) arc (90:360:\\\\markerlength);\\n\\n \\\\draw ($(\\\\xpos,\\\\ypos + \\\\labelheight)$) -- ++(0,\\\\markersep) --\\n ++(0,\\\\markerlength);\\n \\\\draw ($(\\\\xpos,\\\\ypos + \\\\labelheight)$) -- ++(-\\\\markersep,0) --\\n ++(-\\\\markerlength,0);\\n \\\\draw ($(\\\\xpos,\\\\ypos + \\\\labelheight)$)\\n ++(\\\\markerlength,0) arc (0:270:\\\\markerlength);\\n\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos)$) -- ++(0,-\\\\markersep) --\\n ++(0,-\\\\markerlength);\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos)$) -- ++(\\\\markersep,0) --\\n ++(\\\\markerlength,0);\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos)$)\\n ++(-\\\\markerlength,0) arc (-180:90:\\\\markerlength);\\n\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos + \\\\labelheight)$) --\\n ++(0,\\\\markersep) -- ++(0,\\\\markerlength);\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos + \\\\labelheight)$) --\\n ++(\\\\markersep,0) -- ++(\\\\markerlength,0);\\n \\\\draw ($(\\\\xpos + \\\\labelwidth,\\\\ypos + \\\\labelheight)$)\\n ++(-\\\\markerlength,0) arc (180:-90:\\\\markerlength);\\n ')\n tex += dedent('\\n \\\\node[font=\\\\sffamily\\\\%(font_size)s] at\\n ($(\\\\xpos + 1/2 * \\\\labelwidth, \\\\ypos + 1/2 * \\\\labelheight)$)\\n {\\\\strut %(label)s};\\n ') % {'font_size': font_size, 'label': quote_latex(label)}\n if x + 1 < columns:\n x += 1\n else:\n x = 0\n y += 1\n tex += dedent('\\n \\\\end{tikzpicture}\\n \\\\end{document}\\n ')\n return tex", "context": "def render(labels, margin, width, height, marker_length, marker_sep, debug, style, font_size): ...\ndef quote_latex(s): ...\ndef layout(page_width, page_height, margin, label_width, label_height, marker_length, marker_sep): ...\ndef render(labels, margin, width, height, marker_length, marker_sep, debug, style, font_size): ...\ndef compile_pdf(latex): ...\ndef parse_args(): ...\ndef run(): ...\n", "repository": "pb-/mklabels", "test_name": "test_render", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000460.py"} {"focal_file": "assemblyline/assemblyline/lib/assemble/trim.py", "focal_class": null, "focal_method": "trim_graph", "tests": "import unittest\n\nclass Test_trim_graph(unittest.TestCase):\n def test_trim_utr(self):\n transcripts = read_first_locus('trim_utr1.gtf', score_attr='FPKM')\n GG = get_transcript_graphs(transcripts)\n G, tmap = GG[POS_STRAND]\n trim_nodes = trim_graph(G, POS_STRAND, min_trim_length=0, trim_utr_fraction=0.009, trim_intron_fraction=0.0)\n correct = set()\n self.assertTrue(trim_nodes == correct)\n trim_nodes = trim_graph(G, POS_STRAND, min_trim_length=0, trim_utr_fraction=0.015, trim_intron_fraction=0.0)\n correct = set([Exon(1000, 1100)])\n self.assertTrue(trim_nodes == correct)\n trim_nodes = trim_graph(G, POS_STRAND, min_trim_length=0, trim_utr_fraction=0.11, trim_intron_fraction=0.0)\n correct = set([Exon(1000, 1100), Exon(1100, 1200)])\n self.assertTrue(trim_nodes == correct)\n trim_nodes = trim_graph(G, POS_STRAND, min_trim_length=0, trim_utr_fraction=0.26, trim_intron_fraction=0.0)\n correct = set([Exon(1000, 1100), Exon(1100, 1200), Exon(1200, 1300)])\n self.assertTrue(trim_nodes == correct)\n trim_nodes = trim_graph(G, POS_STRAND, min_trim_length=0, trim_utr_fraction=1.0, trim_intron_fraction=0.0)\n correct = set([Exon(1000, 1100), Exon(1100, 1200), Exon(1200, 1300)])\n self.assertTrue(trim_nodes == correct)\n for t in transcripts:\n t.strand = NEG_STRAND\n GG = get_transcript_graphs(transcripts)\n G, tmap = GG[NEG_STRAND]\n trim_nodes = trim_graph(G, NEG_STRAND, min_trim_length=0, trim_utr_fraction=0.009, trim_intron_fraction=0.0)\n correct = set()\n self.assertTrue(trim_nodes == correct)\n trim_nodes = trim_graph(G, NEG_STRAND, min_trim_length=0, trim_utr_fraction=0.015, trim_intron_fraction=0.0)\n correct = set([Exon(1000, 1100)])\n self.assertTrue(trim_nodes == correct)\n trim_nodes = trim_graph(G, NEG_STRAND, min_trim_length=0, trim_utr_fraction=0.11, trim_intron_fraction=0.0)\n correct = set([Exon(1000, 1100), Exon(1100, 1200)])\n self.assertTrue(trim_nodes == correct)\n trim_nodes = trim_graph(G, NEG_STRAND, min_trim_length=0, trim_utr_fraction=0.26, trim_intron_fraction=0.0)\n correct = set([Exon(1000, 1100), Exon(1100, 1200), Exon(1200, 1300)])\n self.assertTrue(trim_nodes == correct)\n trim_nodes = trim_graph(G, NEG_STRAND, min_trim_length=0, trim_utr_fraction=1.0, trim_intron_fraction=0.0)\n correct = set([Exon(1000, 1100), Exon(1100, 1200), Exon(1200, 1300)])\n self.assertTrue(trim_nodes == correct)\n", "method_code": "def trim_graph(G, strand, min_trim_length, trim_utr_fraction, trim_intron_fraction):\n node_chain_map, chains = get_chains(G, introns=False)\n successor_dict = {}\n for n, nbrdict in G.adjacency_iter():\n successor_dict[n] = nbrdict.keys()\n predecessor_dict = {}\n G.reverse(copy=False)\n for n, nbrdict in G.adjacency_iter():\n predecessor_dict[n] = nbrdict.keys()\n G.reverse(copy=False)\n introns = {}\n intron_tree = IntervalTree()\n reverse = strand == NEG_STRAND\n for u, nbrdict in G.adjacency_iter():\n for v in nbrdict:\n if reverse:\n left, right = (v, u)\n else:\n left, right = (u, v)\n if left.end == right.start:\n continue\n u_chain_nodes = chains[node_chain_map[u]]\n u_score = max((G.node[n][NODE_SCORE] for n in u_chain_nodes))\n v_chain_nodes = chains[node_chain_map[v]]\n v_score = max((G.node[n][NODE_SCORE] for n in v_chain_nodes))\n introns[left.end, right.start] = (u_score, v_score)\n intron_tree.insert_interval(Interval(left.end, right.start, value=(u_score, v_score)))\n all_trim_nodes = set()\n for parent, nodes in chains.iteritems():\n if strand == NEG_STRAND:\n nodes.reverse()\n in_degree = len(predecessor_dict[nodes[0]])\n out_degree = len(successor_dict[nodes[-1]])\n trim_nodes = set()\n if in_degree == 1 and out_degree == 1 and ((parent.start, parent.end) in introns):\n pred_score, succ_score = introns[parent.start, parent.end]\n cutoff_score = trim_intron_fraction * max(pred_score, succ_score)\n trim_nodes.update(trim_intron(G, nodes, cutoff_score))\n else:\n found_intron = False\n max_pred_score = 0.0\n max_succ_score = 0.0\n for hit in intron_tree.find(parent.start, parent.end):\n if hit.start > parent.start and hit.end < parent.end:\n continue\n found_intron = True\n pred_score, succ_score = hit.value\n if pred_score > max_pred_score:\n max_pred_score = pred_score\n if succ_score > max_succ_score:\n max_succ_score = succ_score\n if in_degree == 0 and out_degree == 0:\n if found_intron:\n cutoff_score = trim_intron_fraction * max(max_pred_score, max_succ_score)\n trim_nodes.update(trim_intron(G, nodes, cutoff_score))\n trim_nodes.update(trim_bidirectional(G, nodes, min_trim_length, trim_utr_fraction))\n elif in_degree == 0:\n if found_intron:\n cutoff_score = trim_intron_fraction * max_succ_score\n trim_nodes.update(trim_intronic_utr(G, nodes, cutoff_score))\n trim_nodes.update(trim_utr(G, nodes[::-1], min_trim_length, trim_utr_fraction))\n elif out_degree == 0:\n if found_intron:\n cutoff_score = trim_intron_fraction * max_pred_score\n trim_nodes.update(trim_intronic_utr(G, nodes[::-1], cutoff_score))\n trim_nodes.update(trim_utr(G, nodes, min_trim_length, trim_utr_fraction))\n all_trim_nodes.update(trim_nodes)\n if len(all_trim_nodes) > 0:\n logging.debug('\\t\\t(%s) trimmed %d/%d nodes from graph' % (strand_int_to_str(strand), len(all_trim_nodes), len(G)))\n return all_trim_nodes", "context": "def trim_graph(G, strand, min_trim_length, trim_utr_fraction, trim_intron_fraction): ...\ndef trim_intron(G, nodes, cutoff_score): ...\ndef trim_intronic_utr(G, nodes, cutoff_score): ...\ndef trim_bidirectional(G, nodes, min_trim_length, coverage_fraction): ...\ndef trim_utr(G, nodes, min_trim_length, coverage_fraction): ...\ndef trim_graph(G, strand, min_trim_length, trim_utr_fraction, trim_intron_fraction): ...\n", "repository": "lijiangbioinfo/assemblyline", "test_name": "test_trim_utr", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000461.py"} {"focal_file": "test/ekf_test.py", "focal_class": null, "focal_method": "pred_jacobians", "tests": "import unittest\n\nclass Test_pred_jacobians(unittest.TestCase):\n def test_state_jacobians(self):\n self.assertLess(pred_jacobians(), 1e-07)\n", "method_code": "def pred_jacobians():\n x_prev = np.zeros([17], dtype=np.float32)\n x_prev[3] = 2.0\n Jnumerical = nd.Jacobian(pred_state)(x_prev)\n diRo = np.array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -dt, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -dt]], dtype=np.float32)\n dbacc = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]], dtype=np.float32)\n diRim1 = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -dt, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -dt, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -dt]], dtype=np.float32)\n dbgy = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=np.float32)\n fkstat = np.concatenate((diRo, dbacc, diRim1, dbgy), axis=0)\n pred_rot_euler = dt * imu_meas[0:3] - dt * x_prev[14:17]\n pred_rot = euler2rot(pred_rot_euler)\n pred_global_euler = dt * imu_meas[1:3] - dt * x_prev[15:17] + x_prev[6:8]\n pred_global_rot = euler2rot2param(pred_global_euler)\n g = -9.80665\n dRglobal_dE = np.concatenate((np.zeros([3, 1], dtype=np.float32), getLittleJacobian(pred_global_euler)), axis=-1)\n dpi = np.concatenate((np.zeros([3, 3], dtype=np.float32), dt * pred_rot, 0.5 * dt * dt * g * getLittleJacobian(pred_global_euler), -0.5 * dt * dt * np.eye(3, dtype=np.float32), np.zeros([3, 3], dtype=np.float32), -dt * getJacobian(pred_rot_euler, dt * x_prev[3:6]) - g * 0.5 * dt * dt * dt * dRglobal_dE), axis=-1)\n dvi = np.concatenate([tf.zeros([3, 3]), pred_rot, dt * g * getLittleJacobian(pred_global_euler), -dt * np.eye(3, dtype=np.float32), np.zeros([3, 3], dtype=np.float32), -dt * getJacobian(pred_rot_euler, x_prev[3:6]) + -g * dt * dt * dRglobal_dE], axis=-1)\n Janalytical = np.concatenate((dpi, dvi, fkstat), axis=0)\n error = Janalytical - Jnumerical\n return np.linalg.norm(error)", "context": "def pred_jacobians(): ...\ndef skew(x): ...\ndef euler2rot(eulers): ...\ndef euler2rot2param(eulers): ...\ndef getJacobian(eulers, pt): ...\ndef getLittleJacobian(eulers): ...\ndef pred_state(x): ...\ndef pred_state_with_noise(x, n): ...\ndef no_movement_sample_data(): ...\ndef ekf_update(): ...\ndef pred_jacobians(): ...\ndef noise_jacobians(): ...\n", "repository": "lichunshang/end_to_end_odometry", "test_name": "test_state_jacobians", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000462.py"} {"focal_file": "test/ekf_test.py", "focal_class": null, "focal_method": "noise_jacobians", "tests": "import unittest\n\nclass Test_noise_jacobians(unittest.TestCase):\n def test_noise_jacobians(self):\n self.assertLess(noise_jacobians(), 1e-07)\n", "method_code": "def noise_jacobians():\n x_prev = np.zeros([17], dtype=np.float32)\n x_prev[3] = 2.0\n eta = np.zeros([12], dtype=np.float32)\n func = lambda n: pred_state_with_noise(x_prev, n)\n Jnumerical = nd.Jacobian(func)(eta)\n pred_rot_euler = dt * imu_meas[0:3] - dt * x_prev[14:17] - dt * eta[0:3]\n pred_rot = euler2rot(pred_rot_euler)\n pred_global_euler = dt * imu_meas[1:3] - dt * x_prev[15:17] - dt * eta[1:3] + x_prev[6:8]\n pred_global_rot = euler2rot2param(pred_global_euler)\n reuse = np.concatenate((np.zeros([3, 1], dtype=np.float32), getLittleJacobian(pred_global_euler)), axis=-1)\n dpi = np.concatenate((getJacobian(pred_rot_euler, dt * x_prev[3:6]) * -dt + 0.5 * dt * dt * (-dt * g * reuse), -0.5 * dt * dt * np.eye(3, dtype=np.float32), np.zeros([3, 3], dtype=np.float32), np.zeros([3, 3], dtype=np.float32)), axis=-1)\n dvi = np.concatenate((getJacobian(pred_rot_euler, x_prev[3:6]) * -dt + dt * (-dt * g * reuse), -dt * np.eye(3, dtype=np.float32), np.zeros([3, 3], dtype=np.float32), np.zeros([3, 3], dtype=np.float32)), axis=-1)\n drotglobal = np.array([[0, -dt, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, -dt, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.float32)\n daccbias = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=np.float32)\n drotrel = np.array([[-dt, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -dt, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, -dt, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.float32)\n dgyrobias = np.array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]], dtype=np.float32)\n Janalytical = np.concatenate((dpi, dvi, drotglobal, daccbias, drotrel, dgyrobias), axis=0)\n squared = np.dot(Janalytical, np.transpose(Janalytical))\n error = Janalytical - Jnumerical\n return np.linalg.norm(error)", "context": "def noise_jacobians(): ...\ndef skew(x): ...\ndef euler2rot(eulers): ...\ndef euler2rot2param(eulers): ...\ndef getJacobian(eulers, pt): ...\ndef getLittleJacobian(eulers): ...\ndef pred_state(x): ...\ndef pred_state_with_noise(x, n): ...\ndef no_movement_sample_data(): ...\ndef ekf_update(): ...\ndef pred_jacobians(): ...\ndef noise_jacobians(): ...\n", "repository": "lichunshang/end_to_end_odometry", "test_name": "test_noise_jacobians", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000463.py"} {"focal_file": "geonetworkx/geometry_operations.py", "focal_class": null, "focal_method": "discretize_lines", "tests": "import unittest\n\nclass Test_discretize_lines(unittest.TestCase):\n def test_discretize_lines(self):\n nb_lines = 20\n lines = []\n for l in range(nb_lines):\n line_nb_points = np.random.randint(5, 30)\n points = np.random.rand(line_nb_points, 2)\n lines.append(LineString(points))\n discretized_points, points_line_association = discretize_lines(lines, 0.1)\n for l in points_line_association:\n line = lines[l]\n for p in points_line_association[l]:\n point = discretized_points[p]\n assert_almost_intersect(point, line, 'A discretized point does not intersects its given line')\n", "method_code": "def discretize_lines(lines: Iterable[LineString], discretization_tol):\n \"\"\"Discretize some line into points.\n\n Parameters\n ----------\n lines: Iterable[LineString] :\n Lines to discretize\n discretization_tol : float\n Maximum distance between two points on the line.\n\n Returns\n -------\n MultiPoint and defaultdict\n Return all the discretized points as a shapely MultiPoint and a dictionary to map the discretized points for\n each line.\n\n See Also\n --------\n discretize_line\n\n \"\"\"\n points_line_association = defaultdict(list)\n all_points = []\n nb_points = 0\n for line_index, line in enumerate(lines):\n discretized_points = discretize_line(line, discretization_tol)\n nb_discretized_points = len(discretized_points)\n all_points.extend(discretized_points)\n points_line_association[line_index] = list(range(nb_points, nb_points + nb_discretized_points))\n nb_points += nb_discretized_points\n all_points_as_mp = MultiPoint(all_points)\n return (all_points_as_mp, points_line_association)", "context": "def discretize_lines(lines: Iterable[LineString], discretization_tol): ...\ndef merge_two_shape(e1: Extremity, e2: Extremity, line1: LineString, line2: LineString) -> LineString: ...\ndef merge_two_lines_with_closest_extremities(first_line: LineString, second_line: LineString) -> LineString: ...\ndef get_shape_extremities(shape: LineString, shape_id: int): ...\ndef convert_multilinestring_to_linestring(gdf: gpd.GeoDataFrame) -> int: ...\ndef discretize_line(line: LineString, discretization_tol) -> list: ...\ndef discretize_lines(lines: Iterable[LineString], discretization_tol): ...\ndef get_closest_point_from_points(points_from: PointsCoordinatesLike, points_to: list=None, kd_tree: cKDTree=None): ...\ndef get_closest_point_from_line(line_from: LineString, discretization_tol: float, points_to: list=None, kd_tree: cKDTree=None): ...\ndef get_closest_point_from_multi_shape(multi_shape, points_to=None, kd_tree=None, discretization_tol: float=None): ...\ndef get_closest_point_from_shape(shape: Union[Point, LineString, MultiPoint, MultiLineString], points_to: Union[MultiPoint, np.ndarray, list]=None, kd_tree: cKDTree=None): ...\ndef get_closest_point_from_shapes(shapes_from, points_to): ...\ndef get_closest_line_from_point(point_from: PointCoordinatesLike, lines_to=None, discretization_tol=None, kd_tree=None, points_line_association=None): ...\ndef get_closest_line_from_points(points_from, lines_to, discretization_tol): ...\ndef get_polygons_neighborhood(polygons): ...\ndef split_line(line, distance): ...\ndef coordinates_almost_equal(c1: Iterable, c2: Iterable, tolerance=1e-08) -> bool: ...\ndef almost_equally_located(p1: Point, p2: Point, tolerance=1e-08) -> bool: ...\ndef insert_point_in_line(line: LineString, point_coords: list, position: int) -> LineString: ...\ndef get_default_discretization_tolerance(crs): ...\n", "repository": "Artelys/geonetworkx", "test_name": "test_discretize_lines", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000464.py"} {"focal_file": "geonetworkx/geometry_operations.py", "focal_class": null, "focal_method": "get_closest_point_from_multi_shape", "tests": "import unittest\n\nclass Test_get_closest_point_from_multi_shape(unittest.TestCase):\n def test_get_closest_point_from_multiline(self):\n l1 = LineString([(-73.615505, 45.504573), (-73.614989, 45.504329), (-73.614574, 45.504121), (-73.614322, 45.503854), (-73.614193, 45.503532), (-73.614075, 45.503182), (-73.613997, 45.503064), (-73.613952, 45.503005)])\n l2 = LineString([(-73.615454, 45.50464), (-73.614535, 45.504192), (-73.614193, 45.50385), (-73.61394, 45.503213), (-73.61384, 45.503096)])\n ml = MultiLineString([l1, l2])\n points = [Point(-73.613941, 45.504743), Point(-73.616263, 45.504509), Point(-73.61492, 45.50382), Point(-73.613956, 45.502349)]\n points_coords = np.array([[p.x, p.y] for p in points])\n d, ix = gnx.get_closest_point_from_multi_shape(ml, points_coords, discretization_tol=1e-05)\n self.assertEquals(ix, 2)\n", "method_code": "def get_closest_point_from_multi_shape(multi_shape, points_to=None, kd_tree=None, discretization_tol: float=None):\n \"\"\"Computes the closest point to the multi shape (i.e. the point that has the smallest projection distance on the\n entire multi shape object.\n\n Parameters\n ----------\n multi_shape : MultiPoint or MultiLineString\n The multi shape object can be any shapely object among: MultiPoint, MultiLineString\n points_to : list\n A list of points among which to find the closest to the multi shape (Default value = None)\n kd_tree : cKDTree\n A kdtree representing the points among which the closest to the multishape has to be found (optional\n if 'points_to' is given) (Default value = None)\n discretization_tol : float\n A discretization tolerance if the multishape is a MultiLineString\n\n Returns\n -------\n float\n distance\n int\n index of the closest point\n\n See Also\n --------\n get_closest_point_from_points\n get_closest_point_from_line\n\n \"\"\"\n if isinstance(multi_shape, MultiPoint):\n distances_and_points_indexes = get_closest_point_from_points(multi_shape, points_to, kd_tree)\n elif isinstance(multi_shape, MultiLineString):\n if discretization_tol is None:\n raise ValueError('A discretization tolerance must be provided if the multishape is a multiline')\n distances_and_points_indexes = []\n for line in multi_shape:\n distances_and_points_indexes.append(get_closest_point_from_line(line, discretization_tol, points_to, kd_tree))\n else:\n raise TypeError(\"Method not implemented for shape of type '%s', expected MultiPointor MultiLineString\" % str(type(multi_shape)))\n smallest_distance_index = np.argmin((d_ix[0] for d_ix in distances_and_points_indexes))\n return distances_and_points_indexes[smallest_distance_index]", "context": "def get_closest_point_from_multi_shape(multi_shape, points_to=None, kd_tree=None, discretization_tol: float=None): ...\ndef merge_two_shape(e1: Extremity, e2: Extremity, line1: LineString, line2: LineString) -> LineString: ...\ndef merge_two_lines_with_closest_extremities(first_line: LineString, second_line: LineString) -> LineString: ...\ndef get_shape_extremities(shape: LineString, shape_id: int): ...\ndef convert_multilinestring_to_linestring(gdf: gpd.GeoDataFrame) -> int: ...\ndef discretize_line(line: LineString, discretization_tol) -> list: ...\ndef discretize_lines(lines: Iterable[LineString], discretization_tol): ...\ndef get_closest_point_from_points(points_from: PointsCoordinatesLike, points_to: list=None, kd_tree: cKDTree=None): ...\ndef get_closest_point_from_line(line_from: LineString, discretization_tol: float, points_to: list=None, kd_tree: cKDTree=None): ...\ndef get_closest_point_from_multi_shape(multi_shape, points_to=None, kd_tree=None, discretization_tol: float=None): ...\ndef get_closest_point_from_shape(shape: Union[Point, LineString, MultiPoint, MultiLineString], points_to: Union[MultiPoint, np.ndarray, list]=None, kd_tree: cKDTree=None): ...\ndef get_closest_point_from_shapes(shapes_from, points_to): ...\ndef get_closest_line_from_point(point_from: PointCoordinatesLike, lines_to=None, discretization_tol=None, kd_tree=None, points_line_association=None): ...\ndef get_closest_line_from_points(points_from, lines_to, discretization_tol): ...\ndef get_polygons_neighborhood(polygons): ...\ndef split_line(line, distance): ...\ndef coordinates_almost_equal(c1: Iterable, c2: Iterable, tolerance=1e-08) -> bool: ...\ndef almost_equally_located(p1: Point, p2: Point, tolerance=1e-08) -> bool: ...\ndef insert_point_in_line(line: LineString, point_coords: list, position: int) -> LineString: ...\ndef get_default_discretization_tolerance(crs): ...\n", "repository": "Artelys/geonetworkx", "test_name": "test_get_closest_point_from_multiline", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000465.py"} {"focal_file": "nova/cmd/idmapshift.py", "focal_class": null, "focal_method": "shift_path", "tests": "import unittest\n\nclass Test_shift_path(unittest.TestCase):\n @mock.patch('os.lchown')\n @mock.patch('os.lstat')\n def test_shift_path(self, mock_lstat, mock_lchown):\n mock_lstat.return_value = FakeStat(0, 0)\n idmapshift.shift_path('/test/path', self.uid_maps, self.gid_maps, idmapshift.NOBODY_ID, dict(), dict())\n mock_lstat.assert_has_calls([mock.call('/test/path')])\n mock_lchown.assert_has_calls([mock.call('/test/path', 10000, 10000)])\n", "method_code": "def shift_path(path, uid_mappings, gid_mappings, nobody, uid_memo, gid_memo, dry_run=False, verbose=False):\n stat = os.lstat(path)\n uid = stat.st_uid\n gid = stat.st_gid\n target_uid = find_target_id(uid, uid_mappings, nobody, uid_memo)\n target_gid = find_target_id(gid, gid_mappings, nobody, gid_memo)\n if verbose:\n print_chown(path, uid, gid, target_uid, target_gid)\n if not dry_run:\n os.lchown(path, target_uid, target_gid)", "context": "def shift_path(path, uid_mappings, gid_mappings, nobody, uid_memo, gid_memo, dry_run=False, verbose=False): ...\ndef find_target_id(fsid, mappings, nobody, memo): ...\ndef print_chown(path, uid, gid, target_uid, target_gid): ...\ndef shift_path(path, uid_mappings, gid_mappings, nobody, uid_memo, gid_memo, dry_run=False, verbose=False): ...\ndef shift_dir(fsdir, uid_mappings, gid_mappings, nobody, dry_run=False, verbose=False): ...\ndef confirm_path(path, uid_ranges, gid_ranges, nobody): ...\ndef get_ranges(maps): ...\ndef confirm_dir(fsdir, uid_mappings, gid_mappings, nobody): ...\ndef id_map_type(val): ...\ndef main(): ...\n", "repository": "sajeeshcs/nested_quota", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000466.py"} {"focal_file": "nova/cmd/idmapshift.py", "focal_class": null, "focal_method": "shift_dir", "tests": "import unittest\n\nclass Test_shift_dir(unittest.TestCase):\n @mock.patch('nova.cmd.idmapshift.shift_path')\n @mock.patch('os.path.join')\n @mock.patch('os.walk')\n def test_shift_dir(self, mock_walk, mock_join, mock_shift_path):\n mock_walk.return_value = [('/', ['a', 'b'], ['c', 'd'])]\n mock_join.side_effect = join_side_effect\n idmapshift.shift_dir('/', self.uid_maps, self.gid_maps, idmapshift.NOBODY_ID)\n files = ['a', 'b', 'c', 'd']\n mock_walk.assert_has_calls([mock.call('/')])\n mock_join_calls = [mock.call('/', x) for x in files]\n mock_join.assert_has_calls(mock_join_calls)\n args = (self.uid_maps, self.gid_maps, idmapshift.NOBODY_ID)\n kwargs = dict(dry_run=False, verbose=False, uid_memo=dict(), gid_memo=dict())\n shift_path_calls = [mock.call('/', *args, **kwargs)]\n shift_path_calls += [mock.call('/' + x, *args, **kwargs) for x in files]\n mock_shift_path.assert_has_calls(shift_path_calls)\n\n @mock.patch('os.lchown')\n @mock.patch('os.lstat')\n @mock.patch('os.path.join')\n @mock.patch('os.walk')\n def test_integrated_shift_dir(self, mock_walk, mock_join, mock_lstat, mock_lchown):\n mock_walk.return_value = [('/tmp/test', ['a', 'b', 'c'], ['d']), ('/tmp/test/d', ['1', '2'], [])]\n mock_join.side_effect = join_side_effect\n\n def lstat(path):\n stats = {'t': FakeStat(0, 0), 'a': FakeStat(0, 0), 'b': FakeStat(0, 2), 'c': FakeStat(30000, 30000), 'd': FakeStat(100, 100), '1': FakeStat(0, 100), '2': FakeStat(100, 100)}\n return stats[path[-1]]\n mock_lstat.side_effect = lstat\n idmapshift.shift_dir('/tmp/test', self.uid_maps, self.gid_maps, idmapshift.NOBODY_ID, verbose=True)\n lchown_calls = [mock.call('/tmp/test', 10000, 10000), mock.call('/tmp/test/a', 10000, 10000), mock.call('/tmp/test/b', 10000, 10002), mock.call('/tmp/test/c', idmapshift.NOBODY_ID, idmapshift.NOBODY_ID), mock.call('/tmp/test/d', 20090, 20090), mock.call('/tmp/test/d/1', 10000, 20090), mock.call('/tmp/test/d/2', 20090, 20090)]\n mock_lchown.assert_has_calls(lchown_calls)\n", "method_code": "def shift_dir(fsdir, uid_mappings, gid_mappings, nobody, dry_run=False, verbose=False):\n uid_memo = dict()\n gid_memo = dict()\n\n def shift_path_short(p):\n shift_path(p, uid_mappings, gid_mappings, nobody, dry_run=dry_run, verbose=verbose, uid_memo=uid_memo, gid_memo=gid_memo)\n shift_path_short(fsdir)\n for root, dirs, files in os.walk(fsdir):\n for d in dirs:\n path = os.path.join(root, d)\n shift_path_short(path)\n for f in files:\n path = os.path.join(root, f)\n shift_path_short(path)", "context": "def shift_dir(fsdir, uid_mappings, gid_mappings, nobody, dry_run=False, verbose=False): ...\ndef find_target_id(fsid, mappings, nobody, memo): ...\ndef print_chown(path, uid, gid, target_uid, target_gid): ...\ndef shift_path(path, uid_mappings, gid_mappings, nobody, uid_memo, gid_memo, dry_run=False, verbose=False): ...\ndef shift_dir(fsdir, uid_mappings, gid_mappings, nobody, dry_run=False, verbose=False): ...\ndef confirm_path(path, uid_ranges, gid_ranges, nobody): ...\ndef get_ranges(maps): ...\ndef confirm_dir(fsdir, uid_mappings, gid_mappings, nobody): ...\ndef id_map_type(val): ...\ndef main(): ...\n", "repository": "sajeeshcs/nested_quota", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000467.py"} {"focal_file": "nova/cmd/idmapshift.py", "focal_class": null, "focal_method": "confirm_path", "tests": "import unittest\n\nclass Test_confirm_path(unittest.TestCase):\n @mock.patch('os.lstat')\n def test_confirm_path(self, mock_lstat):\n uid_ranges = [(1000, 1999)]\n gid_ranges = [(300, 399)]\n mock_lstat.return_value = FakeStat(1000, 301)\n result = idmapshift.confirm_path('/test/path', uid_ranges, gid_ranges, 50000)\n mock_lstat.assert_has_calls(mock.call('/test/path'))\n self.assertTrue(result)\n", "method_code": "def confirm_path(path, uid_ranges, gid_ranges, nobody):\n stat = os.lstat(path)\n uid = stat.st_uid\n gid = stat.st_gid\n uid_in_range = True if uid == nobody else False\n gid_in_range = True if gid == nobody else False\n if not uid_in_range or not gid_in_range:\n for start, end in uid_ranges:\n if start <= uid <= end:\n uid_in_range = True\n break\n for start, end in gid_ranges:\n if start <= gid <= end:\n gid_in_range = True\n break\n return uid_in_range and gid_in_range", "context": "def confirm_path(path, uid_ranges, gid_ranges, nobody): ...\ndef find_target_id(fsid, mappings, nobody, memo): ...\ndef print_chown(path, uid, gid, target_uid, target_gid): ...\ndef shift_path(path, uid_mappings, gid_mappings, nobody, uid_memo, gid_memo, dry_run=False, verbose=False): ...\ndef shift_dir(fsdir, uid_mappings, gid_mappings, nobody, dry_run=False, verbose=False): ...\ndef confirm_path(path, uid_ranges, gid_ranges, nobody): ...\ndef get_ranges(maps): ...\ndef confirm_dir(fsdir, uid_mappings, gid_mappings, nobody): ...\ndef id_map_type(val): ...\ndef main(): ...\n", "repository": "sajeeshcs/nested_quota", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000468.py"} {"focal_file": "nova/cmd/idmapshift.py", "focal_class": null, "focal_method": "confirm_dir", "tests": "import unittest\n\nclass Test_confirm_dir(unittest.TestCase):\n @mock.patch('nova.cmd.idmapshift.confirm_path')\n @mock.patch('os.path.join')\n @mock.patch('os.walk')\n def test_confirm_dir(self, mock_walk, mock_join, mock_confirm_path):\n mock_walk.return_value = [('/', ['a', 'b'], ['c', 'd'])]\n mock_join.side_effect = join_side_effect\n mock_confirm_path.return_value = True\n idmapshift.confirm_dir('/', self.uid_maps, self.gid_maps, idmapshift.NOBODY_ID)\n files = ['a', 'b', 'c', 'd']\n mock_walk.assert_has_calls([mock.call('/')])\n mock_join_calls = [mock.call('/', x) for x in files]\n mock_join.assert_has_calls(mock_join_calls)\n args = (self.uid_map_ranges, self.gid_map_ranges, idmapshift.NOBODY_ID)\n confirm_path_calls = [mock.call('/', *args)]\n confirm_path_calls += [mock.call('/' + x, *args) for x in files]\n mock_confirm_path.assert_has_calls(confirm_path_calls)\n", "method_code": "def confirm_dir(fsdir, uid_mappings, gid_mappings, nobody):\n uid_ranges = get_ranges(uid_mappings)\n gid_ranges = get_ranges(gid_mappings)\n if not confirm_path(fsdir, uid_ranges, gid_ranges, nobody):\n return False\n for root, dirs, files in os.walk(fsdir):\n for d in dirs:\n path = os.path.join(root, d)\n if not confirm_path(path, uid_ranges, gid_ranges, nobody):\n return False\n for f in files:\n path = os.path.join(root, f)\n if not confirm_path(path, uid_ranges, gid_ranges, nobody):\n return False\n return True", "context": "def confirm_dir(fsdir, uid_mappings, gid_mappings, nobody): ...\ndef find_target_id(fsid, mappings, nobody, memo): ...\ndef print_chown(path, uid, gid, target_uid, target_gid): ...\ndef shift_path(path, uid_mappings, gid_mappings, nobody, uid_memo, gid_memo, dry_run=False, verbose=False): ...\ndef shift_dir(fsdir, uid_mappings, gid_mappings, nobody, dry_run=False, verbose=False): ...\ndef confirm_path(path, uid_ranges, gid_ranges, nobody): ...\ndef get_ranges(maps): ...\ndef confirm_dir(fsdir, uid_mappings, gid_mappings, nobody): ...\ndef id_map_type(val): ...\ndef main(): ...\n", "repository": "sajeeshcs/nested_quota", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000469.py"} {"focal_file": "nova/cmd/idmapshift.py", "focal_class": null, "focal_method": "id_map_type", "tests": "import unittest\n\nclass Test_id_map_type(unittest.TestCase):\n def test_id_map_type(self):\n result = idmapshift.id_map_type('1:1:1,2:2:2')\n self.assertEqual([(1, 1, 1), (2, 2, 2)], result)\n", "method_code": "def id_map_type(val):\n maps = val.split(',')\n id_maps = []\n for m in maps:\n map_vals = m.split(':')\n if len(map_vals) != 3:\n msg = 'Invalid id map %s, correct syntax is guest-id:host-id:count.'\n raise argparse.ArgumentTypeError(msg % val)\n try:\n vals = [int(i) for i in map_vals]\n except ValueError:\n msg = 'Invalid id map %s, values must be integers' % val\n raise argparse.ArgumentTypeError(msg)\n id_maps.append(tuple(vals))\n return id_maps", "context": "def id_map_type(val): ...\ndef find_target_id(fsid, mappings, nobody, memo): ...\ndef print_chown(path, uid, gid, target_uid, target_gid): ...\ndef shift_path(path, uid_mappings, gid_mappings, nobody, uid_memo, gid_memo, dry_run=False, verbose=False): ...\ndef shift_dir(fsdir, uid_mappings, gid_mappings, nobody, dry_run=False, verbose=False): ...\ndef confirm_path(path, uid_ranges, gid_ranges, nobody): ...\ndef get_ranges(maps): ...\ndef confirm_dir(fsdir, uid_mappings, gid_mappings, nobody): ...\ndef id_map_type(val): ...\ndef main(): ...\n", "repository": "sajeeshcs/nested_quota", "test_name": "test_id_map_type", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000470.py"} {"focal_file": "nova/cmd/idmapshift.py", "focal_class": null, "focal_method": "main", "tests": "import unittest\n\nclass Test_main(unittest.TestCase):\n @mock.patch('nova.cmd.idmapshift.shift_dir')\n @mock.patch('argparse.ArgumentParser')\n def test_main(self, mock_parser_class, mock_shift_dir):\n mock_parser = mock.MagicMock()\n mock_parser.parse_args.return_value = mock_parser\n mock_parser.idempotent = False\n mock_parser.confirm = False\n mock_parser.path = '/test/path'\n mock_parser.uid = self.uid_maps\n mock_parser.gid = self.gid_maps\n mock_parser.nobody = idmapshift.NOBODY_ID\n mock_parser.dry_run = False\n mock_parser.verbose = False\n mock_parser_class.return_value = mock_parser\n idmapshift.main()\n mock_shift_dir_call = mock.call('/test/path', self.uid_maps, self.gid_maps, idmapshift.NOBODY_ID, dry_run=False, verbose=False)\n mock_shift_dir.assert_has_calls([mock_shift_dir_call])\n", "method_code": "def main():\n parser = argparse.ArgumentParser('User Namespace FS Owner Shift')\n parser.add_argument('path')\n parser.add_argument('-u', '--uid', type=id_map_type, default=[])\n parser.add_argument('-g', '--gid', type=id_map_type, default=[])\n parser.add_argument('-n', '--nobody', default=NOBODY_ID, type=int)\n parser.add_argument('-i', '--idempotent', action='store_true')\n parser.add_argument('-c', '--confirm', action='store_true')\n parser.add_argument('-d', '--dry-run', action='store_true')\n parser.add_argument('-v', '--verbose', action='store_true')\n args = parser.parse_args()\n if args.idempotent or args.confirm:\n if confirm_dir(args.path, args.uid, args.gid, args.nobody):\n sys.exit(0)\n elif args.confirm:\n sys.exit(1)\n shift_dir(args.path, args.uid, args.gid, args.nobody, dry_run=args.dry_run, verbose=args.verbose)", "context": "def main(): ...\ndef find_target_id(fsid, mappings, nobody, memo): ...\ndef print_chown(path, uid, gid, target_uid, target_gid): ...\ndef shift_path(path, uid_mappings, gid_mappings, nobody, uid_memo, gid_memo, dry_run=False, verbose=False): ...\ndef shift_dir(fsdir, uid_mappings, gid_mappings, nobody, dry_run=False, verbose=False): ...\ndef confirm_path(path, uid_ranges, gid_ranges, nobody): ...\ndef get_ranges(maps): ...\ndef confirm_dir(fsdir, uid_mappings, gid_mappings, nobody): ...\ndef id_map_type(val): ...\ndef main(): ...\n", "repository": "sajeeshcs/nested_quota", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000471.py"} {"focal_file": "gapsule/utils/decorators.py", "focal_class": null, "focal_method": "ajaxquery", "tests": "import unittest\n\nclass Test_ajaxquery(unittest.TestCase):\n def test_ajax_query(self):\n query, handle_mock, render_mock = self.create_query('GET', '1')\n func = ajaxquery(handle_mock)\n func(query)\n handle_mock.assert_called_once_with(query)\n render_mock.assert_not_called()\n\n def test_nonajax_query(self):\n query, handle_mock, render_mock = self.create_query('GET', '0')\n func = ajaxquery(handle_mock)\n func(query)\n handle_mock.assert_not_called()\n render_mock.assert_called_once_with('index.html')\n", "method_code": "def ajaxquery(f):\n \"\"\" Decorated function only runs if ajax-querying, otherwise render 'index.html'. \"\"\"\n\n @functools.wraps(f)\n def _wrapper(self, *args, **kwargs):\n if self.request.method in ('GET', 'HEAD') and (not self.get_query_argument('ajax', '0') == '1'):\n self.render(self.get_template_name(), **kwargs)\n return None\n else:\n return f(self, *args, **kwargs)\n return _wrapper", "context": "def ajaxquery(f): ...\ndef ajaxquery(f): ...\ndef active_authenticated(f): ...\ndef unauthenticated(url='/'): ...\n", "repository": "xjkdev/gapsule", "test_name": "test_ajax_query", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000472.py"} {"focal_file": "gapsule/utils/decorators.py", "focal_class": null, "focal_method": "unauthenticated", "tests": "import unittest\n\nclass Test_unauthenticated(unittest.TestCase):\n def test_unauthenticated1(self):\n handle_mock = Mock()\n user = NonCallableMock(user='alice', active=False)\n query, redirect = self.create_query('GET', user)\n f = unauthenticated('/')(handle_mock)\n f(query)\n redirect.assert_called_once()\n handle_mock.assert_not_called()\n\n def test_unauthenticated2(self):\n handle_mock = Mock()\n user = None\n query, redirect = self.create_query('GET', user)\n f = unauthenticated('/')(handle_mock)\n f(query)\n redirect.assert_not_called()\n handle_mock.assert_called_once_with(query)\n", "method_code": "def unauthenticated(url='/'):\n \"\"\" Decorate an function that only run when user unauthenticated. \"\"\"\n\n def decorator(f):\n\n @functools.wraps(f)\n def _wrapper(self, *args, **kwargs):\n nonlocal url\n if self.current_user:\n if self.request.method in ('GET', 'HEAD'):\n self.redirect(url)\n return None\n raise HTTPError(403)\n return f(self, *args, **kwargs)\n return _wrapper\n return decorator", "context": "def unauthenticated(url='/'): ...\ndef ajaxquery(f): ...\ndef active_authenticated(f): ...\ndef unauthenticated(url='/'): ...\n", "repository": "xjkdev/gapsule", "test_name": "test_unauthenticated1", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000473.py"} {"focal_file": "gapsule/utils/decorators.py", "focal_class": null, "focal_method": "active_authenticated", "tests": "import unittest\n\nclass Test_active_authenticated(unittest.TestCase):\n def test_active_authenticated1(self):\n handle_mock = Mock()\n user = NonCallableMock(user='alice', active=False)\n query, redirect = self.create_query('GET', user)\n f = active_authenticated(handle_mock)\n f(query)\n redirect.assert_called_once()\n handle_mock.assert_not_called()\n\n def test_active_authenticated2(self):\n handle_mock = Mock()\n user = NonCallableMock(user='alice', active=True)\n query, redirect = self.create_query('GET', user)\n f = active_authenticated(handle_mock)\n f(query)\n redirect.assert_not_called()\n handle_mock.assert_called_once_with(query)\n\n def test_active_authenticated3(self):\n handle_mock = Mock()\n user = None\n query, redirect = self.create_query('GET', user)\n f = active_authenticated(handle_mock)\n f(query)\n redirect.assert_called_once()\n handle_mock.assert_not_called()\n", "method_code": "def active_authenticated(f):\n \"\"\" Decorate an function only runs when if current user is signed and active. \n When not signed, redirect to login_url.\n When not active, redirect to verify_url. \"\"\"\n\n @functools.wraps(f)\n def _wrapper(self, *args, **kwargs):\n if not (self.current_user and self.current_user.active is True):\n if self.request.method in ('GET', 'HEAD'):\n url = self.get_login_url() if not self.current_user else self.get_verify_url()\n if '?' not in url:\n if urllib.parse.urlsplit(url).scheme:\n next_url = self.request.full_url()\n else:\n assert self.request.uri is not None\n next_url = self.request.uri\n url += '?' + urlencode(dict(next=next_url))\n self.redirect(url)\n return None\n raise HTTPError(403)\n return f(self, *args, **kwargs)\n return _wrapper", "context": "def active_authenticated(f): ...\ndef ajaxquery(f): ...\ndef active_authenticated(f): ...\ndef unauthenticated(url='/'): ...\n", "repository": "xjkdev/gapsule", "test_name": "test_active_authenticated1", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000474.py"} {"focal_file": "gapsule/utils/check_validity.py", "focal_class": null, "focal_method": "check_mail_validity", "tests": "import unittest\n\nclass Test_check_mail_validity(unittest.TestCase):\n def test_check_mail(self):\n false_data = ['', 'test', 'teste@cn', '-- test@dd.com', 'test@@qq.com']\n true_data = ['test@ddd.com', 'test@qq.com.cn']\n for false in false_data:\n self.assertFalse(check_mail_validity(false))\n for true in true_data:\n self.assertTrue(check_mail_validity(true))\n", "method_code": "def check_mail_validity(mail_address):\n if len(mail_address) == 0 or len(mail_address) > 40:\n return False\n if not re.match('^([A-Za-z0-9_\\\\.-])+\\\\@([A-Za-z0-9_\\\\.-])+\\\\.([A-Za-z]{2,8})$', mail_address):\n return False\n return True", "context": "def check_mail_validity(mail_address): ...\ndef check_reponame_validity(reponame): ...\ndef check_username_validity(username): ...\ndef check_mail_validity(mail_address): ...\ndef check_password_validity(password): ...\n", "repository": "xjkdev/gapsule", "test_name": "test_check_mail", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000475.py"} {"focal_file": "gapsule/utils/check_validity.py", "focal_class": null, "focal_method": "check_password_validity", "tests": "import unittest\n\nclass Test_check_password_validity(unittest.TestCase):\n def test_check_password(self):\n false_data = ['Ex1', '12345678', 'a1234567', 'Aaaaaaaa', '-- Aa123456', 'Aa012345678901234567890123456789012345678']\n true_data = ['Aa123456', 'A1234567']\n for false in false_data:\n self.assertFalse(check_password_validity(false))\n for true in true_data:\n self.assertTrue(check_password_validity(true))\n", "method_code": "def check_password_validity(password):\n if len(password) < 8 or len(password) == 0 or len(password) > 40:\n return False\n if not re.search('[A-Z]+', password):\n return False\n if not re.search('[0-9]+', password):\n return False\n if not re.match('^([a-zA-Z0-9_])+$', password):\n return False\n return True", "context": "def check_password_validity(password): ...\ndef check_reponame_validity(reponame): ...\ndef check_username_validity(username): ...\ndef check_mail_validity(mail_address): ...\ndef check_password_validity(password): ...\n", "repository": "xjkdev/gapsule", "test_name": "test_check_password", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000476.py"} {"focal_file": "gapsule/utils/check_validity.py", "focal_class": null, "focal_method": "check_reponame_validity", "tests": "import unittest\n\nclass Test_check_reponame_validity(unittest.TestCase):\n def test_check_reponame(self):\n false_data = ['tes', \"test'--\", 'abcdefghijabcdefghij123', '12345']\n true_data = ['anexample', 'ANEXAMPLE', 'a12345']\n for false in false_data:\n self.assertFalse(check_reponame_validity(false))\n for true in true_data:\n self.assertTrue(check_reponame_validity(true))\n\n def test_check_username(self):\n false_data = [';drop database gapsule;', 'a12', 'a01234567890123456789', '*test']\n true_data = ['anexample', 'ANEXAMPLE', 'a12345']\n true_data = ['anexample', 'ANEXAMPLE', 'a12345']\n for false in false_data:\n self.assertFalse(check_reponame_validity(false))\n for true in true_data:\n self.assertTrue(check_reponame_validity(true))\n", "method_code": "def check_reponame_validity(reponame):\n if len(reponame) < 4 or len(reponame) > 20:\n return False\n if not re.match('^[a-zA-Z][a-zA-Z0-9_]+$', reponame):\n return False\n return True", "context": "def check_reponame_validity(reponame): ...\ndef check_reponame_validity(reponame): ...\ndef check_username_validity(username): ...\ndef check_mail_validity(mail_address): ...\ndef check_password_validity(password): ...\n", "repository": "xjkdev/gapsule", "test_name": "test_check_reponame", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000477.py"} {"focal_file": "gapsule/models/git.py", "focal_class": null, "focal_method": "git_ls_files", "tests": "import unittest\n\nclass Test_git_ls_files(unittest.TestCase):\n @async_test\n async def test_ls_files(self):\n files = await git.git_ls_files('abcd', 'efgh', 'master')\n for name, h in files:\n self.assertTrue(name in ['test1.txt', 'test2.txt'])\n self.assertIsNot(re.match('[0-9a-f]{40}', h), None)\n files = await git.git_ls_files('abcd', 'efgh', 'master', show_tree=True)\n for name, h, isdir in files:\n self.assertTrue(name in ['test1.txt', 'test2.txt'])\n self.assertTrue(ishash(h))\n self.assertFalse(isdir)\n", "method_code": "def git_ls_files(owner: str, reponame: str, branch: str, *, path: str=None, show_tree=False, recursive=True) -> Union[List[Tuple[str, str]], List[Tuple[str, str, bool]]]: ...", "context": "async def git_ls_files(owner: str, reponame: str, branch: str, *, path: str=None, show_tree=False, recursive=True) -> Union[List[Tuple[str, str]], List[Tuple[str, str, bool]]]:\n root = get_repo_dirpath(owner, reponame)\n _check_exists(root)\n cmd = ['git', 'ls-tree']\n if recursive:\n cmd += ['-r']\n if show_tree:\n cmd += ['-t']\n cmd += [branch]\n if path is not None:\n cmd.append(path)\n returncode, out, err = await run(cmd, cwd=root, stdout=PIPE, stderr=PIPE, timeout=2)\n if returncode != 0:\n err = err.decode()\n if 'fatal: Not a valid object name master' in err:\n return []\n raise RuntimeError('git ls-tree error')\n filelines = map(lambda line: line.split(maxsplit=3), out.decode().split('\\n'))\n if not show_tree:\n result = [(info[3], info[2]) for info in filelines if len(info) != 0]\n else:\n result = [(info[3], info[2], info[1] == 'tree') for info in filelines if len(info) != 0]\n return result\ndef _check_exists(root: str): ...\ndef get_repo_dirpath(owner: str, reponame: str) -> str: ...\ndef delete_repo(owner: str, reponame: str): ...\ndef init_git_repo(owner: str, reponame: str) -> None: ...\ndef git_config(workingdir: str, key: str, value: str): ...\ndef git_ls_files(owner: str, reponame: str, branch: str, *, path: str=None, show_tree=False, recursive=True) -> Union[List[Tuple[str, str]], List[Tuple[str, str, bool]]]: ...: ...\ndef _read_medium_log(log: str) -> List[Dict[str, str]]: ...\ndef git_log(root: str, branch: str, pretty=ONELINE, path=None, maxsize: int=None, *, base: str=None) -> Union[List[Tuple[str, str]], List[Dict[str, str]], List[Tuple[str, str, str]]]: ...\ndef git_commit_logs(owner: str, reponame: str, branch: str, pretty=ONELINE, path=None, maxsize: int=None, *, base: str=None) -> Union[List[Tuple[str, str]], List[Dict[str, str]], List[Tuple[str, str, str]]]: ...\ndef git_branches(owner: str, reponame: str) -> Tuple[str, List[str]]: ...\ndef get_all_files_latest_commit(owner: str, reponame: str, branch: str, files: List[str]=None) -> List[str]: ...\ndef git_cat_file(owner: str, reponame: str, branch: str, path: str) -> bytes: ...\ndef git_fetch(dstroot: str, dstrefs: str, srcroot: str, srcrefs: str, *, fetch_head=False): ...\ndef git_create_branch(root: str, newbranch: str, frombranch: str): ...\ndef git_rm_branch(root: str, branch, *, force=False): ...\ndef git_clone(workingdir: str, owner: str, reponame: str, branch: str=None, *, bare=False): ...\ndef git_checkout(workingdir: str, branch: str): ...\ndef git_merge_action(workingdir: str, action: str): ...\ndef git_merge(workingdir: str, dstbranch: str, srcbranch: str): ...\ndef git_push(workingdir: str, dstbranch: str, dstremote: str=None): ...\ndef git_pull(workingdir: str, dstremote: str=None): ...\ndef git_commit(workingdir: str, message: str): ...\ndef git_diff_parsing(data): ...\ndef git_diff(workingdir: str, base_branch: str, compare_to: str) -> List[Tuple[str, str]]: ...\n", "repository": "xjkdev/gapsule", "test_name": "", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000478.py"} {"focal_file": "gapsule/models/git.py", "focal_class": null, "focal_method": "get_all_files_latest_commit", "tests": "import unittest\n\nclass Test_get_all_files_latest_commit(unittest.TestCase):\n @async_test\n async def test_all_files_latest_commit(self):\n logs = await git.get_all_files_latest_commit('abcd', 'efgh', 'master')\n for name, _, _, msg in logs:\n self.assertTrue(('test1.txt', 'init message') == (name, msg) or ('test2.txt', 'test commit') == (name, msg))\n", "method_code": "def get_all_files_latest_commit(owner: str, reponame: str, branch: str, files: List[str]=None) -> List[str]: ...", "context": "async def get_all_files_latest_commit(owner: str, reponame: str, branch: str, files: List[str]=None) -> List[str]:\n if files is None:\n files = [x[0] for x in await git_ls_files(owner, reponame, branch, recursive=False)]\n\n async def _task(f):\n r = await git_commit_logs(owner, reponame, branch, path=f, pretty=HASH_DATE_AND_MESSAGE, maxsize=1)\n return [f] + r[0]\n tasklist = (_task(f) for f in files)\n done = await asyncio.gather(*tasklist, return_exceptions=True)\n if len(done) < len(files):\n print('get_all_files_lastest_commit, not all tasks done.')\n return done\ndef _check_exists(root: str): ...\ndef get_repo_dirpath(owner: str, reponame: str) -> str: ...\ndef delete_repo(owner: str, reponame: str): ...\ndef init_git_repo(owner: str, reponame: str) -> None: ...\ndef git_config(workingdir: str, key: str, value: str): ...\ndef git_ls_files(owner: str, reponame: str, branch: str, *, path: str=None, show_tree=False, recursive=True) -> Union[List[Tuple[str, str]], List[Tuple[str, str, bool]]]: ...\ndef _read_medium_log(log: str) -> List[Dict[str, str]]: ...\ndef git_log(root: str, branch: str, pretty=ONELINE, path=None, maxsize: int=None, *, base: str=None) -> Union[List[Tuple[str, str]], List[Dict[str, str]], List[Tuple[str, str, str]]]: ...\ndef git_commit_logs(owner: str, reponame: str, branch: str, pretty=ONELINE, path=None, maxsize: int=None, *, base: str=None) -> Union[List[Tuple[str, str]], List[Dict[str, str]], List[Tuple[str, str, str]]]: ...\ndef git_branches(owner: str, reponame: str) -> Tuple[str, List[str]]: ...\ndef get_all_files_latest_commit(owner: str, reponame: str, branch: str, files: List[str]=None) -> List[str]: ...: ...\ndef git_cat_file(owner: str, reponame: str, branch: str, path: str) -> bytes: ...\ndef git_fetch(dstroot: str, dstrefs: str, srcroot: str, srcrefs: str, *, fetch_head=False): ...\ndef git_create_branch(root: str, newbranch: str, frombranch: str): ...\ndef git_rm_branch(root: str, branch, *, force=False): ...\ndef git_clone(workingdir: str, owner: str, reponame: str, branch: str=None, *, bare=False): ...\ndef git_checkout(workingdir: str, branch: str): ...\ndef git_merge_action(workingdir: str, action: str): ...\ndef git_merge(workingdir: str, dstbranch: str, srcbranch: str): ...\ndef git_push(workingdir: str, dstbranch: str, dstremote: str=None): ...\ndef git_pull(workingdir: str, dstremote: str=None): ...\ndef git_commit(workingdir: str, message: str): ...\ndef git_diff_parsing(data): ...\ndef git_diff(workingdir: str, base_branch: str, compare_to: str) -> List[Tuple[str, str]]: ...\n", "repository": "xjkdev/gapsule", "test_name": "", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000479.py"} {"focal_file": "gapsule/models/git.py", "focal_class": null, "focal_method": "git_cat_file", "tests": "import unittest\n\nclass Test_git_cat_file(unittest.TestCase):\n @async_test\n async def test_cat_file(self):\n content = await git.git_cat_file('abcd', 'efgh', 'master', 'test2.txt')\n self.assertTrue(content.decode(), 'testing file2')\n", "method_code": "def git_cat_file(owner: str, reponame: str, branch: str, path: str) -> bytes: ...", "context": "async def git_cat_file(owner: str, reponame: str, branch: str, path: str) -> bytes:\n root = get_repo_dirpath(owner, reponame)\n _check_exists(root)\n print('244 line')\n files = await git_ls_files(owner, reponame, branch, path=path, show_tree=True, recursive=False)\n for f in files:\n name, objhash, isdir = f\n if name == path:\n break\n else:\n raise FileNotFoundError(path)\n if isdir:\n raise OSError('trying to read content of directory')\n proc = await asyncio.create_subprocess_exec('git', 'cat-file', 'blob', objhash, cwd=root, stdout=PIPE, stderr=PIPE)\n out, err = await asyncio.wait_for(proc.communicate(), 5)\n if await asyncio.wait_for(proc.wait(), 1) != 0:\n print('a', out, err.decode())\n raise OSError('git cat file error')\n return out\ndef _check_exists(root: str): ...\ndef get_repo_dirpath(owner: str, reponame: str) -> str: ...\ndef delete_repo(owner: str, reponame: str): ...\ndef init_git_repo(owner: str, reponame: str) -> None: ...\ndef git_config(workingdir: str, key: str, value: str): ...\ndef git_ls_files(owner: str, reponame: str, branch: str, *, path: str=None, show_tree=False, recursive=True) -> Union[List[Tuple[str, str]], List[Tuple[str, str, bool]]]: ...\ndef _read_medium_log(log: str) -> List[Dict[str, str]]: ...\ndef git_log(root: str, branch: str, pretty=ONELINE, path=None, maxsize: int=None, *, base: str=None) -> Union[List[Tuple[str, str]], List[Dict[str, str]], List[Tuple[str, str, str]]]: ...\ndef git_commit_logs(owner: str, reponame: str, branch: str, pretty=ONELINE, path=None, maxsize: int=None, *, base: str=None) -> Union[List[Tuple[str, str]], List[Dict[str, str]], List[Tuple[str, str, str]]]: ...\ndef git_branches(owner: str, reponame: str) -> Tuple[str, List[str]]: ...\ndef get_all_files_latest_commit(owner: str, reponame: str, branch: str, files: List[str]=None) -> List[str]: ...\ndef git_cat_file(owner: str, reponame: str, branch: str, path: str) -> bytes: ...: ...\ndef git_fetch(dstroot: str, dstrefs: str, srcroot: str, srcrefs: str, *, fetch_head=False): ...\ndef git_create_branch(root: str, newbranch: str, frombranch: str): ...\ndef git_rm_branch(root: str, branch, *, force=False): ...\ndef git_clone(workingdir: str, owner: str, reponame: str, branch: str=None, *, bare=False): ...\ndef git_checkout(workingdir: str, branch: str): ...\ndef git_merge_action(workingdir: str, action: str): ...\ndef git_merge(workingdir: str, dstbranch: str, srcbranch: str): ...\ndef git_push(workingdir: str, dstbranch: str, dstremote: str=None): ...\ndef git_pull(workingdir: str, dstremote: str=None): ...\ndef git_commit(workingdir: str, message: str): ...\ndef git_diff_parsing(data): ...\ndef git_diff(workingdir: str, base_branch: str, compare_to: str) -> List[Tuple[str, str]]: ...\n", "repository": "xjkdev/gapsule", "test_name": "", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000480.py"} {"focal_file": "nova/compat/flagfile.py", "focal_class": null, "focal_method": "_open_file_for_reading", "tests": "import unittest\n\nclass Test_open_file_for_reading(unittest.TestCase):\n def test_open_file_for_reading(self):\n with flagfile._open_file_for_reading(__file__):\n pass\n", "method_code": "def _open_file_for_reading(path):\n \"\"\"Helper method which test code may stub out.\"\"\"\n return open(path, 'r')", "context": "def _open_file_for_reading(path): ...\ndef _get_flagfile(argp): ...\ndef _open_file_for_reading(path): ...\ndef _open_fd_for_writing(fd, _path): ...\ndef _read_lines(flagfile): ...\ndef _read_flagfile(arg, next_arg, tempdir=None): ...\ndef _iterate_args(args, iterator, **kwargs): ...\ndef handle_flagfiles(args, tempdir=None): ...\ndef handle_flagfiles_managed(args): ...\n", "repository": "paulmathews/nova", "test_name": "test_open_file_for_reading", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000481.py"} {"focal_file": "nova/compat/flagfile.py", "focal_class": null, "focal_method": "_open_fd_for_writing", "tests": "import unittest\n\nclass Test_open_fd_for_writing(unittest.TestCase):\n def test_open_fd_for_writing(self):\n fd, path = tempfile.mkstemp()\n try:\n with flagfile._open_fd_for_writing(fd, None):\n pass\n finally:\n os.remove(path)\n", "method_code": "def _open_fd_for_writing(fd, _path):\n \"\"\"Helper method which test code may stub out.\"\"\"\n return os.fdopen(fd, 'w')", "context": "def _open_fd_for_writing(fd, _path): ...\ndef _get_flagfile(argp): ...\ndef _open_file_for_reading(path): ...\ndef _open_fd_for_writing(fd, _path): ...\ndef _read_lines(flagfile): ...\ndef _read_flagfile(arg, next_arg, tempdir=None): ...\ndef _iterate_args(args, iterator, **kwargs): ...\ndef handle_flagfiles(args, tempdir=None): ...\ndef handle_flagfiles_managed(args): ...\n", "repository": "paulmathews/nova", "test_name": "test_open_fd_for_writing", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000482.py"} {"focal_file": "nova/compat/flagfile.py", "focal_class": null, "focal_method": "handle_flagfiles_managed", "tests": "import unittest\n\nclass Test_handle_flagfiles_managed(unittest.TestCase):\n def test_flagfile_managed(self):\n self.files['foo.flags'] = ''\n before = ['--flagfile=foo.flags']\n with flagfile.handle_flagfiles_managed(before) as after:\n self.assertEquals(after, ['--config-file=' + self.tempfiles[-1]])\n self.assertEquals(self.files[self.tempfiles[-1]], '[DEFAULT]\\n')\n self.assertTrue(self.tempdir is None)\n", "method_code": "def handle_flagfiles_managed(args):\n \"\"\"A context manager for handle_flagfiles() which removes temp files.\n\n For use with the 'with' statement, i.e.::\n\n with handle_flagfiles_managed(args) as args:\n # Do stuff\n # Any temporary fils have been removed\n \"\"\"\n tempdir = tempfile.mkdtemp(prefix='nova-conf-')\n try:\n yield handle_flagfiles(args, tempdir=tempdir)\n finally:\n shutil.rmtree(tempdir)", "context": "@contextlib.contextmanager\ndef handle_flagfiles_managed(args): ...\ndef _get_flagfile(argp): ...\ndef _open_file_for_reading(path): ...\ndef _open_fd_for_writing(fd, _path): ...\ndef _read_lines(flagfile): ...\ndef _read_flagfile(arg, next_arg, tempdir=None): ...\ndef _iterate_args(args, iterator, **kwargs): ...\ndef handle_flagfiles(args, tempdir=None): ...\ndef handle_flagfiles_managed(args): ...\n", "repository": "paulmathews/nova", "test_name": "test_flagfile_managed", "smells": [1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000483.py"} {"focal_file": "html5lib/inputstream.py", "focal_class": "BufferedStream", "focal_method": "tell", "tests": "import unittest\n\nclass Test_BufferedStream_tell(unittest.TestCase):\n def test_tell(self):\n fp = BufferedStream(BytesIO(b'abcdef'))\n read1 = fp.read(1)\n assert fp.tell() == 1\n read2 = fp.read(2)\n assert fp.tell() == 3\n read3 = fp.read(3)\n assert fp.tell() == 6\n read4 = fp.read(4)\n assert fp.tell() == 6\n\n def test_seek_tell(self):\n fp = BufferedStream(BytesIO(b'abcdef'))\n read1 = fp.read(1)\n assert fp.tell() == 1\n fp.seek(0)\n read2 = fp.read(1)\n assert fp.tell() == 1\n read3 = fp.read(2)\n assert fp.tell() == 3\n fp.seek(2)\n read4 = fp.read(2)\n assert fp.tell() == 4\n fp.seek(4)\n read5 = fp.read(2)\n assert fp.tell() == 6\n", "method_code": " def tell(self):\n pos = 0\n for chunk in self.buffer[:self.position[0]]:\n pos += len(chunk)\n pos += self.position[1]\n return pos\n ", "context": "class BufferedStream(object):\n def tell(self): ...\n def __init__(self, stream): ...\n def seek(self, pos): ...\n def read(self, bytes): ...\n def _bufferedBytes(self): ...\n def _readStream(self, bytes): ...\n def _readFromBuffer(self, bytes): ...\n\n self.stream = stream\n self.buffer = []\n self.position = [-1, 0]\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "test_tell", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000484.py"} {"focal_file": "html5lib/inputstream.py", "focal_class": "BufferedStream", "focal_method": "seek", "tests": "import unittest\n\nclass Test_BufferedStream_seek(unittest.TestCase):\n def test_seek(self):\n fp = BufferedStream(BytesIO(b'abcdef'))\n read1 = fp.read(1)\n assert read1 == b'a'\n fp.seek(0)\n read2 = fp.read(1)\n assert read2 == b'a'\n read3 = fp.read(2)\n assert read3 == b'bc'\n fp.seek(2)\n read4 = fp.read(2)\n assert read4 == b'cd'\n fp.seek(4)\n read5 = fp.read(2)\n assert read5 == b'ef'\n", "method_code": " def seek(self, pos):\n assert pos <= self._bufferedBytes()\n offset = pos\n i = 0\n while len(self.buffer[i]) < offset:\n offset -= len(self.buffer[i])\n i += 1\n self.position = [i, offset]\n ", "context": "class BufferedStream(object):\n def seek(self, pos): ...\n def __init__(self, stream): ...\n def tell(self): ...\n def read(self, bytes): ...\n def _bufferedBytes(self): ...\n def _readStream(self, bytes): ...\n def _readFromBuffer(self, bytes): ...\n\n self.stream = stream\n self.buffer = []\n self.position = [-1, 0]\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "test_seek", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000485.py"} {"focal_file": "html5lib/inputstream.py", "focal_class": null, "focal_method": "position", "tests": "import unittest\n\nclass Test_position(unittest.TestCase):\n def test_position(self):\n stream = HTMLBinaryInputStreamShortChunk(codecs.BOM_UTF8 + b'a\\nbb\\nccc\\nddde\\nf\\ngh')\n self.assertEqual(stream.position(), (1, 0))\n self.assertEqual(stream.charsUntil('c'), 'a\\nbb\\n')\n self.assertEqual(stream.position(), (3, 0))\n stream.unget('\\n')\n self.assertEqual(stream.position(), (2, 2))\n self.assertEqual(stream.charsUntil('c'), '\\n')\n self.assertEqual(stream.position(), (3, 0))\n stream.unget('\\n')\n self.assertEqual(stream.position(), (2, 2))\n self.assertEqual(stream.char(), '\\n')\n self.assertEqual(stream.position(), (3, 0))\n self.assertEqual(stream.charsUntil('e'), 'ccc\\nddd')\n self.assertEqual(stream.position(), (4, 3))\n self.assertEqual(stream.charsUntil('h'), 'e\\nf\\ng')\n self.assertEqual(stream.position(), (6, 1))\n\n def test_position2(self):\n stream = HTMLUnicodeInputStreamShortChunk('abc\\nd')\n self.assertEqual(stream.position(), (1, 0))\n self.assertEqual(stream.char(), 'a')\n self.assertEqual(stream.position(), (1, 1))\n self.assertEqual(stream.char(), 'b')\n self.assertEqual(stream.position(), (1, 2))\n self.assertEqual(stream.char(), 'c')\n self.assertEqual(stream.position(), (1, 3))\n self.assertEqual(stream.char(), '\\n')\n self.assertEqual(stream.position(), (2, 0))\n self.assertEqual(stream.char(), 'd')\n self.assertEqual(stream.position(), (2, 1))\n", "method_code": " def position(self):\n \"\"\"Returns (line, col) of the current position in the stream.\"\"\"\n line, col = self._position(self.chunkOffset)\n return (line + 1, col)\n ", "context": "class HTMLUnicodeInputStream(object):\n def position(self): ...\n def __init__(self, source): ...\n def reset(self): ...\n def openStream(self, source): ...\n def _position(self, offset): ...\n def char(self): ...\n def readChunk(self, chunkSize=None): ...\n def characterErrorsUCS4(self, data): ...\n def characterErrorsUCS2(self, data): ...\n def charsUntil(self, characters, opposite=False): ...\n def unget(self, char): ...\n\n self.newLines = [0]\n self.charEncoding = ('utf-8', 'certain')\n self.dataStream = self.openStream(source)\n\n _defaultChunkSize = 10240\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "test_position", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000486.py"} {"focal_file": "reportlab/src/reportlab/pdfbase/pdfutils.py", "focal_class": null, "focal_method": "_AsciiHexEncode", "tests": "import unittest\n\nclass Test_AsciiHexEncode(unittest.TestCase):\n def testAsciiHex(self):\n \"\"\"Test if the obvious test for whether ASCII-Hex encoding works.\"\"\"\n plainText = 'What is the average velocity of a sparrow?'\n encoded = _AsciiHexEncode(plainText)\n decoded = _AsciiHexDecode(encoded)\n msg = 'Round-trip AsciiHex encoding failed.'\n assert decoded == plainText, msg\n", "method_code": "def _AsciiHexEncode(input):\n \"\"\"Encodes input using ASCII-Hex coding.\n\n This is a verbose encoding used for binary data within\n a PDF file. One byte binary becomes two bytes of ASCII.\n Helper function used by images.\"\"\"\n if isUnicode(input):\n input = input.encode('utf-8')\n output = getBytesIO()\n output.write(binascii.b2a_hex(input))\n output.write(b'>')\n return output.getvalue()", "context": "def _AsciiHexEncode(input): ...\ndef _chunker(src, dst=[], chunkSize=60): ...\ndef makeA85Image(filename, IMG=None): ...\ndef makeRawImage(filename, IMG=None): ...\ndef cacheImageFile(filename, returnInMemory=0, IMG=None): ...\ndef preProcessImages(spec): ...\ndef cachedImageExists(filename): ...\ndef _normalizeLineEnds(text, desired='\\r\\n', unlikely='\\x00\\x01\\x02\\x03'): ...\ndef _AsciiHexEncode(input): ...\ndef _AsciiHexDecode(input): ...\ndef _wrap(input, columns=60): ...\ndef readJPEGInfo(image): ...\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "testAsciiHex", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000487.py"} {"focal_file": "reportlab/src/reportlab/pdfbase/ttfonts.py", "focal_class": "TTFontFile", "focal_method": "makeSubset", "tests": "import unittest\n\nclass Test_TTFontFile_makeSubset(unittest.TestCase):\n def testSubsetting(self):\n \"\"\"Tests TTFontFile and TTF parsing code\"\"\"\n ttf = TTFontFile('Vera.ttf')\n subset = ttf.makeSubset([65, 66])\n subset = TTFontFile(getBytesIO(subset), 0)\n for tag in ('cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep'):\n self.assert_(subset.get_table(tag))\n subset.seek_table('loca')\n for n in range(4):\n pos = subset.read_ushort()\n self.failIf(pos % 2 != 0, 'glyph %d at +%d should be long aligned' % (n, pos * 2))\n self.assertEquals(subset.name, b'BitstreamVeraSans-Roman')\n self.assertEquals(subset.flags, FF_SYMBOLIC)\n self.assertEquals(subset.italicAngle, 0.0)\n self.assertNear(subset.ascent, 759.765625)\n self.assertNear(subset.descent, -240.234375)\n self.assertEquals(subset.capHeight, 759.765625)\n self.assertNear(subset.bbox, [-183.10546875, -235.83984375, 1287.109375, 928.22265625])\n self.assertEquals(subset.stemV, 87)\n", "method_code": " def makeSubset(self, subset):\n \"\"\"Create a subset of a TrueType font\"\"\"\n output = TTFontMaker()\n glyphMap = [0]\n glyphSet = {0: 0}\n codeToGlyph = {}\n for code in subset:\n if code in self.charToGlyph:\n originalGlyphIdx = self.charToGlyph[code]\n else:\n originalGlyphIdx = 0\n if originalGlyphIdx not in glyphSet:\n glyphSet[originalGlyphIdx] = len(glyphMap)\n glyphMap.append(originalGlyphIdx)\n codeToGlyph[code] = glyphSet[originalGlyphIdx]\n start = self.get_table_pos('glyf')[0]\n n = 0\n while n < len(glyphMap):\n originalGlyphIdx = glyphMap[n]\n glyphPos = self.glyphPos[originalGlyphIdx]\n glyphLen = self.glyphPos[originalGlyphIdx + 1] - glyphPos\n n += 1\n if not glyphLen:\n continue\n self.seek(start + glyphPos)\n numberOfContours = self.read_short()\n if numberOfContours < 0:\n self.skip(8)\n flags = GF_MORE_COMPONENTS\n while flags & GF_MORE_COMPONENTS:\n flags = self.read_ushort()\n glyphIdx = self.read_ushort()\n if glyphIdx not in glyphSet:\n glyphSet[glyphIdx] = len(glyphMap)\n glyphMap.append(glyphIdx)\n if flags & GF_ARG_1_AND_2_ARE_WORDS:\n self.skip(4)\n else:\n self.skip(2)\n if flags & GF_WE_HAVE_A_SCALE:\n self.skip(2)\n elif flags & GF_WE_HAVE_AN_X_AND_Y_SCALE:\n self.skip(4)\n elif flags & GF_WE_HAVE_A_TWO_BY_TWO:\n self.skip(8)\n for tag in ('name', 'OS/2', 'cvt ', 'fpgm', 'prep'):\n try:\n output.add(tag, self.get_table(tag))\n except KeyError:\n pass\n post = b'\\x00\\x03\\x00\\x00' + self.get_table('post')[4:16] + b'\\x00' * 16\n output.add('post', post)\n numGlyphs = len(glyphMap)\n hmtx = []\n for n in xrange(numGlyphs):\n aw, lsb = self.hmetrics[glyphMap[n]]\n hmtx.append(int(aw))\n hmtx.append(int(lsb))\n n = len(hmtx) - 2\n while n and hmtx[n] == hmtx[n - 2]:\n n -= 2\n if not n:\n n = 2\n numberOfHMetrics = n >> 1\n hmtx = hmtx[:n] + hmtx[n + 1::2]\n hmtx = pack(*['>%dH' % len(hmtx)] + hmtx)\n output.add('hmtx', hmtx)\n hhea = self.get_table('hhea')\n hhea = _set_ushort(hhea, 34, numberOfHMetrics)\n output.add('hhea', hhea)\n maxp = self.get_table('maxp')\n maxp = _set_ushort(maxp, 4, numGlyphs)\n output.add('maxp', maxp)\n entryCount = len(subset)\n length = 10 + entryCount * 2\n cmap = [0, 1, 1, 0, 0, 12, 6, length, 0, 0, entryCount] + list(map(codeToGlyph.get, subset))\n cmap = pack(*['>%dH' % len(cmap)] + cmap)\n output.add('cmap', cmap)\n glyphData = self.get_table('glyf')\n offsets = []\n glyf = []\n pos = 0\n for n in xrange(numGlyphs):\n offsets.append(pos)\n originalGlyphIdx = glyphMap[n]\n glyphPos = self.glyphPos[originalGlyphIdx]\n glyphLen = self.glyphPos[originalGlyphIdx + 1] - glyphPos\n data = glyphData[glyphPos:glyphPos + glyphLen]\n if glyphLen > 2 and unpack('>h', data[:2])[0] < 0:\n pos_in_glyph = 10\n flags = GF_MORE_COMPONENTS\n while flags & GF_MORE_COMPONENTS:\n flags = unpack('>H', data[pos_in_glyph:pos_in_glyph + 2])[0]\n glyphIdx = unpack('>H', data[pos_in_glyph + 2:pos_in_glyph + 4])[0]\n data = _set_ushort(data, pos_in_glyph + 2, glyphSet[glyphIdx])\n pos_in_glyph = pos_in_glyph + 4\n if flags & GF_ARG_1_AND_2_ARE_WORDS:\n pos_in_glyph = pos_in_glyph + 4\n else:\n pos_in_glyph = pos_in_glyph + 2\n if flags & GF_WE_HAVE_A_SCALE:\n pos_in_glyph = pos_in_glyph + 2\n elif flags & GF_WE_HAVE_AN_X_AND_Y_SCALE:\n pos_in_glyph = pos_in_glyph + 4\n elif flags & GF_WE_HAVE_A_TWO_BY_TWO:\n pos_in_glyph = pos_in_glyph + 8\n glyf.append(data)\n pos = pos + glyphLen\n if pos % 4 != 0:\n padding = 4 - pos % 4\n glyf.append(b'\\x00' * padding)\n pos = pos + padding\n offsets.append(pos)\n output.add('glyf', b''.join(glyf))\n loca = []\n if pos + 1 >> 1 > 65535:\n indexToLocFormat = 1\n for offset in offsets:\n loca.append(offset)\n loca = pack(*['>%dL' % len(loca)] + loca)\n else:\n indexToLocFormat = 0\n for offset in offsets:\n loca.append(offset >> 1)\n loca = pack(*['>%dH' % len(loca)] + loca)\n output.add('loca', loca)\n head = self.get_table('head')\n head = _set_ushort(head, 50, indexToLocFormat)\n output.add('head', head)\n return output.makeStream()\n ", "context": "class TTFontFile(TTFontParser):\n def makeSubset(self, subset): ...\n def __init__(self, file, charInfo=1, validate=0, subfontIndex=0): ...\n def extractInfo(self, charInfo=1): ...\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "testSubsetting", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000488.py"} {"focal_file": "reportlab/src/reportlab/pdfbase/ttfonts.py", "focal_class": "TTFontFace", "focal_method": "addSubsetObjects", "tests": "import unittest\n\nclass Test_TTFontFace_addSubsetObjects(unittest.TestCase):\n def testAddSubsetObjects(self):\n \"\"\"Tests TTFontFace.addSubsetObjects\"\"\"\n face = TTFontFace('Vera.ttf')\n doc = PDFDocument()\n fontDescriptor = face.addSubsetObjects(doc, 'TestFont', [120, 8215])\n fontDescriptor = doc.idToObject[fontDescriptor.name].dict\n self.assertEquals(fontDescriptor['Type'], '/FontDescriptor')\n self.assertEquals(fontDescriptor['Ascent'], face.ascent)\n self.assertEquals(fontDescriptor['CapHeight'], face.capHeight)\n self.assertEquals(fontDescriptor['Descent'], face.descent)\n self.assertEquals(fontDescriptor['Flags'], face.flags & ~FF_NONSYMBOLIC | FF_SYMBOLIC)\n self.assertEquals(fontDescriptor['FontName'], '/TestFont')\n self.assertEquals(fontDescriptor['FontBBox'].sequence, face.bbox)\n self.assertEquals(fontDescriptor['ItalicAngle'], face.italicAngle)\n self.assertEquals(fontDescriptor['StemV'], face.stemV)\n fontFile = fontDescriptor['FontFile2']\n fontFile = doc.idToObject[fontFile.name]\n self.assert_(fontFile.content != '')\n", "method_code": " def addSubsetObjects(self, doc, fontname, subset):\n \"\"\"Generate a TrueType font subset and add it to the PDF document.\n Returns a PDFReference to the new FontDescriptor object.\"\"\"\n fontFile = pdfdoc.PDFStream()\n fontFile.content = self.makeSubset(subset)\n fontFile.dictionary['Length1'] = len(fontFile.content)\n if doc.compression:\n fontFile.filters = [pdfdoc.PDFZCompress]\n fontFileRef = doc.Reference(fontFile, 'fontFile:%s(%s)' % (self.filename, fontname))\n flags = self.flags & ~FF_NONSYMBOLIC\n flags = flags | FF_SYMBOLIC\n fontDescriptor = pdfdoc.PDFDictionary({'Type': '/FontDescriptor', 'Ascent': self.ascent, 'CapHeight': self.capHeight, 'Descent': self.descent, 'Flags': flags, 'FontBBox': pdfdoc.PDFArray(self.bbox), 'FontName': pdfdoc.PDFName(fontname), 'ItalicAngle': self.italicAngle, 'StemV': self.stemV, 'FontFile2': fontFileRef})\n return doc.Reference(fontDescriptor, 'fontDescriptor:' + fontname)\n ", "context": "class TTFontFace(TTFontFilepdfmetrics.TypeFace):\n def addSubsetObjects(self, doc, fontname, subset): ...\n def __init__(self, filename, validate=0, subfontIndex=0): ...\n def getCharWidth(self, code): ...\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "testAddSubsetObjects", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000489.py"} {"focal_file": "reportlab/src/reportlab/pdfbase/ttfonts.py", "focal_class": "TTFont", "focal_method": "stringWidth", "tests": "import unittest\n\nclass Test_TTFont_stringWidth(unittest.TestCase):\n def testStringWidth(self):\n \"\"\"Test TTFont.stringWidth\"\"\"\n font = TTFont('Vera', 'Vera.ttf')\n self.assert_(font.stringWidth('test', 10) > 0)\n width = font.stringWidth(utf8(8800) * 2, 1000)\n expected = font.face.getCharWidth(8800) * 2\n self.assertNear(width, expected)\n", "method_code": " def stringWidth(self, text, size, encoding='utf8'):\n return instanceStringWidthTTF(self, text, size, encoding)\n ", "context": "class TTFont():\n def stringWidth(self, text, size, encoding='utf8'): ...\n def __init__(self, name, filename, validate=0, subfontIndex=0, asciiReadable=None): ...\n def _assignState(self, doc, asciiReadable=None, namePrefix=None): ...\n def splitString(self, text, doc, encoding='utf-8'): ...\n def getSubsetInternalName(self, subset, doc): ...\n def addObjects(self, doc): ...\n\n self.fontName = name\n self.face = TTFontFace(filename, validate=validate, subfontIndex=subfontIndex)\n self.encoding = TTEncoding()\n self.state = WeakKeyDictionary()\n self._asciiReadable = asciiReadable\n\n _multiByte = 1\n _dynamicFont = 1\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "testStringWidth", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000490.py"} {"focal_file": "reportlab/src/reportlab/pdfbase/ttfonts.py", "focal_class": "TTFont", "focal_method": "splitString", "tests": "import unittest\n\nclass Test_TTFont_splitString(unittest.TestCase):\n def testSplitString(self):\n \"\"\"Tests TTFont.splitString\"\"\"\n doc = PDFDocument()\n font = TTFont('Vera', 'Vera.ttf')\n text = b''.join((utf8(i) for i in range(511)))\n allchars = b''.join((int2Byte(i) for i in range(256)))\n nospace = allchars[:32] + allchars[33:]\n chunks = [(0, allchars), (1, nospace)]\n self.assertEquals(font.splitString(text, doc), chunks)\n self.assertEquals(font.splitString(text, doc), chunks)\n text = b''.join((utf8(i) for i in range(510, -1, -1)))\n allchars = b''.join((int2Byte(i) for i in range(255, -1, -1)))\n nospace = allchars[:223] + allchars[224:]\n chunks = [(1, nospace), (0, allchars)]\n self.assertEquals(font.splitString(text, doc), chunks)\n\n def testSplitStringSpaces(self):\n doc = PDFDocument()\n font = TTFont('Vera', 'Vera.ttf')\n text = b''.join((utf8(i) for i in range(512, -1, -1)))\n chunks = font.splitString(text, doc)\n state = font.state[doc]\n self.assertEquals(state.assignments[32], 32)\n self.assertEquals(state.subsets[0][32], 32)\n self.assertEquals(state.subsets[1][32], 32)\n", "method_code": " def splitString(self, text, doc, encoding='utf-8'):\n \"\"\"Splits text into a number of chunks, each of which belongs to a\n single subset. Returns a list of tuples (subset, string). Use subset\n numbers with getSubsetInternalName. Doc is needed for distinguishing\n subsets when building different documents at the same time.\"\"\"\n asciiReadable = self._asciiReadable\n try:\n state = self.state[doc]\n except KeyError:\n state = self.state[doc] = TTFont.State(asciiReadable)\n curSet = -1\n cur = []\n results = []\n if not isUnicode(text):\n text = text.decode('utf-8')\n assignments = state.assignments\n subsets = state.subsets\n for code in map(ord, text):\n if code in assignments:\n n = assignments[code]\n else:\n if state.frozen:\n raise pdfdoc.PDFError('Font %s is already frozen, cannot add new character U+%04X' % (self.fontName, code))\n n = state.nextCode\n if n & 255 == 32:\n if n != 32:\n subsets[n >> 8].append(32)\n state.nextCode += 1\n n = state.nextCode\n state.nextCode += 1\n assignments[code] = n\n if n > 32:\n if not n & 255:\n subsets.append([])\n subsets[n >> 8].append(code)\n else:\n subsets[0][n] = code\n if n >> 8 != curSet:\n if cur:\n results.append((curSet, bytes(cur) if isPy3 else ''.join((chr(c) for c in cur))))\n curSet = n >> 8\n cur = []\n cur.append(n & 255)\n if cur:\n results.append((curSet, bytes(cur) if isPy3 else ''.join((chr(c) for c in cur))))\n return results\n ", "context": "class TTFont():\n def splitString(self, text, doc, encoding='utf-8'): ...\n def __init__(self, name, filename, validate=0, subfontIndex=0, asciiReadable=None): ...\n def stringWidth(self, text, size, encoding='utf8'): ...\n def _assignState(self, doc, asciiReadable=None, namePrefix=None): ...\n def getSubsetInternalName(self, subset, doc): ...\n def addObjects(self, doc): ...\n\n self.fontName = name\n self.face = TTFontFace(filename, validate=validate, subfontIndex=subfontIndex)\n self.encoding = TTEncoding()\n self.state = WeakKeyDictionary()\n self._asciiReadable = asciiReadable\n\n _multiByte = 1\n _dynamicFont = 1\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "testSplitString", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000491.py"} {"focal_file": "reportlab/src/reportlab/pdfbase/ttfonts.py", "focal_class": "TTFont", "focal_method": "getSubsetInternalName", "tests": "import unittest\n\nclass Test_TTFont_getSubsetInternalName(unittest.TestCase):\n def testSubsetInternalName(self):\n \"\"\"Tests TTFont.getSubsetInternalName\"\"\"\n doc = PDFDocument()\n font = TTFont('Vera', 'Vera.ttf')\n text = b''.join((utf8(i) for i in range(513)))\n font.splitString(text, doc)\n self.assertRaises(IndexError, font.getSubsetInternalName, -1, doc)\n self.assertRaises(IndexError, font.getSubsetInternalName, 3, doc)\n self.assertEquals(font.getSubsetInternalName(0, doc), '/F1+0')\n self.assertEquals(font.getSubsetInternalName(1, doc), '/F1+1')\n self.assertEquals(font.getSubsetInternalName(2, doc), '/F1+2')\n self.assertEquals(doc.delayedFonts, [font])\n", "method_code": " def getSubsetInternalName(self, subset, doc):\n \"\"\"Returns the name of a PDF Font object corresponding to a given\n subset of this dynamic font. Use this function instead of\n PDFDocument.getInternalFontName.\"\"\"\n try:\n state = self.state[doc]\n except KeyError:\n state = self.state[doc] = TTFont.State(self._asciiReadable)\n if subset < 0 or subset >= len(state.subsets):\n raise IndexError('Subset %d does not exist in font %s' % (subset, self.fontName))\n if state.internalName is None:\n state.internalName = state.namePrefix + repr(len(doc.fontMapping) + 1)\n doc.fontMapping[self.fontName] = '/' + state.internalName\n doc.delayedFonts.append(self)\n return '/%s+%d' % (state.internalName, subset)\n ", "context": "class TTFont():\n def getSubsetInternalName(self, subset, doc): ...\n def __init__(self, name, filename, validate=0, subfontIndex=0, asciiReadable=None): ...\n def stringWidth(self, text, size, encoding='utf8'): ...\n def _assignState(self, doc, asciiReadable=None, namePrefix=None): ...\n def splitString(self, text, doc, encoding='utf-8'): ...\n def addObjects(self, doc): ...\n\n self.fontName = name\n self.face = TTFontFace(filename, validate=validate, subfontIndex=subfontIndex)\n self.encoding = TTEncoding()\n self.state = WeakKeyDictionary()\n self._asciiReadable = asciiReadable\n\n _multiByte = 1\n _dynamicFont = 1\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "testSubsetInternalName", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000492.py"} {"focal_file": "reportlab/src/reportlab/pdfbase/ttfonts.py", "focal_class": "TTFont", "focal_method": "addObjects", "tests": "import unittest\n\nclass Test_TTFont_addObjects(unittest.TestCase):\n def testAddObjectsEmpty(self):\n \"\"\"TTFont.addObjects should not fail when no characters were used\"\"\"\n font = TTFont('Vera', 'Vera.ttf')\n doc = PDFDocument()\n font.addObjects(doc)\n\n def testAddObjects(self):\n \"\"\"Test TTFont.addObjects\"\"\"\n ttfAsciiReadable = rl_config.ttfAsciiReadable\n try:\n rl_config.ttfAsciiReadable = 1\n doc = PDFDocument()\n font = TTFont('Vera', 'Vera.ttf')\n font.splitString('a', doc)\n internalName = font.getSubsetInternalName(0, doc)[1:]\n font.addObjects(doc)\n pdfFont = doc.idToObject[internalName]\n self.assertEquals(doc.idToObject['BasicFonts'].dict[internalName], pdfFont)\n self.assertEquals(pdfFont.Name, internalName)\n self.assertEquals(pdfFont.BaseFont, 'AAAAAA+BitstreamVeraSans-Roman')\n self.assertEquals(pdfFont.FirstChar, 0)\n self.assertEquals(pdfFont.LastChar, 127)\n self.assertEquals(len(pdfFont.Widths.sequence), 128)\n toUnicode = doc.idToObject[pdfFont.ToUnicode.name]\n self.assert_(toUnicode.content != '')\n fontDescriptor = doc.idToObject[pdfFont.FontDescriptor.name]\n self.assertEquals(fontDescriptor.dict['Type'], '/FontDescriptor')\n finally:\n rl_config.ttfAsciiReadable = ttfAsciiReadable\n", "method_code": " def addObjects(self, doc):\n \"\"\"Makes one or more PDF objects to be added to the document. The\n caller supplies the internal name to be used (typically F1, F2, ... in\n sequence).\n \n This method creates a number of Font and FontDescriptor objects. Every\n FontDescriptor is a (no more than) 256 character subset of the original\n TrueType font.\"\"\"\n try:\n state = self.state[doc]\n except KeyError:\n state = self.state[doc] = TTFont.State(self._asciiReadable)\n state.frozen = 1\n for n, subset in enumerate(state.subsets):\n internalName = self.getSubsetInternalName(n, doc)[1:]\n baseFontName = b''.join((SUBSETN(n), b'+', self.face.name, self.face.subfontNameX)).decode('pdfdoc')\n pdfFont = pdfdoc.PDFTrueTypeFont()\n pdfFont.__Comment__ = 'Font %s subset %d' % (self.fontName, n)\n pdfFont.Name = internalName\n pdfFont.BaseFont = baseFontName\n pdfFont.FirstChar = 0\n pdfFont.LastChar = len(subset) - 1\n widths = list(map(self.face.getCharWidth, subset))\n pdfFont.Widths = pdfdoc.PDFArray(widths)\n cmapStream = pdfdoc.PDFStream()\n cmapStream.content = makeToUnicodeCMap(baseFontName, subset)\n if doc.compression:\n cmapStream.filters = [pdfdoc.PDFZCompress]\n pdfFont.ToUnicode = doc.Reference(cmapStream, 'toUnicodeCMap:' + baseFontName)\n pdfFont.FontDescriptor = self.face.addSubsetObjects(doc, baseFontName, subset)\n ref = doc.Reference(pdfFont, internalName)\n fontDict = doc.idToObject['BasicFonts'].dict\n fontDict[internalName] = pdfFont\n del self.state[doc]\n ", "context": "class TTFont():\n def addObjects(self, doc): ...\n def __init__(self, name, filename, validate=0, subfontIndex=0, asciiReadable=None): ...\n def stringWidth(self, text, size, encoding='utf8'): ...\n def _assignState(self, doc, asciiReadable=None, namePrefix=None): ...\n def splitString(self, text, doc, encoding='utf-8'): ...\n def getSubsetInternalName(self, subset, doc): ...\n\n self.fontName = name\n self.face = TTFontFace(filename, validate=validate, subfontIndex=subfontIndex)\n self.encoding = TTEncoding()\n self.state = WeakKeyDictionary()\n self._asciiReadable = asciiReadable\n\n _multiByte = 1\n _dynamicFont = 1\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "testAddObjectsEmpty", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000493.py"} {"focal_file": "reportlab/src/reportlab/pdfbase/ttfonts.py", "focal_class": null, "focal_method": "makeToUnicodeCMap", "tests": "import unittest\n\nclass Test_makeToUnicodeCMap(unittest.TestCase):\n def testMakeToUnicodeCMap(self):\n \"\"\"Test makeToUnicodeCMap\"\"\"\n self.assertEquals(makeToUnicodeCMap('TestFont', [4660, 17185, 16962]), '/CIDInit /ProcSet findresource begin\\n12 dict begin\\nbegincmap\\n/CIDSystemInfo\\n<< /Registry (TestFont)\\n/Ordering (TestFont)\\n/Supplement 0\\n>> def\\n/CMapName /TestFont def\\n/CMapType 2 def\\n1 begincodespacerange\\n<00> <02>\\nendcodespacerange\\n3 beginbfchar\\n<00> <1234>\\n<01> <4321>\\n<02> <4242>\\nendbfchar\\nendcmap\\nCMapName currentdict /CMap defineresource pop\\nend\\nend')\n", "method_code": "def makeToUnicodeCMap(fontname, subset):\n \"\"\"Creates a ToUnicode CMap for a given subset. See Adobe\n _PDF_Reference (ISBN 0-201-75839-3) for more information.\"\"\"\n cmap = ['/CIDInit /ProcSet findresource begin', '12 dict begin', 'begincmap', '/CIDSystemInfo', '<< /Registry (%s)' % fontname, '/Ordering (%s)' % fontname, '/Supplement 0', '>> def', '/CMapName /%s def' % fontname, '/CMapType 2 def', '1 begincodespacerange', '<00> <%02X>' % (len(subset) - 1), 'endcodespacerange', '%d beginbfchar' % len(subset)] + ['<%02X> <%04X>' % (i, v) for i, v in enumerate(subset)] + ['endbfchar', 'endcmap', 'CMapName currentdict /CMap defineresource pop', 'end', 'end']\n return '\\n'.join(cmap)", "context": "def makeToUnicodeCMap(fontname, subset): ...\ndef makeToUnicodeCMap(fontname, subset): ...\ndef splice(stream, offset, value): ...\ndef _set_ushort(stream, offset, value): ...\ndef TTFOpenFile(fn): ...\n", "repository": "malexandre/python-xhtml2pdf-demo", "test_name": "testMakeToUnicodeCMap", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000494.py"} {"focal_file": "compmed/CompMedServiceInterface.py", "focal_class": null, "focal_method": "_inject_offset_for_paginated_query", "tests": "import unittest\n\nclass Test_inject_offset_for_paginated_query(unittest.TestCase):\n def test_inject_offset_for_paginated_query(self):\n \"\"\"\n case: entity chunk is returned with offsets injected\n\n \"\"\"\n input = [{'Id': 0, 'BeginOffset': 10, 'EndOffset': 20, 'Score': 0.99}, {'Id': 1, 'BeginOffset': 30, 'EndOffset': 35, 'Score': 0.99}]\n expectedOutput = [{'Id': 20, 'BeginOffset': 20, 'EndOffset': 30, 'Score': 0.99}, {'Id': 21, 'BeginOffset': 40, 'EndOffset': 45, 'Score': 0.99}]\n actualOutput = self.CompMedServiceInterface._inject_offset_for_paginated_query(input, 10, 20)\n self.assertEqual(expectedOutput, actualOutput, 'entity chunk is returned with offsets injected')\n", "method_code": " def _inject_offset_for_paginated_query(self, entity_chunk, char_offset: int, id_offset: int):\n \"\"\"\n Given a JSON-like entity, use the provided initial char offset and entity ID offset to\n :param entity_chunk: a list of dicts containing: 'Id', 'BeginOffset', 'EndOffset'\n :param char_offset: the int offset to add to all entities\n :param id_offset: the ID count offset to add to all ID's\n :return:\n \"\"\"\n for entity in entity_chunk:\n entity['Id'] = entity['Id'] + id_offset\n entity['BeginOffset'] = entity['BeginOffset'] + char_offset\n entity['EndOffset'] = entity['EndOffset'] + char_offset\n return entity_chunk\n ", "context": "class CompMedServiceInterface(AmazonServiceInterface):\n def _inject_offset_for_paginated_query(self, entity_chunk, char_offset: int, id_offset: int): ...\n def __init__(self, output_parser): ...\n def get_entities(self, text, **kwargs): ...\n def get_phi(self, text, **kwargs): ...\n def _get_call(self, text, **kwargs): ...\n def _get_service_function(self, **kwargs): ...\n def _pare_returned_types(self, chunk_result, vetted_types): ...\n def _get_paginated_entities(self, text_list, **kwargs): ...\n def vet_text(self, text, cutoff=CUTOFF_LENGTH): ...\n def _find_cutoff_point_in_text(self, text_chunk): ...\n def _vet_entity_types(self, type_list): ...\n\n self.parser = output_parser\n", "repository": "FredHutch/ComprehendMedicalInterface", "test_name": "test_inject_offset_for_paginated_query", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000495.py"} {"focal_file": "compmed/CompMedServiceInterface.py", "focal_class": null, "focal_method": "_get_paginated_entities", "tests": "import unittest\n\nclass Test_get_paginated_entities(unittest.TestCase):\n def test_get_paginated_entities(self):\n \"\"\"\n case: when the MedLPService is called with paginated input, the output is correctly stitched together.\n \"\"\"\n serviceOutput_1 = {'Entities': [{'Id': 0, 'BeginOffset': 20, 'EndOffset': 30, 'Score': 0.99}, {'Id': 1, 'BeginOffset': 40, 'EndOffset': 45, 'Score': 0.99}]}\n serviceOutput_2 = {'Entities': [{'Id': 0, 'BeginOffset': 20, 'EndOffset': 30, 'Score': 0.99}, {'Id': 1, 'BeginOffset': 40, 'EndOffset': 45, 'Score': 0.99}]}\n serviceOutput_3 = {'Entities': [{'Id': 0, 'BeginOffset': 20, 'EndOffset': 30, 'Score': 0.99}, {'Id': 1, 'BeginOffset': 40, 'EndOffset': 45, 'Score': 0.99}]}\n mockCompMedService = mock.MagicMock()\n mockCompMedService.detect_entities.side_effect = iter([serviceOutput_1, serviceOutput_2, serviceOutput_3])\n self.CompMedServiceInterface.service = mockCompMedService\n input = ['foo bar baz', 'bif zoom pow', 'bof zow bonk']\n expectedOutput = [{'Id': 0, 'BeginOffset': 20, 'EndOffset': 30, 'Score': 0.99}, {'Id': 1, 'BeginOffset': 40, 'EndOffset': 45, 'Score': 0.99}, {'Id': 2, 'BeginOffset': 31, 'EndOffset': 41, 'Score': 0.99}, {'Id': 3, 'BeginOffset': 51, 'EndOffset': 56, 'Score': 0.99}, {'Id': 4, 'BeginOffset': 43, 'EndOffset': 53, 'Score': 0.99}, {'Id': 5, 'BeginOffset': 63, 'EndOffset': 68, 'Score': 0.99}]\n actualOutput = self.CompMedServiceInterface._get_paginated_entities(input, apicall='entities')\n self.assertEqual(expectedOutput, actualOutput, 'The returns from the MedLPService will be correctly stitched together across calls')\n", "method_code": " def _get_paginated_entities(self, text_list, **kwargs):\n results = []\n char_offset = 0\n id_offset = 0\n fn = self._get_service_function(**kwargs)\n for i, text_chunk in enumerate(text_list):\n if 'entityTypes' in kwargs:\n vetted_types = self._vet_entity_types(kwargs['entityTypes'])\n chunk_result = fn(Text=text_chunk)\n chunk_result = self._pare_returned_types(chunk_result, vetted_types)\n else:\n chunk_result = fn(Text=text_chunk)\n id_increment = 0\n try:\n id_increment = chunk_result['Entities'][-1]['Id'] + 1\n except IndexError as e:\n logger.warning('no entities within range of {} to {}'.format(char_offset, char_offset + CUTOFF_LENGTH))\n results.append(self._inject_offset_for_paginated_query(chunk_result['Entities'], char_offset, id_offset))\n char_offset += len(text_chunk)\n id_offset += id_increment\n flattened_results = list(itertools.chain.from_iterable(results))\n return flattened_results\n ", "context": "class CompMedServiceInterface(AmazonServiceInterface):\n def _get_paginated_entities(self, text_list, **kwargs): ...\n def __init__(self, output_parser): ...\n def get_entities(self, text, **kwargs): ...\n def get_phi(self, text, **kwargs): ...\n def _get_call(self, text, **kwargs): ...\n def _get_service_function(self, **kwargs): ...\n def _pare_returned_types(self, chunk_result, vetted_types): ...\n def _inject_offset_for_paginated_query(self, entity_chunk, char_offset: int, id_offset: int): ...\n def vet_text(self, text, cutoff=CUTOFF_LENGTH): ...\n def _find_cutoff_point_in_text(self, text_chunk): ...\n def _vet_entity_types(self, type_list): ...\n\n self.parser = output_parser\n", "repository": "FredHutch/ComprehendMedicalInterface", "test_name": "test_get_paginated_entities", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000496.py"} {"focal_file": "make_ngrams.py", "focal_class": null, "focal_method": "lowercase_sentence_start_if_required", "tests": "import unittest\n\nclass Test_lowercase_sentence_start_if_required(unittest.TestCase):\n def test_lowercase_sentence_start_if_required(self):\n s = 'Hello there'\n e = 'hello there'\n r = make_ngrams.lowercase_sentence_start_if_required(s)\n self.assertEqual(r, e)\n s = 'Hello There'\n e = 'Hello There'\n r = make_ngrams.lowercase_sentence_start_if_required(s)\n self.assertEqual(r, e)\n", "method_code": "def lowercase_sentence_start_if_required(sentence):\n nbr_capital_letters = [s for s in sentence if s in string.ascii_uppercase]\n if len(nbr_capital_letters) == 1:\n sentence = sentence[0].lower() + sentence[1:]\n return sentence", "context": "def lowercase_sentence_start_if_required(sentence): ...\ndef get_cleaned_capitalised_word_sequences(sentence): ...\ndef remove_urls(s): ...\ndef flatten(l): ...\ndef lowercase_sentence_start_if_required(sentence): ...\ndef lowercase_split(s): ...\ndef stopword(word): ...\ndef get_capitalised_word_sequences(sentences): ...\n", "repository": "ianozsvald/twitter_networkx_concept_map", "test_name": "test_lowercase_sentence_start_if_required", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000497.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/command/build_ext.py", "focal_class": "build_ext", "focal_method": "get_ext_filename", "tests": "import unittest\n\nclass Test_build_ext_get_ext_filename(unittest.TestCase):\n def test_get_ext_filename(self):\n dist = Distribution()\n cmd = build_ext(dist)\n cmd.ext_map['foo/bar'] = ''\n res = cmd.get_ext_filename('foo')\n wanted = distutils_build_ext.get_ext_filename(cmd, 'foo')\n assert res == wanted\n", "method_code": " def get_ext_filename(self, fullname):\n filename = _build_ext.get_ext_filename(self, fullname)\n if fullname in self.ext_map:\n ext = self.ext_map[fullname]\n if isinstance(ext, Library):\n fn, ext = os.path.splitext(filename)\n return self.shlib_compiler.library_filename(fn, libtype)\n elif use_stubs and ext._links_to_dynamic:\n d, fn = os.path.split(filename)\n return os.path.join(d, 'dl-' + fn)\n return filename\n ", "context": "class build_ext(_build_ext):\n def get_ext_filename(self, fullname): ...\n def run(self): ...\n def copy_extensions_to_source(self): ...\n def initialize_options(self): ...\n def finalize_options(self): ...\n def setup_shlib_compiler(self): ...\n def get_export_symbols(self, ext): ...\n def build_extension(self, ext): ...\n def links_to_dynamic(self, ext): ...\n def get_outputs(self): ...\n def write_stub(self, output_dir, ext, compile=False): ...\n", "repository": "dipivan/my-first-blog1", "test_name": "test_get_ext_filename", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000498.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/command/easy_install.py", "focal_class": "easy_install", "focal_method": "install_site_py", "tests": "import unittest\n\nclass Test_easy_install_install_site_py(unittest.TestCase):\n def test_install_site_py(self):\n dist = Distribution()\n cmd = easy_install(dist)\n cmd.sitepy_installed = False\n cmd.install_dir = tempfile.mkdtemp()\n try:\n cmd.install_site_py()\n sitepy = os.path.join(cmd.install_dir, 'site.py')\n self.assertTrue(os.path.exists(sitepy))\n finally:\n shutil.rmtree(cmd.install_dir)\n", "method_code": " def install_site_py(self):\n \"\"\"Make sure there's a site.py in the target dir, if needed\"\"\"\n if self.sitepy_installed:\n return\n sitepy = os.path.join(self.install_dir, 'site.py')\n source = resource_string('setuptools', 'site-patch.py')\n current = ''\n if os.path.exists(sitepy):\n log.debug('Checking existing site.py in %s', self.install_dir)\n f = open(sitepy, 'rb')\n current = f.read()\n if sys.version_info >= (3,):\n current = current.decode()\n f.close()\n if not current.startswith('def __boot():'):\n raise DistutilsError('%s is not a setuptools-generated site.py; please remove it.' % sitepy)\n if current != source:\n log.info('Creating %s', sitepy)\n if not self.dry_run:\n ensure_directory(sitepy)\n f = open(sitepy, 'wb')\n f.write(source)\n f.close()\n self.byte_compile([sitepy])\n self.sitepy_installed = True\n ", "context": "class easy_install(Command):\n def install_site_py(self): ...\n def initialize_options(self): ...\n def delete_blockers(self, blockers): ...\n def finalize_options(self): ...\n def _expand_attrs(self, attrs): ...\n def expand_basedirs(self): ...\n def expand_dirs(self): ...\n def run(self): ...\n def pseudo_tempname(self): ...\n def warn_deprecated_options(self): ...\n def check_site_dir(self): ...\n def cant_write_to_target(self): ...\n def check_pth_processing(self): ...\n def install_egg_scripts(self, dist): ...\n def add_output(self, path): ...\n def not_editable(self, spec): ...\n def check_editable(self, spec): ...\n def easy_install(self, spec, deps=False): ...\n def install_item(self, spec, download, tmpdir, deps, install_needed=False): ...\n def select_scheme(self, name): ...\n def process_distribution(self, requirement, dist, deps=True, *info): ...\n def should_unzip(self, dist): ...\n def maybe_move(self, spec, dist_filename, setup_base): ...\n def install_wrapper_scripts(self, dist): ...\n def install_script(self, dist, script_name, script_text, dev_path=None): ...\n def write_script(self, script_name, contents, mode='t', blockers=()): ...\n def install_eggs(self, spec, dist_filename, tmpdir): ...\n def egg_distribution(self, egg_path): ...\n def install_egg(self, egg_path, tmpdir): ...\n def install_exe(self, dist_filename, tmpdir): ...\n def exe_to_egg(self, dist_filename, egg_tmp): ...\n def installation_report(self, req, dist, what='Installed'): ...\n def report_editable(self, spec, setup_script): ...\n def run_setup(self, setup_script, setup_base, args): ...\n def build_and_install(self, setup_script, setup_base): ...\n def _set_fetcher_options(self, base): ...\n def update_pth(self, dist): ...\n def unpack_progress(self, src, dst): ...\n def unpack_and_compile(self, egg_path, destination): ...\n def byte_compile(self, to_compile): ...\n def no_default_version_msg(self): ...\n def create_home_path(self): ...\n def _expand(self, *attrs): ...\n\n description = 'Find/get/install Python packages'\n command_consumes_arguments = True\n user_options = [('prefix=', None, 'installation prefix'), ('zip-ok', 'z', 'install package as a zipfile'), ('multi-version', 'm', 'make apps have to require() a version'), ('upgrade', 'U', 'force upgrade (searches PyPI for latest versions)'), ('install-dir=', 'd', 'install package to DIR'), ('script-dir=', 's', 'install scripts to DIR'), ('exclude-scripts', 'x', \"Don't install scripts\"), ('always-copy', 'a', 'Copy all needed packages to install dir'), ('index-url=', 'i', 'base URL of Python Package Index'), ('find-links=', 'f', 'additional URL(s) to search for packages'), ('build-directory=', 'b', 'download/extract/build in DIR; keep the results'), ('optimize=', 'O', 'also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable [default: -O0]'), ('record=', None, 'filename in which to record list of installed files'), ('always-unzip', 'Z', \"don't install as a zipfile, no matter what\"), ('site-dirs=', 'S', 'list of directories where .pth files work'), ('editable', 'e', 'Install specified packages in editable form'), ('no-deps', 'N', \"don't install dependencies\"), ('allow-hosts=', 'H', 'pattern(s) that hostnames must match'), ('local-snapshots-ok', 'l', 'allow building eggs from local checkouts'), ('version', None, 'print version information and exit'), ('no-find-links', None, \"Don't load find-links defined in packages being installed\")]\n boolean_options = ['zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version']\n negative_opt = {'always-unzip': 'zip-ok'}\n create_index = PackageIndex\n INSTALL_SCHEMES = dict(posix=dict(install_dir='$base/lib/python$py_version_short/site-packages', script_dir='$base/bin'))\n DEFAULT_SCHEME = dict(install_dir='$base/Lib/site-packages', script_dir='$base/Scripts')\n", "repository": "dipivan/my-first-blog1", "test_name": "test_install_site_py", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000499.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/command/easy_install.py", "focal_class": null, "focal_method": "get_script_args", "tests": "import unittest\n\nclass Test_get_script_args(unittest.TestCase):\n def test_get_script_args(self):\n dist = FakeDist()\n old_platform = sys.platform\n try:\n name, script = [i for i in next(get_script_args(dist))][0:2]\n finally:\n sys.platform = old_platform\n self.assertEqual(script, WANTED)\n", "method_code": " def get_script_args(cls, dist, executable=sys_executable, wininst=False):\n \"\"\"\n Yield write_script() argument tuples for a distribution's entrypoints\n \"\"\"\n gen_class = cls.get_writer(wininst)\n spec = str(dist.as_requirement())\n header = get_script_header('', executable, wininst)\n for type_ in ('console', 'gui'):\n group = type_ + '_scripts'\n for name, ep in dist.get_entry_map(group).items():\n script_text = gen_class.template % locals()\n for res in gen_class._get_script_args(type_, name, header, script_text):\n yield res\n ", "context": "class ScriptWriter(object):\n @classmethod\n def get_script_args(cls, dist, executable=sys_executable, wininst=False): ...\n def get_writer(cls, force_windows): ...\n def _get_script_args(cls, type_, name, header, script_text): ...\n\n template = textwrap.dedent(\"\\n # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\\n __requires__ = %(spec)r\\n import sys\\n from pkg_resources import load_entry_point\\n\\n if __name__ == '__main__':\\n sys.exit(\\n load_entry_point(%(spec)r, %(group)r, %(name)r)()\\n )\\n \").lstrip()\n", "repository": "dipivan/my-first-blog1", "test_name": "test_get_script_args", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000500.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/command/easy_install.py", "focal_class": "easy_install", "focal_method": "easy_install", "tests": "import unittest\n\nclass Test_easy_install_easy_install(unittest.TestCase):\n def test_user_install_implied(self):\n site.ENABLE_USER_SITE = True\n dist = Distribution()\n dist.script_name = 'setup.py'\n cmd = easy_install(dist)\n cmd.args = ['py']\n cmd.ensure_finalized()\n self.assertTrue(cmd.user, 'user should be implied')\n", "method_code": " def easy_install(self, spec, deps=False):\n tmpdir = tempfile.mkdtemp(prefix='easy_install-')\n download = None\n if not self.editable:\n self.install_site_py()\n try:\n if not isinstance(spec, Requirement):\n if URL_SCHEME(spec):\n self.not_editable(spec)\n download = self.package_index.download(spec, tmpdir)\n return self.install_item(None, download, tmpdir, deps, True)\n elif os.path.exists(spec):\n self.not_editable(spec)\n return self.install_item(None, spec, tmpdir, deps, True)\n else:\n spec = parse_requirement_arg(spec)\n self.check_editable(spec)\n dist = self.package_index.fetch_distribution(spec, tmpdir, self.upgrade, self.editable, not self.always_copy, self.local_index)\n if dist is None:\n msg = 'Could not find suitable distribution for %r' % spec\n if self.always_copy:\n msg += ' (--always-copy skips system and development eggs)'\n raise DistutilsError(msg)\n elif dist.precedence == DEVELOP_DIST:\n self.process_distribution(spec, dist, deps, 'Using')\n return dist\n else:\n return self.install_item(spec, dist.location, tmpdir, deps)\n finally:\n if os.path.exists(tmpdir):\n rmtree(tmpdir)\n ", "context": "class easy_install(Command):\n def easy_install(self, spec, deps=False): ...\n def initialize_options(self): ...\n def delete_blockers(self, blockers): ...\n def finalize_options(self): ...\n def _expand_attrs(self, attrs): ...\n def expand_basedirs(self): ...\n def expand_dirs(self): ...\n def run(self): ...\n def pseudo_tempname(self): ...\n def warn_deprecated_options(self): ...\n def check_site_dir(self): ...\n def cant_write_to_target(self): ...\n def check_pth_processing(self): ...\n def install_egg_scripts(self, dist): ...\n def add_output(self, path): ...\n def not_editable(self, spec): ...\n def check_editable(self, spec): ...\n def install_item(self, spec, download, tmpdir, deps, install_needed=False): ...\n def select_scheme(self, name): ...\n def process_distribution(self, requirement, dist, deps=True, *info): ...\n def should_unzip(self, dist): ...\n def maybe_move(self, spec, dist_filename, setup_base): ...\n def install_wrapper_scripts(self, dist): ...\n def install_script(self, dist, script_name, script_text, dev_path=None): ...\n def write_script(self, script_name, contents, mode='t', blockers=()): ...\n def install_eggs(self, spec, dist_filename, tmpdir): ...\n def egg_distribution(self, egg_path): ...\n def install_egg(self, egg_path, tmpdir): ...\n def install_exe(self, dist_filename, tmpdir): ...\n def exe_to_egg(self, dist_filename, egg_tmp): ...\n def installation_report(self, req, dist, what='Installed'): ...\n def report_editable(self, spec, setup_script): ...\n def run_setup(self, setup_script, setup_base, args): ...\n def build_and_install(self, setup_script, setup_base): ...\n def _set_fetcher_options(self, base): ...\n def update_pth(self, dist): ...\n def unpack_progress(self, src, dst): ...\n def unpack_and_compile(self, egg_path, destination): ...\n def byte_compile(self, to_compile): ...\n def no_default_version_msg(self): ...\n def install_site_py(self): ...\n def create_home_path(self): ...\n def _expand(self, *attrs): ...\n\n description = 'Find/get/install Python packages'\n command_consumes_arguments = True\n user_options = [('prefix=', None, 'installation prefix'), ('zip-ok', 'z', 'install package as a zipfile'), ('multi-version', 'm', 'make apps have to require() a version'), ('upgrade', 'U', 'force upgrade (searches PyPI for latest versions)'), ('install-dir=', 'd', 'install package to DIR'), ('script-dir=', 's', 'install scripts to DIR'), ('exclude-scripts', 'x', \"Don't install scripts\"), ('always-copy', 'a', 'Copy all needed packages to install dir'), ('index-url=', 'i', 'base URL of Python Package Index'), ('find-links=', 'f', 'additional URL(s) to search for packages'), ('build-directory=', 'b', 'download/extract/build in DIR; keep the results'), ('optimize=', 'O', 'also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable [default: -O0]'), ('record=', None, 'filename in which to record list of installed files'), ('always-unzip', 'Z', \"don't install as a zipfile, no matter what\"), ('site-dirs=', 'S', 'list of directories where .pth files work'), ('editable', 'e', 'Install specified packages in editable form'), ('no-deps', 'N', \"don't install dependencies\"), ('allow-hosts=', 'H', 'pattern(s) that hostnames must match'), ('local-snapshots-ok', 'l', 'allow building eggs from local checkouts'), ('version', None, 'print version information and exit'), ('no-find-links', None, \"Don't load find-links defined in packages being installed\")]\n boolean_options = ['zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version']\n negative_opt = {'always-unzip': 'zip-ok'}\n create_index = PackageIndex\n INSTALL_SCHEMES = dict(posix=dict(install_dir='$base/lib/python$py_version_short/site-packages', script_dir='$base/bin'))\n DEFAULT_SCHEME = dict(install_dir='$base/Lib/site-packages', script_dir='$base/Scripts')\n", "repository": "dipivan/my-first-blog1", "test_name": "test_user_install_implied", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000501.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "url_ok", "tests": "import unittest\n\nclass Test_url_ok(unittest.TestCase):\n def test_url_ok(self):\n index = setuptools.package_index.PackageIndex(hosts=('www.example.com',))\n url = 'file:///tmp/test_package_index'\n self.assertTrue(index.url_ok(url, True))\n", "method_code": " def url_ok(self, url, fatal=False):\n s = URL_SCHEME(url)\n if s and s.group(1).lower() == 'file' or self.allows(urlparse(url)[1]):\n return True\n msg = '\\nNote: Bypassing %s (disallowed host; see http://bit.ly/1dg9ijs for details).\\n'\n if fatal:\n raise DistutilsError(msg % url)\n else:\n self.warn(msg, url)\n ", "context": "class PackageIndex(Environment):\n def url_ok(self, url, fatal=False): ...\n def __init__(self, index_url='https://pypi.python.org/simple', hosts=('*',), ca_bundle=None, verify_ssl=True, *args, **kw): ...\n def process_url(self, url, retrieve=False): ...\n def process_filename(self, fn, nested=False): ...\n def scan_egg_links(self, search_path): ...\n def scan_egg_link(self, path, entry): ...\n def process_index(self, url, page): ...\n def need_version_info(self, url): ...\n def scan_all(self, msg=None, *args): ...\n def find_packages(self, requirement): ...\n def obtain(self, requirement, installer=None): ...\n def check_hash(self, checker, filename, tfp): ...\n def add_find_links(self, urls): ...\n def prescan(self): ...\n def not_found_in_index(self, requirement): ...\n def download(self, spec, tmpdir): ...\n def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None): ...\n def fetch(self, requirement, tmpdir, force_scan=False, source=False): ...\n def gen_setup(self, filename, fragment, tmpdir): ...\n def _download_to(self, url, filename): ...\n def reporthook(self, url, filename, blocknum, blksize, size): ...\n def open_url(self, url, warning=None): ...\n def _download_url(self, scheme, url, tmpdir): ...\n def scan_url(self, url): ...\n def _attempt_download(self, url, filename): ...\n def _download_html(self, url, headers, filename): ...\n def _download_svn(self, url, filename): ...\n def _vcs_split_rev_from_url(url, pop_prefix=False): ...\n def _download_git(self, url, filename): ...\n def _download_hg(self, url, filename): ...\n def debug(self, msg, *args): ...\n def info(self, msg, *args): ...\n def warn(self, msg, *args): ...\n\n self.index_url = index_url + '/'[:not index_url.endswith('/')]\n self.scanned_urls = {}\n self.fetched_urls = {}\n self.package_pages = {}\n self.allows = re.compile('|'.join(map(translate, hosts))).match\n self.to_scan = []\n\n dl_blocksize = 8192\n", "repository": "dipivan/my-first-blog1", "test_name": "test_url_ok", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000502.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "parse_bdist_wininst", "tests": "import unittest\n\nclass Test_parse_bdist_wininst(unittest.TestCase):\n def test_parse_bdist_wininst(self):\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win32-py2.4.exe'), ('reportlab-2.5', '2.4', 'win32'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win32.exe'), ('reportlab-2.5', None, 'win32'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win-amd64-py2.7.exe'), ('reportlab-2.5', '2.7', 'win-amd64'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win-amd64.exe'), ('reportlab-2.5', None, 'win-amd64'))\n", "method_code": "def parse_bdist_wininst(name):\n \"\"\"Return (base,pyversion) or (None,None) for possible .exe name\"\"\"\n lower = name.lower()\n base, py_ver, plat = (None, None, None)\n if lower.endswith('.exe'):\n if lower.endswith('.win32.exe'):\n base = name[:-10]\n plat = 'win32'\n elif lower.startswith('.win32-py', -16):\n py_ver = name[-7:-4]\n base = name[:-16]\n plat = 'win32'\n elif lower.endswith('.win-amd64.exe'):\n base = name[:-14]\n plat = 'win-amd64'\n elif lower.startswith('.win-amd64-py', -20):\n py_ver = name[-7:-4]\n base = name[:-20]\n plat = 'win-amd64'\n return (base, py_ver, plat)", "context": "def parse_bdist_wininst(name): ...\ndef parse_bdist_wininst(name): ...\ndef egg_info_for_url(url): ...\ndef distros_for_url(url, metadata=None): ...\ndef distros_for_location(location, basename, metadata=None): ...\ndef distros_for_filename(filename, metadata=None): ...\ndef interpret_distro_name(location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None): ...\ndef unique_everseen(iterable, key=None): ...\ndef unique_values(func): ...\ndef find_external_links(url, page): ...\ndef uchr(c): ...\ndef decode_entity(match): ...\ndef htmldecode(text): ...\ndef socket_timeout(timeout=15): ...\ndef _encode_auth(auth): ...\ndef open_with_auth(url, opener=urllib2.urlopen): ...\ndef fix_sf_url(url): ...\ndef local_open(url): ...\n", "repository": "dipivan/my-first-blog1", "test_name": "test_parse_bdist_wininst", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000503.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "report", "tests": "import unittest\n\nclass Test_report(unittest.TestCase):\n def test_report(self):\n checker = setuptools.package_index.HashChecker.from_url('http://foo/bar#md5=f12895fdffbd45007040d2e44df98478')\n rep = checker.report(lambda x: x, 'My message about %s')\n self.assertEqual(rep, 'My message about md5')\n", "method_code": " def report(self, reporter, template):\n \"\"\"\n Call reporter with information about the checker (hash name)\n substituted into the template.\n \"\"\"\n return\n ", "context": "class ContentChecker(object):\n def report(self, reporter, template): ...\n def feed(self, block): ...\n def is_valid(self): ...\n", "repository": "dipivan/my-first-blog1", "test_name": "test_report", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000504.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/command/easy_install.py", "focal_class": null, "focal_method": "get_script_header", "tests": "import unittest\n\nclass Test_get_script_header(unittest.TestCase):\n def test_get_script_header(self):\n if not sys.platform.startswith('java') or not is_sh(sys.executable):\n expected = '#!%s\\n' % nt_quote_arg(os.path.normpath(sys.executable))\n self.assertEqual(get_script_header('#!/usr/local/bin/python'), expected)\n expected = '#!%s -x\\n' % nt_quote_arg(os.path.normpath(sys.executable))\n self.assertEqual(get_script_header('#!/usr/bin/python -x'), expected)\n self.assertEqual(get_script_header('#!/usr/bin/python', executable=self.non_ascii_exe), '#!%s -x\\n' % self.non_ascii_exe)\n candidate = get_script_header('#!/usr/bin/python', executable=self.exe_with_spaces)\n self.assertEqual(candidate, '#!\"%s\"\\n' % self.exe_with_spaces)\n\n def test_get_script_header_jython_workaround(self):\n if sys.version_info >= (3,) and os.environ.get('LC_CTYPE') in (None, 'C', 'POSIX'):\n return\n\n class java:\n\n class lang:\n\n class System:\n\n @staticmethod\n def getProperty(property):\n return ''\n sys.modules['java'] = java\n platform = sys.platform\n sys.platform = 'java1.5.0_13'\n stdout, stderr = (sys.stdout, sys.stderr)\n try:\n exe = os.path.normpath(os.path.splitext(__file__)[0] + '.py')\n self.assertEqual(get_script_header('#!/usr/local/bin/python', executable=exe), '#!/usr/bin/env %s\\n' % exe)\n sys.stdout = sys.stderr = StringIO()\n self.assertEqual(get_script_header('#!/usr/bin/python -x', executable=exe), '#!%s -x\\n' % exe)\n self.assertTrue('Unable to adapt shebang line' in sys.stdout.getvalue())\n sys.stdout = sys.stderr = StringIO()\n self.assertEqual(get_script_header('#!/usr/bin/python', executable=self.non_ascii_exe), '#!%s -x\\n' % self.non_ascii_exe)\n self.assertTrue('Unable to adapt shebang line' in sys.stdout.getvalue())\n finally:\n del sys.modules['java']\n sys.platform = platform\n sys.stdout, sys.stderr = (stdout, stderr)\n", "method_code": "def get_script_header(script_text, executable=sys_executable, wininst=False):\n \"\"\"Create a #! line, getting options (if any) from script_text\"\"\"\n from distutils.command.build_scripts import first_line_re\n if not isinstance(first_line_re.pattern, str):\n first_line_re = re.compile(first_line_re.pattern.decode())\n first = (script_text + '\\n').splitlines()[0]\n match = first_line_re.match(first)\n options = ''\n if match:\n options = match.group(1) or ''\n if options:\n options = ' ' + options\n if wininst:\n executable = 'python.exe'\n else:\n executable = nt_quote_arg(executable)\n hdr = '#!%(executable)s%(options)s\\n' % locals()\n if not isascii(hdr):\n if options:\n if options.strip().startswith('-'):\n options = ' -x' + options.strip()[1:]\n else:\n options = ' -x'\n executable = fix_jython_executable(executable, options)\n hdr = '#!%(executable)s%(options)s\\n' % locals()\n return hdr", "context": "def get_script_header(script_text, executable=sys_executable, wininst=False): ...\ndef is_64bit(): ...\ndef samefile(p1, p2): ...\ndef get_site_dirs(): ...\ndef expand_paths(inputs): ...\ndef extract_wininst_cfg(dist_filename): ...\ndef get_exe_prefixes(exe_filename): ...\ndef parse_requirement_arg(spec): ...\ndef get_script_header(script_text, executable=sys_executable, wininst=False): ...\ndef auto_chmod(func, arg, exc): ...\ndef uncache_zipdir(path): ...\ndef _uncache(path, cache): ...\ndef is_python(text, filename=''): ...\ndef is_sh(executable): ...\ndef nt_quote_arg(arg): ...\ndef is_python_script(script_text, filename): ...\ndef chmod(path, mode): ...\ndef fix_jython_executable(executable, options): ...\ndef get_win_launcher(type): ...\ndef load_launcher_manifest(name): ...\ndef rmtree(path, ignore_errors=False, onerror=auto_chmod): ...\ndef current_umask(): ...\ndef bootstrap(): ...\ndef main(argv=None, **kw): ...\n", "repository": "dipivan/my-first-blog1", "test_name": "test_get_script_header", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000505.py"} {"focal_file": "virtual/Lib/site-packages/setuptools/command/upload_docs.py", "focal_class": "upload_docs", "focal_method": "create_zipfile", "tests": "import unittest\n\nclass Test_upload_docs_create_zipfile(unittest.TestCase):\n def test_create_zipfile(self):\n dist = Distribution()\n cmd = upload_docs(dist)\n cmd.upload_dir = self.upload_dir\n cmd.target_dir = self.upload_dir\n tmp_dir = tempfile.mkdtemp()\n tmp_file = os.path.join(tmp_dir, 'foo.zip')\n try:\n zip_file = cmd.create_zipfile(tmp_file)\n assert zipfile.is_zipfile(tmp_file)\n zip_file = zipfile.ZipFile(tmp_file)\n assert zip_file.namelist() == ['index.html']\n zip_file.close()\n finally:\n shutil.rmtree(tmp_dir)\n", "method_code": " def create_zipfile(self, filename):\n zip_file = zipfile.ZipFile(filename, 'w')\n try:\n self.mkpath(self.target_dir)\n for root, dirs, files in os.walk(self.target_dir):\n if root == self.target_dir and (not files):\n raise DistutilsOptionError(\"no files found in upload directory '%s'\" % self.target_dir)\n for name in files:\n full = os.path.join(root, name)\n relative = root[len(self.target_dir):].lstrip(os.path.sep)\n dest = os.path.join(relative, name)\n zip_file.write(full, dest)\n finally:\n zip_file.close()\n ", "context": "class upload_docs(upload):\n def create_zipfile(self, filename): ...\n def has_sphinx(self): ...\n def initialize_options(self): ...\n def finalize_options(self): ...\n def run(self): ...\n def upload_file(self, filename): ...\n\n description = 'Upload documentation to PyPI'\n user_options = [('repository=', 'r', 'url of repository [default: %s]' % upload.DEFAULT_REPOSITORY), ('show-response', None, 'display full response text from server'), ('upload-dir=', None, 'directory to upload')]\n boolean_options = upload.boolean_options\n sub_commands = [('build_sphinx', has_sphinx)]\n", "repository": "dipivan/my-first-blog1", "test_name": "test_create_zipfile", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000506.py"} {"focal_file": "chainsaw/api.py", "focal_class": null, "focal_method": "load", "tests": "import unittest\n\nclass Test_load(unittest.TestCase):\n def test_various_formats_load(self):\n chunksizes = [0, 13]\n X = None\n bpti_mini_previous = None\n for cs in chunksizes:\n for bpti_mini in self.bpti_mini_files:\n Y = api.load(bpti_mini, top=self.bpti_pdbfile, chunk_size=cs)\n if X is not None:\n np.testing.assert_array_almost_equal(X, Y, err_msg='Comparing %s to %s failed for chunksize %s' % (bpti_mini, bpti_mini_previous, cs))\n X = Y\n bpti_mini_previous = bpti_mini\n", "method_code": "def load(trajfiles, features=None, top=None, stride=1, chunk_size=None, **kw):\n \"\"\" Loads coordinate features into memory.\n\n If your memory is not big enough consider the use of **pipeline**, or use\n the stride option to subsample the data.\n\n Parameters\n ----------\n trajfiles : str, list of str or nested list (one level) of str\n A filename or a list of filenames to trajectory files that can be\n processed by chainsaw. Both molecular dynamics trajectory files and raw\n data files (tabulated ASCII or binary) can be loaded.\n\n If a nested list of filenames is given, eg.:\n [['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]\n the grouped fragments will be treated as a joint trajectory.\n\n When molecular dynamics trajectory files are loaded either a featurizer\n must be specified (for reading specific quantities such as distances or\n dihedrals), or a topology file (in that case only Cartesian coordinates\n will be read). In the latter case, the resulting feature vectors will\n have length 3N for each trajectory frame, with N being the number of\n atoms and (x1, y1, z1, x2, y2, z2, ...) being the sequence of\n coordinates in the vector.\n\n Molecular dynamics trajectory files are loaded through mdtraj (http://mdtraj.org/latest/),\n and can possess any of the mdtraj-compatible trajectory formats\n including:\n\n * CHARMM/NAMD (.dcd)\n * Gromacs (.xtc)\n * Gromacs (.trr)\n * AMBER (.binpos)\n * AMBER (.netcdf)\n * PDB trajectory format (.pdb)\n * TINKER (.arc),\n * MDTRAJ (.hdf5)\n * LAMMPS trajectory format (.lammpstrj)\n\n Raw data can be in the following format:\n\n * tabulated ASCII (.dat, .txt)\n * binary python (.npy, .npz)\n\n features : MDFeaturizer, optional, default = None\n a featurizer object specifying how molecular dynamics files should\n be read (e.g. intramolecular distances, angles, dihedrals, etc).\n\n top : str, optional, default = None\n A molecular topology file, e.g. in PDB (.pdb) format\n\n stride : int, optional, default = 1\n Load only every stride'th frame. By default, every frame is loaded\n\n chunk_size: int, optional, default = 100\n The chunk size at which the input file is being processed.\n\n Returns\n -------\n data : ndarray or list of ndarray\n If a single filename was given as an input (and unless the format is\n .npz), the return will be a single ndarray of size (T, d), where T is\n the number of time steps in the trajectory and d is the number of features\n (coordinates, observables). When reading from molecular dynamics data\n without a specific featurizer, each feature vector will have size d=3N\n and will hold the Cartesian coordinates in the sequence\n (x1, y1, z1, x2, y2, z2, ...).\n If multiple filenames were given, or if the file is a .npz holding\n multiple arrays, the result is a list of appropriately shaped arrays\n\n See also\n --------\n :func:`chainsaw.source`\n if your memory is not big enough, specify data source and put it into your\n transformation or clustering algorithms instead of the loaded data. This\n will stream the data and save memory on the cost of longer processing\n times.\n\n Examples\n --------\n\n >>> from chainsaw import load\n >>> files = ['traj01.xtc', 'traj02.xtc'] # doctest: +SKIP\n >>> output = load(files, top='my_structure.pdb') # doctest: +SKIP\n\n \"\"\"\n from chainsaw.data.util.reader_utils import create_file_reader\n if isinstance(trajfiles, _string_types) or (isinstance(trajfiles, (list, tuple)) and (any((isinstance(item, (list, tuple, _string_types)) for item in trajfiles)) or len(trajfiles) is 0)):\n reader = create_file_reader(trajfiles, top, features, chunk_size=chunk_size if chunk_size is not None else 0, **kw)\n trajs = reader.get_output(stride=stride)\n if len(trajs) == 1:\n return trajs[0]\n else:\n return trajs\n else:\n raise ValueError('unsupported type (%s) of input' % type(trajfiles))", "context": "def load(trajfiles, features=None, top=None, stride=1, chunk_size=None, **kw): ...\ndef featurizer(topfile): ...\ndef load(trajfiles, features=None, top=None, stride=1, chunk_size=None, **kw): ...\ndef source(inp, features=None, top=None, chunk_size=None, **kw): ...\ndef pipeline(stages, run=True, stride=1, chunksize=1000): ...\ndef discretizer(reader, transform=None, cluster=None, run=True, stride=1, chunksize=1000): ...\ndef save_traj(traj_inp, indexes, outfile, top=None, stride=1, chunksize=1000, image_molecules=False, verbose=False): ...\ndef save_trajs(traj_inp, indexes, prefix='set_', fmt=None, outfiles=None, inmemory=False, stride=1, verbose=False): ...\ndef _get_input_stage(previous_stage): ...\ndef _param_stage(previous_stage, this_stage, stride=1, chunk_size=None): ...\ndef pca(data=None, dim=-1, var_cutoff=0.95, stride=1, mean=None, skip=0): ...\ndef tica(data=None, lag=10, dim=-1, var_cutoff=0.95, kinetic_map=True, stride=1, force_eigenvalues_le_one=False, mean=None, remove_mean=True, skip=0): ...\ndef cluster_mini_batch_kmeans(data=None, k=100, max_iter=10, batch_size=0.2, metric='euclidean', init_strategy='kmeans++', n_jobs=None, chunk_size=5000, skip=0): ...\ndef cluster_kmeans(data=None, k=None, max_iter=10, tolerance=1e-05, stride=1, metric='euclidean', init_strategy='kmeans++', fixed_seed=False, n_jobs=None, chunk_size=5000, skip=0): ...\ndef cluster_uniform_time(data=None, k=None, stride=1, metric='euclidean', n_jobs=None, chunk_size=5000, skip=0): ...\ndef cluster_regspace(data=None, dmin=-1, max_centers=1000, stride=1, metric='euclidean', n_jobs=None, chunk_size=5000, skip=0): ...\ndef assign_to_centers(data=None, centers=None, stride=1, return_dtrajs=True, metric='euclidean', n_jobs=None, chunk_size=5000, skip=0): ...\n", "repository": "markovmodel/coordinates", "test_name": "test_various_formats_load", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000507.py"} {"focal_file": "chainsaw/api.py", "focal_class": null, "focal_method": "source", "tests": "import unittest\n\nclass Test_source(unittest.TestCase):\n def test_various_formats_source(self):\n chunksizes = [0, 13]\n X = None\n bpti_mini_previous = None\n for cs in chunksizes:\n for bpti_mini in self.bpti_mini_files:\n Y = api.source(bpti_mini, top=self.bpti_pdbfile).get_output(chunk=cs)\n if X is not None:\n np.testing.assert_array_almost_equal(X, Y, err_msg='Comparing %s to %s failed for chunksize %s' % (bpti_mini, bpti_mini_previous, cs))\n X = Y\n bpti_mini_previous = bpti_mini\n", "method_code": "def source(inp, features=None, top=None, chunk_size=None, **kw):\n \"\"\" Defines trajectory data source\n\n This function defines input trajectories without loading them. You can pass\n the resulting object into transformers such as :func:`chainsaw.tica`\n or clustering algorithms such as :func:`chainsaw.cluster_kmeans`.\n Then, the data will be streamed instead of being loaded, thus saving memory.\n\n You can also use this function to construct the first stage of a data\n processing :func:`pipeline`.\n\n Parameters\n ----------\n inp : str (file name) or ndarray or list of strings (file names) or list of ndarrays or nested list of str|ndarray (1 level)\n The inp file names or input data. Can be given in any of\n these ways:\n\n 1. File name of a single trajectory. It can have any of the molecular\n dynamics trajectory formats or raw data formats specified in :py:func:`load`.\n 2. List of trajectory file names. It can have any of the molecular\n dynamics trajectory formats or raw data formats specified in :py:func:`load`.\n 3. Molecular dynamics trajectory in memory as a numpy array of shape\n (T, N, 3) with T time steps, N atoms each having three (x,y,z)\n spatial coordinates.\n 4. List of molecular dynamics trajectories in memory, each given as a\n numpy array of shape (T_i, N, 3), where trajectory i has T_i time\n steps and all trajectories have shape (N, 3).\n 5. Trajectory of some features or order parameters in memory\n as a numpy array of shape (T, N) with T time steps and N dimensions.\n 6. List of trajectories of some features or order parameters in memory,\n each given as a numpy array of shape (T_i, N), where trajectory i\n has T_i time steps and all trajectories have N dimensions.\n 7. List of NumPy array files (.npy) of shape (T, N). Note these\n arrays are not being loaded completely, but mapped into memory\n (read-only).\n 8. List of tabulated ASCII files of shape (T, N).\n 9. Nested lists (1 level) like), eg.:\n [['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]\n the grouped fragments will be treated as a joint trajectory.\n\n features : MDFeaturizer, optional, default = None\n a featurizer object specifying how molecular dynamics files should be\n read (e.g. intramolecular distances, angles, dihedrals, etc). This\n parameter only makes sense if the input comes in the form of molecular\n dynamics trajectories or data, and will otherwise create a warning and\n have no effect.\n\n top : str, optional, default = None\n A topology file name. This is needed when molecular dynamics\n trajectories are given and no featurizer is given.\n In this case, only the Cartesian coordinates will be read.\n\n chunk_size: int, optional, default = 100 for file readers and 5000 for\n already loaded data The chunk size at which the input file is being\n processed.\n\n Returns\n -------\n reader : :class:`DataSource ` object\n\n See also\n --------\n :func:`chainsaw.load`\n If your memory is big enough to load all features into memory, don't\n bother using source - working in memory is faster!\n\n :func:`chainsaw.pipeline`\n The data input is the first stage for your pipeline. Add other stages\n to it and build a pipeline to analyze big data in streaming mode.\n\n Examples\n --------\n\n Create a reader for NumPy files:\n\n >>> import numpy as np\n >>> from chainsaw import source\n >>> reader = source(['001.npy', '002.npy'] # doctest: +SKIP\n\n Create a reader for trajectory files and select some distance as feature:\n\n >>> reader = source(['traj01.xtc', 'traj02.xtc'], top='my_structure.pdb') # doctest: +SKIP\n >>> reader.featurizer.add_distances([[0, 1], [5, 6]]) # doctest: +SKIP\n >>> calculated_features = reader.get_output() # doctest: +SKIP\n\n create a reader for a csv file:\n\n >>> reader = source('data.csv') # doctest: +SKIP\n\n Create a reader for huge NumPy in-memory arrays to process them in\n huge chunks to avoid memory issues:\n\n >>> data = np.random.random(int(1e7))\n >>> reader = source(data, chunk_size=5000)\n >>> from chainsaw import cluster_regspace\n >>> regspace = cluster_regspace(reader, dmin=0.1)\n\n Returns\n -------\n\n reader : a reader instance\n\n .. autoclass:: chainsaw.data.interface.ReaderInterface\n :members:\n :undoc-members:\n\n .. rubric:: Methods\n\n .. autoautosummary:: chainsaw.data.interface.ReaderInterface\n :methods:\n\n .. rubric:: Attributes\n\n .. autoautosummary:: chainsaw.data.interface.ReaderInterface\n :attributes:\n\n \"\"\"\n from chainsaw.data.util.reader_utils import create_file_reader\n if isinstance(inp, _string_types) or (isinstance(inp, (list, tuple)) and (any((isinstance(item, (list, tuple, _string_types)) for item in inp)) or len(inp) is 0)):\n reader = create_file_reader(inp, top, features, chunk_size=chunk_size if chunk_size is not None else 100, **kw)\n elif isinstance(inp, _np.ndarray) or (isinstance(inp, (list, tuple)) and (any((isinstance(item, _np.ndarray) for item in inp)) or len(inp) is 0)):\n from chainsaw.data.data_in_memory import DataInMemory as _DataInMemory\n reader = _DataInMemory(inp, chunksize=chunk_size if chunk_size else 5000, **kw)\n else:\n raise ValueError('unsupported type (%s) of input' % type(inp))\n return reader", "context": "def source(inp, features=None, top=None, chunk_size=None, **kw): ...\ndef featurizer(topfile): ...\ndef load(trajfiles, features=None, top=None, stride=1, chunk_size=None, **kw): ...\ndef source(inp, features=None, top=None, chunk_size=None, **kw): ...\ndef pipeline(stages, run=True, stride=1, chunksize=1000): ...\ndef discretizer(reader, transform=None, cluster=None, run=True, stride=1, chunksize=1000): ...\ndef save_traj(traj_inp, indexes, outfile, top=None, stride=1, chunksize=1000, image_molecules=False, verbose=False): ...\ndef save_trajs(traj_inp, indexes, prefix='set_', fmt=None, outfiles=None, inmemory=False, stride=1, verbose=False): ...\ndef _get_input_stage(previous_stage): ...\ndef _param_stage(previous_stage, this_stage, stride=1, chunk_size=None): ...\ndef pca(data=None, dim=-1, var_cutoff=0.95, stride=1, mean=None, skip=0): ...\ndef tica(data=None, lag=10, dim=-1, var_cutoff=0.95, kinetic_map=True, stride=1, force_eigenvalues_le_one=False, mean=None, remove_mean=True, skip=0): ...\ndef cluster_mini_batch_kmeans(data=None, k=100, max_iter=10, batch_size=0.2, metric='euclidean', init_strategy='kmeans++', n_jobs=None, chunk_size=5000, skip=0): ...\ndef cluster_kmeans(data=None, k=None, max_iter=10, tolerance=1e-05, stride=1, metric='euclidean', init_strategy='kmeans++', fixed_seed=False, n_jobs=None, chunk_size=5000, skip=0): ...\ndef cluster_uniform_time(data=None, k=None, stride=1, metric='euclidean', n_jobs=None, chunk_size=5000, skip=0): ...\ndef cluster_regspace(data=None, dmin=-1, max_centers=1000, stride=1, metric='euclidean', n_jobs=None, chunk_size=5000, skip=0): ...\ndef assign_to_centers(data=None, centers=None, stride=1, return_dtrajs=True, metric='euclidean', n_jobs=None, chunk_size=5000, skip=0): ...\n", "repository": "markovmodel/coordinates", "test_name": "test_various_formats_source", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000508.py"} {"focal_file": "chainsaw/util/types.py", "focal_class": null, "focal_method": "is_int_matrix", "tests": "import unittest\n\nclass Test_is_int_matrix(unittest.TestCase):\n def test_iterator(self):\n c = self.ass\n for itraj, chunk in c:\n assert types.is_int(itraj)\n assert types.is_int_matrix(chunk)\n assert chunk.shape[0] <= c.chunksize or c.chunksize == 0\n assert chunk.shape[1] == c.dimension()\n", "method_code": "def is_int_matrix(l):\n \"\"\"Checks if l is a numpy array of floats\n\n \"\"\"\n if isinstance(l, np.ndarray):\n if l.ndim == 2 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n return True\n return False", "context": "def is_int_matrix(l): ...\ndef is_int(l): ...\ndef is_float(l): ...\ndef is_iterable_of_int(l): ...\ndef is_list_of_int(l): ...\ndef is_tuple_of_int(l): ...\ndef is_iterable_of_float(l): ...\ndef is_list_of_float(l): ...\ndef is_tuple_of_float(l): ...\ndef is_int_vector(l): ...\ndef is_int_matrix(l): ...\ndef is_float_vector(l): ...\ndef is_float_matrix(l): ...\ndef is_bool_matrix(l): ...\ndef is_float_array(l): ...\ndef is_string(s): ...\ndef is_iterable(I): ...\ndef is_list(S): ...\ndef is_list_of_string(S): ...\ndef ensure_dtraj(dtraj): ...\ndef ensure_dtraj_list(dtrajs): ...\ndef ensure_int_vector(I, require_order=False): ...\ndef ensure_int_vector_or_None(F, require_order=False): ...\ndef ensure_float_vector(F, require_order=False): ...\ndef ensure_float_vector_or_None(F, require_order=False): ...\ndef ensure_dtype_float(x, default=np.float64): ...\ndef assert_square_matrix(A): ...\ndef assert_array(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): ...\ndef ensure_ndarray(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): ...\ndef ensure_ndarray_or_sparse(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): ...\ndef ensure_ndarray_or_None(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): ...\ndef ensure_traj(traj): ...\ndef ensure_traj_list(trajs): ...\n", "repository": "markovmodel/coordinates", "test_name": "test_iterator", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000509.py"} {"focal_file": "chainsaw/data/cache.py", "focal_class": "Cache", "focal_method": "get_output", "tests": "import unittest\n\nclass Test_Cache_get_output(unittest.TestCase):\n def test_get_output(self):\n src = chainsaw.source(self.files, chunk_size=0)\n dim = 1\n stride = 2\n skip = 3\n desired = src.get_output(stride=stride, dimensions=dim, skip=skip)\n cache = Cache(src)\n actual = cache.get_output(stride=stride, dimensions=dim, skip=skip)\n np.testing.assert_allclose(actual, desired)\n\n def test_tica_cached_output(self):\n src = chainsaw.source(self.files, chunk_size=0)\n tica = chainsaw.tica(src, dim=2)\n tica_output = tica.get_output()\n cache = Cache(tica)\n np.testing.assert_allclose(cache.get_output(), tica_output)\n", "method_code": " def get_output(self, dimensions=slice(0, None), stride=1, skip=0, chunk=None):\n if isinstance(dimensions, int):\n ndim = 1\n dimensions = slice(dimensions, dimensions + 1)\n elif isinstance(dimensions, (list, np.ndarray, tuple, slice)):\n if hasattr(dimensions, 'ndim') and dimensions.ndim > 1:\n raise ValueError(\"dimension indices can't have more than one dimension\")\n ndim = len(np.zeros(self.ndim)[dimensions])\n else:\n raise ValueError('unsupported type (%s) of \"dimensions\"' % type(dimensions))\n assert ndim > 0, 'ndim was zero in %s' % self.__class__.__name__\n dim_inds = dimensions.indices(1)\n self.logger.debug('dim slice: {}; dim inds: {}'.format(dimensions, dim_inds))\n res = [traj[skip::stride, dimensions] for traj in self.data]\n assert all((isinstance(o, np.ndarray) for o in res))\n return res\n ", "context": "class Cache(DataSource):\n def get_output(self, dimensions=slice(0, None), stride=1, skip=0, chunk=None): ...\n def __init__(self, data_source, chunksize=1000, fill_cache=True): ...\n def data(self): ...\n def data_producer(self): ...\n def data_producer(self, val): ...\n def input_description(self): ...\n def current_cache_file_name(self): ...\n def _create_iterator(self, skip=0, chunk=0, stride=1, return_trajindex=True, cols=None): ...\n def __len__(self): ...\n def __repr__(self): ...\n\n self.data_producer = data_source\n self._real_reader = reader\n self._cache_files = {}\n self._ndim = self.data_producer.ndim\n self._ntraj = self.data_producer.ntraj\n self._lengths = self.data_producer.trajectory_lengths()\n", "repository": "markovmodel/coordinates", "test_name": "test_get_output", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000510.py"} {"focal_file": "chainsaw/data/py_csv_reader.py", "focal_class": null, "focal_method": "reset", "tests": "import unittest\n\nclass Test_reset(unittest.TestCase):\n def test_reset(self):\n reader = CSVReader((self.filename1, self.filename2))\n it = reader.iterator()\n data = [chunk for chunk in it]\n it.reset()\n data2 = [chunk for chunk in it]\n np.testing.assert_equal(data, data2)\n", "method_code": " def reset(self):\n super(PyCSVIterator, self).reset()\n self._itraj = -1\n self._next_traj()\n ", "context": "class PyCSVIterator(DataSourceIterator):\n def reset(self): ...\n def __init__(self, data_source, skip=0, chunk=0, stride=1, return_trajindex=False, cols=None): ...\n def close(self): ...\n def _next_chunk(self): ...\n def _next_traj(self): ...\n def _convert_to_np_chunk(self, list_of_strings): ...\n def _open_file(self): ...\n\n self._custom_cols = cols\n self._skip_rows = np.empty(0) if self._skip_rows is None else np.unique(self._skip_rows)\n self.line = 0\n self._reader = csv.reader(self._file_handle, dialect=self._data_source._get_dialect(self._itraj))\n", "repository": "markovmodel/coordinates", "test_name": "test_reset", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000511.py"} {"focal_file": "chainsaw/data/md/featurization/util.py", "focal_class": null, "focal_method": "_describe_atom", "tests": "import unittest\n\nclass Test_describe_atom(unittest.TestCase):\n def test_describe_atom(self):\n str1 = _describe_atom(self.traj.topology, 0)\n str2 = _describe_atom(self.traj.topology, self.traj.n_atoms - 1)\n assert len(str1.split()) >= 4\n assert len(str2.split()) >= 4\n assert str1.split()[-1] == '0'\n assert str2.split()[-1] == '1'\n", "method_code": "def _describe_atom(topology, index):\n \"\"\"\n Returns a string describing the given atom\n\n :param topology:\n :param index:\n :return:\n \"\"\"\n at = topology.atom(index)\n if topology.n_chains > 1:\n return '%s %i %s %i %i' % (at.residue.name, at.residue.resSeq, at.name, at.index, at.residue.chain.index)\n else:\n return '%s %i %s %i' % (at.residue.name, at.residue.resSeq, at.name, at.index)", "context": "def _describe_atom(topology, index): ...\ndef _describe_atom(topology, index): ...\ndef _catch_unhashable(x): ...\ndef hash_top(top): ...\ndef _parse_pairwise_input(indices1, indices2, MDlogger, fname=''): ...\ndef _parse_groupwise_input(group_definitions, group_pairs, MDlogger, mname=''): ...\n", "repository": "markovmodel/coordinates", "test_name": "test_describe_atom", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000512.py"} {"focal_file": "chainsaw/data/util/fileformat_registry.py", "focal_class": null, "focal_method": "register", "tests": "import unittest\n\nclass Test_register(unittest.TestCase):\n def test_multiple_calls_register(self):\n with self.assertRaises(RuntimeError) as exc:\n\n @FileFormatRegistry.register('.foo')\n @FileFormatRegistry.register('.bar')\n class test_src:\n pass\n self.assertIn('only once', exc.exception.args[0])\n", "method_code": " def register(cls, *args):\n \"\"\" register the given class as Reader class for given extension(s). \"\"\"\n \n def decorator(f):\n if hasattr(f, 'SUPPORTED_EXTENSIONS') and f.SUPPORTED_EXTENSIONS is not ():\n raise RuntimeError('please call register() only once per class!')\n extensions = tuple(args)\n cls._readers.update({e: f for e in extensions})\n f.SUPPORTED_EXTENSIONS = extensions\n return f\n return decorator\n ", "context": "class FileFormatRegistry(object):\n @classmethod\n def register(cls, *args): ...\n def is_md_format(extension): ...\n def supported_extensions(self): ...\n def __getitem__(self, item): ...\n\n _readers = {}\n", "repository": "markovmodel/coordinates", "test_name": "test_multiple_calls_register", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000513.py"} {"focal_file": "chainsaw/data/fragmented_trajectory_reader.py", "focal_class": "FragmentedTrajectoryReader", "focal_method": "_index_to_reader_index", "tests": "import unittest\n\nclass Test_FragmentedTrajectoryReader_index_to_reader_index(unittest.TestCase):\n def test_index_to_reader_index(self):\n reader = FragmentedTrajectoryReader([self.d, self.d])\n assert (0, 0) == reader._index_to_reader_index(0, 0), 'first frame is first frame of first reader'\n assert (0, 1) == reader._index_to_reader_index(1, 0), 'second frame is second frame of first reader'\n assert (1, 0) == reader._index_to_reader_index(100, 0), \"101'st frame is first frame of second reader\"\n assert (1, 1) == reader._index_to_reader_index(101, 0), \"102'nd frame is second frame of second reader\"\n with self.assertRaises(ValueError):\n reader._index_to_reader_index(-1, 0)\n with self.assertRaises(ValueError):\n reader._index_to_reader_index(200, 0)\n", "method_code": " def _index_to_reader_index(self, index, itraj):\n \"\"\"\n Accepts an index parameter in [0, sum(reader_lenghts)) and returns a tuple (reader_index, local_index),\n where the tuple (reader_index, local_index) corresponds to the global frame index of the fragmented trajectory.\n :param index: the global index\n :return: a tuple (reader_index, local_index)\n \"\"\"\n prev_len = 0\n for readerIndex, length in enumerate(self._cumulative_lengths[itraj]):\n if prev_len <= index < length:\n return (readerIndex, index - prev_len)\n prev_len = length\n raise ValueError('Requested index %s was out of bounds [0,%s)' % (index, self._cumulative_lengths[itraj][-1]))\n ", "context": "class FragmentedTrajectoryReader(DataSource):\n def _index_to_reader_index(self, index, itraj): ...\n def __init__(self, trajectories, topologyfile=None, chunksize=1000, featurizer=None): ...\n def filenames_flat(self): ...\n def reader_by_filename(self, filename): ...\n def _create_iterator(self, skip=0, chunk=0, stride=1, return_trajindex=True, cols=None): ...\n def describe(self): ...\n def dimension(self): ...\n def _get_traj_info(self, filename): ...\n\n self._is_reader = True\n self._ntraj = len(trajectories)\n self._readers = [[source(input_item, features=featurizer, top=topologyfile, chunk_size=chunksize) for input_item in trajectories[itraj]] for itraj in range(0, self._ntraj)]\n self._reader_by_filename = {}\n self._reader_lengths = [[reader.trajectory_length(0, 1) for reader in self._readers[itraj]] for itraj in range(0, self._ntraj)]\n self._lengths = [sum(self._reader_lengths[itraj]) for itraj in range(0, self._ntraj)]\n self._cumulative_lengths = [np.cumsum(self._reader_lengths[itraj]) for itraj in range(0, self._ntraj)]\n self._trajectories = trajectories\n self._filenames = trajectories\n", "repository": "markovmodel/coordinates", "test_name": "test_index_to_reader_index", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000514.py"} {"focal_file": "chainsaw/data/util/traj_info_cache.py", "focal_class": null, "focal_method": "instance", "tests": "import unittest\n\nclass Test_instance(unittest.TestCase):\n def test_get_instance(self):\n inst = TrajectoryInfoCache.instance()\n inst.current_db_version\n self.assertIs(inst, self.db)\n", "method_code": " def instance():\n \"\"\" :returns the TrajectoryInfoCache singleton instance\"\"\"\n if TrajectoryInfoCache._instance is None:\n if not config.cfg_dir:\n filename = None\n else:\n filename = os.path.join(config.cfg_dir, 'traj_info.sqlite3')\n TrajectoryInfoCache._instance = TrajectoryInfoCache(filename)\n return TrajectoryInfoCache._instance\n ", "context": "class TrajectoryInfoCache(object):\n @staticmethod\n def instance(): ...\n def __init__(self, database_filename=None): ...\n def current_db_version(self): ...\n def num_entries(self): ...\n def _handle_csv(self, reader, filename, length): ...\n def __getitem__(self, filename_reader_tuple): ...\n def _get_file_hash(self, filename): ...\n def _get_file_hash_v2(self, filename): ...\n def hash_file(self, filename): ...\n def __setitem__(self, traj_info): ...\n def clear(self): ...\n def close(self): ...\n\n self.database_filename = database_filename\n\n _instance = None\n DB_VERSION = 2\n", "repository": "markovmodel/coordinates", "test_name": "test_get_instance", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000515.py"} {"focal_file": "nd_okta_auth/factor/push.py", "focal_class": null, "focal_method": "name", "tests": "import unittest\n\nclass Test_name(unittest.TestCase):\n def test_push_name(self):\n push_factor = factor.PushFactor('foobar')\n self.assertEqual('push', push_factor.name())\n", "method_code": " def name(self):\n return 'push'\n ", "context": "class PushFactor(Factor):\n def name(self): ...\n def verify(self, fid, state_token, sleep): ...\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_push_name", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000516.py"} {"focal_file": "nd_okta_auth/factor/totp.py", "focal_class": null, "focal_method": "name", "tests": "import unittest\n\nclass Test_name(unittest.TestCase):\n def test_totp_name(self):\n totp_factor = factor.TotpFactor('foobar')\n self.assertEqual('token:software:totp', totp_factor.name())\n", "method_code": " def name(self):\n return 'token:software:totp'\n ", "context": "class TotpFactor(Factor):\n def name(self): ...\n def get_passcode(self): ...\n def verify(self, fid, state_token, sleep): ...\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_totp_name", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000517.py"} {"focal_file": "nd_okta_auth/factor/u2f.py", "focal_class": null, "focal_method": "name", "tests": "import unittest\n\nclass Test_name(unittest.TestCase):\n def test_push_name(self):\n u2f_factor = factor.U2fFactor('foobar')\n self.assertEqual('u2f', u2f_factor.name())\n", "method_code": " def name(self):\n return 'u2f'\n ", "context": "class U2fFactor(Factor):\n def name(self): ...\n def _get_devices(self): ...\n def _get_client(self, dev, appId): ...\n def verify(self, fid, state_token, sleep): ...\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_push_name", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000518.py"} {"focal_file": "nd_okta_auth/factor/webauthn.py", "focal_class": null, "focal_method": "name", "tests": "import unittest\n\nclass Test_name(unittest.TestCase):\n def test_push_name(self):\n webauthn = factor.WebauthnFactor('foobar')\n self.assertEqual('webauthn', webauthn.name())\n", "method_code": " def name(self):\n return 'webauthn'\n ", "context": "class WebauthnFactor(Factor):\n def name(self): ...\n def _get_devices(self): ...\n def _get_client(self, dev, appId): ...\n def verify(self, fid, state_token, sleep): ...\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_push_name", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000519.py"} {"focal_file": "nd_okta_auth/auth.py", "focal_class": null, "focal_method": "user_input", "tests": "import unittest\n\nclass Test_user_input(unittest.TestCase):\n @mock.patch('nd_okta_auth.auth.input')\n def test_input(self, mock_input):\n mock_input.return_value = 'test'\n self.assertEqual('test', user_input('input test'))\n", "method_code": "def user_input(text):\n \"\"\"Wraps input() making testing support of py2 and py3 easier\"\"\"\n return input(text)", "context": "def user_input(text): ...\ndef user_input(text): ...\ndef setup_logging(): ...\ndef login(aws_profile: str, okta_appid: str, okta_org: str, username: str, reup: bool, debug: bool=False): ...\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000520.py"} {"focal_file": "nd_okta_auth/aws.py", "focal_class": "nd_okta_auth.aws.Credentials", "focal_method": "add_profile", "tests": "import unittest\n\nclass Test_nd_okta_auth_aws_Credentials_add_profile(unittest.TestCase):\n @mock.patch('nd_okta_auth.aws.os.chmod')\n @mock.patch('configparser.ConfigParser')\n @mock.patch('nd_okta_auth.aws.open')\n def test_add_profile(self, open_mock, parser_mock, chmod_mock):\n fake_parser = mock.MagicMock(name='config_parser')\n parser_mock.return_value = fake_parser\n fake_parser.has_section.return_value = None\n profile = aws.Credentials('/test')\n profile.add_profile(name='TestProfile', region='us-east-1', access_key='key', secret_key='secret', session_token='token')\n fake_parser.assert_has_calls([mock.call.has_section('TestProfile'), mock.call.add_section('TestProfile'), mock.call.set('TestProfile', 'region', 'us-east-1'), mock.call.set('TestProfile', 'aws_session_token', 'token'), mock.call.set('TestProfile', 'aws_security_token', 'token'), mock.call.set('TestProfile', 'aws_secret_access_key', 'secret'), mock.call.set('TestProfile', 'output', 'json'), mock.call.set('TestProfile', 'aws_access_key_id', 'key')], any_order=True)\n", "method_code": " def add_profile(self, name, region, access_key, secret_key, session_token):\n \"\"\"Writes out a set of AWS Credentials to disk.\n \n args:\n name: The profile name to write to\n region: The region to use as the default region for this profile\n access_key: The AWS_ACCESS_KEY_ID\n secret_key: The AWS_SECRET_ACCESS_KEY\n session_token: The AWS_SESSION_TOKEN\n \"\"\"\n name = str(name)\n self._add_profile(name, {'output': 'json', 'region': str(region), 'aws_access_key_id': str(access_key), 'aws_secret_access_key': str(secret_key), 'aws_security_token': str(session_token), 'aws_session_token': str(session_token)})\n log.info('Wrote profile \"{name}\" to {file}'.format(name=name, file=self.filename))\n ", "context": "class Credentials(object):\n def add_profile(self, name, region, access_key, secret_key, session_token): ...\n def __init__(self, filename): ...\n def _add_profile(self, name, profile): ...\n\n self.filename = filename\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000521.py"} {"focal_file": "nd_okta_auth/aws.py", "focal_class": "nd_okta_auth.aws.Session", "focal_method": "_write", "tests": "import unittest\n\nclass Test_nd_okta_auth_aws_Session_write(unittest.TestCase):\n @mock.patch('nd_okta_auth.aws.Credentials.add_profile')\n def test_write(self, mock_add_profile):\n session = aws.Session('BogusAssertion')\n ret = session._write()\n self.assertEquals(None, ret)\n mock_add_profile.assert_has_calls([mock.call(access_key=None, name='default', region='us-east-1', secret_key=None, session_token=None)])\n", "method_code": " def _write(self):\n \"\"\"Writes out our secrets to the Credentials object\"\"\"\n self.writer.add_profile(name=self.profile, region=self.region, access_key=self.aws_access_key_id, secret_key=self.aws_secret_access_key, session_token=self.session_token)\n log.info('Session expires at {time}'.format(time=self.expiration))\n ", "context": "class Session(object):\n def _write(self): ...\n def __init__(self, assertion, credential_path='~/.aws', profile='default', region='us-east-1'): ...\n def is_valid(self): ...\n def set_role(self, role_index): ...\n def available_roles(self): ...\n def assume_role(self): ...\n\n self.sts = boto3.client('sts')\n self.profile = profile\n self.region = region\n self.assertion = SamlAssertion(assertion)\n self.writer = Credentials(cred_file)\n self.aws_access_key_id = None\n self.aws_secret_access_key = None\n self.aws_session_token = None\n self.expiration = None\n self.session_token = None\n self.role = None\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000522.py"} {"focal_file": "nd_okta_auth/aws.py", "focal_class": "nd_okta_auth.aws.Session", "focal_method": "assume_role", "tests": "import unittest\n\nclass Test_nd_okta_auth_aws_Session_assume_role(unittest.TestCase):\n @mock.patch('nd_okta_auth.aws.Session._write')\n def test_assume_role(self, mock_write):\n mock_write.return_value = None\n assertion = mock.Mock()\n assertion.roles.return_value = [{'role': '', 'principle': ''}]\n session = aws.Session('BogusAssertion')\n session.assertion = assertion\n sts = {'Credentials': {'AccessKeyId': 'AKI', 'SecretAccessKey': 'squirrel', 'SessionToken': 'token', 'Expiration': 'never'}}\n session.sts = mock.Mock()\n session.sts.assume_role_with_saml.return_value = sts\n ret = session.assume_role()\n self.assertEquals(None, ret)\n self.assertEquals('AKI', session.aws_access_key_id)\n self.assertEquals('squirrel', session.aws_secret_access_key)\n self.assertEquals('token', session.session_token)\n self.assertEquals('never', session.expiration)\n mock_write.assert_has_calls([mock.call()])\n\n @mock.patch('nd_okta_auth.aws.Session._write')\n def test_assume_role_multiple(self, mock_write):\n mock_write.return_value = None\n assertion = mock.Mock()\n roles = [{'role': '1', 'principle': ''}, {'role': '2', 'principle': ''}]\n assertion.roles.return_value = roles\n session = aws.Session('BogusAssertion')\n session.assertion = assertion\n sts = {'Credentials': {'AccessKeyId': 'AKI', 'SecretAccessKey': 'squirrel', 'SessionToken': 'token', 'Expiration': 'never'}}\n session.sts = mock.Mock()\n session.sts.assume_role_with_saml.return_value = sts\n with self.assertRaises(aws.MultipleRoles):\n session.assume_role()\n", "method_code": " def assume_role(self):\n \"\"\"Use the SAML Assertion to actually get the credentials.\n \n Uses the supplied (one time use!) SAML Assertion to go out to Amazon\n and get back a set of temporary credentials. These are written out to\n disk and can be used for an hour before they need to be replaced.\n \"\"\"\n if self.role is None:\n try:\n if len(self.assertion.roles()) > 1:\n raise MultipleRoles\n self.role = self.assertion.roles()[0]\n except xml.etree.ElementTree.ParseError:\n log.error('Could not find any Role in the SAML assertion')\n log.error(self.assertion.__dict__)\n raise InvalidSaml()\n log.info('Assuming role: {}'.format(self.role['role']))\n session = self.sts.assume_role_with_saml(RoleArn=self.role['role'], PrincipalArn=self.role['principle'], SAMLAssertion=self.assertion.encode())\n creds = session['Credentials']\n self.aws_access_key_id = creds['AccessKeyId']\n self.aws_secret_access_key = creds['SecretAccessKey']\n self.session_token = creds['SessionToken']\n self.expiration = creds['Expiration']\n self._write()\n ", "context": "class Session(object):\n def assume_role(self): ...\n def __init__(self, assertion, credential_path='~/.aws', profile='default', region='us-east-1'): ...\n def is_valid(self): ...\n def set_role(self, role_index): ...\n def available_roles(self): ...\n def _write(self): ...\n\n self.sts = boto3.client('sts')\n self.profile = profile\n self.region = region\n self.assertion = SamlAssertion(assertion)\n self.writer = Credentials(cred_file)\n self.aws_access_key_id = None\n self.aws_secret_access_key = None\n self.aws_session_token = None\n self.expiration = None\n self.session_token = None\n self.role = None\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000523.py"} {"focal_file": "nd_okta_auth/aws.py", "focal_class": "nd_okta_auth.aws.Session", "focal_method": "set_role", "tests": "import unittest\n\nclass Test_nd_okta_auth_aws_Session_set_role(unittest.TestCase):\n def test_set_role(self):\n assertion = mock.Mock()\n assertion.roles.return_value = [{'role': '', 'principle': ''}]\n session = aws.Session('BogusAssertion')\n session.assertion = assertion\n session.set_role('0')\n self.assertEquals('', session.role['role'])\n", "method_code": " def set_role(self, role_index):\n \"\"\"Sets the role based on the supplied index value\"\"\"\n self.role = self.assertion.roles()[int(role_index)]\n ", "context": "class Session(object):\n def set_role(self, role_index): ...\n def __init__(self, assertion, credential_path='~/.aws', profile='default', region='us-east-1'): ...\n def is_valid(self): ...\n def available_roles(self): ...\n def assume_role(self): ...\n def _write(self): ...\n\n self.sts = boto3.client('sts')\n self.profile = profile\n self.region = region\n self.assertion = SamlAssertion(assertion)\n self.writer = Credentials(cred_file)\n self.aws_access_key_id = None\n self.aws_secret_access_key = None\n self.aws_session_token = None\n self.expiration = None\n self.session_token = None\n self.role = None\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_set_role", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000524.py"} {"focal_file": "nd_okta_auth/aws.py", "focal_class": "nd_okta_auth.aws.Session", "focal_method": "available_roles", "tests": "import unittest\n\nclass Test_nd_okta_auth_aws_Session_available_roles(unittest.TestCase):\n def test_available_roles(self):\n assertion = mock.Mock()\n roles = [{'role': '1', 'principle': ''}, {'role': '2', 'principle': ''}]\n assertion.roles.return_value = roles\n session = aws.Session('BogusAssertion')\n session.assertion = assertion\n result = session.available_roles()\n self.assertEquals(roles, result)\n", "method_code": " def available_roles(self):\n \"\"\"Returns the roles availble from AWS\"\"\"\n return self.assertion.roles()\n ", "context": "class Session(object):\n def available_roles(self): ...\n def __init__(self, assertion, credential_path='~/.aws', profile='default', region='us-east-1'): ...\n def is_valid(self): ...\n def set_role(self, role_index): ...\n def assume_role(self): ...\n def _write(self): ...\n\n self.sts = boto3.client('sts')\n self.profile = profile\n self.region = region\n self.assertion = SamlAssertion(assertion)\n self.writer = Credentials(cred_file)\n self.aws_access_key_id = None\n self.aws_secret_access_key = None\n self.aws_session_token = None\n self.expiration = None\n self.session_token = None\n self.role = None\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_available_roles", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000525.py"} {"focal_file": "nd_okta_auth/main.py", "focal_class": null, "focal_method": "get_config_parser", "tests": "import unittest\n\nclass Test_get_config_parser(unittest.TestCase):\n def test_get_config_parser(self):\n argv = ['nd_okta_auth.py', '-a', 'app/id', '-o', 'foobar', '-u', 'test']\n ret = main.get_config_parser(argv)\n self.assertEquals(ret.org, 'foobar')\n self.assertEquals(ret.appid, 'app/id')\n self.assertEquals(ret.username, 'test')\n", "method_code": "def get_config_parser(argv):\n \"\"\"Returns a configured ArgumentParser for the CLI options\"\"\"\n epilog = '**Application ID**\\nThe ApplicationID is actually a two part piece of the redirect URL \\nthat Okta uses when you are logged into the Web UI. If you mouse \\nover the appropriate Application and see a URL that looks like \\nthis. \\n\\n\\thttps://foobar.okta.com/home/amazon_aws/0oaciCSo1d8/123?...\\n\\nYou would enter in \"0oaciCSo1d8/123\" as your Application ID.\\n'\n arg_parser = argparse.ArgumentParser(prog=argv[0], formatter_class=argparse.RawDescriptionHelpFormatter, epilog=epilog, description='Okta Auther')\n arg_parser._action_groups.pop()\n required_args = arg_parser.add_argument_group('required arguments')\n required_args.add_argument('-o', '--org', type=str, help='Okta Organization Name - ie, if your login URL is https://foobar.okta.com, enter in foobar here', required=True)\n required_args.add_argument('-u', '--username', type=str, help='Okta Login Name - either bob@foobar.com, or just bob works too, depending on your organization settings.', required=True)\n required_args.add_argument('-a', '--appid', type=str, help='The \"redirect link\" Application ID - this can be found by mousing over the application in Okta\\'s Web UI. See details below for more help.', required=True)\n optional_args = arg_parser.add_argument_group('optional arguments')\n optional_args.add_argument('-V', '--version', action='version', version=__version__)\n optional_args.add_argument('-D', '--debug', action='store_true', help='Enable DEBUG logging - note, this is extremely verbose and exposes credentials so be careful here!', default=False)\n optional_args.add_argument('-r', '--reup', action='store_true', help='Automatically re-up the AWS creds beforethey expire.', default=0)\n optional_args.add_argument('-n', '--name', type=str, help='AWS Profile Name', default='default')\n config = arg_parser.parse_args(args=argv[1:])\n return config", "context": "def get_config_parser(argv): ...\ndef get_config_parser(argv): ...\ndef entry_point(): ...\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_get_config_parser", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000526.py"} {"focal_file": "nd_okta_auth/main.py", "focal_class": null, "focal_method": "entry_point", "tests": "import unittest\n\nclass Test_entry_point(unittest.TestCase):\n @mock.patch('nd_okta_auth.auth.login')\n @mock.patch('nd_okta_auth.main.get_config_parser')\n def test_entry_point(self, config_mock, auth_login):\n fake_parser = mock.MagicMock(name='fake_parser')\n fake_parser.name = 'eng'\n fake_parser.org = 'org'\n fake_parser.appid = 'appid'\n fake_parser.username = 'username'\n fake_parser.debug = True\n fake_parser.reup = False\n config_mock.return_value = fake_parser\n with self.assertRaises(SystemExit):\n main.entry_point()\n auth_login.assert_called_with(aws_profile='eng', okta_appid='appid', okta_org='org', username='username', reup=False, debug=True)\n", "method_code": "def entry_point():\n \"\"\"Zero-argument entry point for use with setuptools/distribute.\"\"\"\n config = get_config_parser(sys.argv)\n raise SystemExit(auth.login(aws_profile=config.name, okta_appid=config.appid, okta_org=config.org, username=config.username, reup=config.reup, debug=config.debug))", "context": "def entry_point(): ...\ndef get_config_parser(argv): ...\ndef entry_point(): ...\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000527.py"} {"focal_file": "nd_okta_auth/okta.py", "focal_class": "nd_okta_auth.okta.Okta", "focal_method": "set_token", "tests": "import unittest\n\nclass Test_nd_okta_auth_okta_Okta_set_token(unittest.TestCase):\n def test_set_token(self):\n client = okta.Okta('organization', 'username', 'password')\n client.session = mock.MagicMock(name='session')\n client.set_token(SUCCESS_RESPONSE)\n self.assertEquals(client.session_token, 'XXXTOKENXXX')\n", "method_code": " def set_token(self, ret):\n \"\"\"Parses an authentication response and stores the token.\n \n Parses a SUCCESSFUL authentication response from Okta and stores the\n token.\n \n args:\n ret: The response from Okta that we know is successful and contains\n a sessionToken\n \"\"\"\n firstName = ret['_embedded']['user']['profile']['firstName']\n lastName = ret['_embedded']['user']['profile']['lastName']\n log.info('Successfully authed {firstName} {lastName}'.format(firstName=firstName, lastName=lastName))\n self.session_token = ret['sessionToken']\n ", "context": "class Okta(base_client.BaseOktaClient):\n def set_token(self, ret): ...\n def __init__(self, organization, username, password): ...\n def auth(self): ...\n\n self.username = username\n self.password = password\n self.supported_factors = factor.factors(organization)\n self.session_token = None\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_set_token", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000528.py"} {"focal_file": "nd_okta_auth/okta.py", "focal_class": "nd_okta_auth.okta.Okta", "focal_method": "auth", "tests": "import unittest\n\nclass Test_nd_okta_auth_okta_Okta_auth(unittest.TestCase):\n def test_auth(self):\n client = okta.Okta('organization', 'username', 'password')\n client._request = mock.MagicMock(name='request')\n client._request.side_effect = [SUCCESS_RESPONSE]\n ret = client.auth()\n self.assertEquals(ret, None)\n", "method_code": " def auth(self):\n \"\"\"Performs an initial authentication against Okta.\n \n The initial Okta Login authentication is handled here - and optionally\n MFA authentication is triggered. If successful, this method stores a\n SessionToken. This SessionToken can be used to initiate a call to the\n \"Embed Link\" of an Okta Application.\n \n **Note ... Undocumented/Unclear Okta Behavior**\n If you use the SessionToken only to make your subsequent requests, its\n usable only once and then it expires. However, if you combine it with a\n long-lived SID cookie (which we do, by using reqests.Session() to make\n all of our web requests), then that SessionToken can be redeemd many\n times as long as you do it through the \"Embed Links\". See the OktaSaml\n client for an example.\n \n https://developer.okta.com/use_cases/authentication/\n session_cookie#visit-an-embed-link-with-the-session-token\n \"\"\"\n path = '/authn'\n data = {'username': self.username, 'password': self.password}\n try:\n ret = self._request(path, data)\n except requests.exceptions.HTTPError as e:\n if e.response.status_code == 401:\n raise InvalidPassword()\n status = ret.get('status', None)\n if status == 'SUCCESS':\n self.set_token(ret)\n return\n if status == 'MFA_ENROLL' or status == 'MFA_ENROLL_ACTIVATE':\n log.warning('User {u} needs to enroll in 2FA first'.format(u=self.username))\n raise UnknownError()\n if status == 'MFA_REQUIRED' or status == 'MFA_CHALLENGE':\n enabled_factors = ret['_embedded']['factors']\n for supported_factor in self.supported_factors:\n filtered_factors = list(filter(lambda x: x.get('factorType') == supported_factor.name(), enabled_factors))\n for enabled_factor in filtered_factors:\n log.info('Authenticating with factor: {} id {}'.format(supported_factor.name(), enabled_factor['id']))\n try:\n ret = supported_factor.verify(enabled_factor['id'], ret['stateToken'], sleep=1)\n self.set_token(ret)\n return\n except KeyboardInterrupt:\n log.info('User skipping factor: {}'.format(supported_factor.name()))\n continue\n except factor.FactorVerificationFailed as e:\n log.error(e)\n continue\n except requests.exceptions.ReadTimeout:\n log.error('HTTP timeout contacting Okta at {}'.format(self.base_url))\n continue\n raise ExhaustedFactors('Failed to verify with any MFA factor')\n ", "context": "class Okta(base_client.BaseOktaClient):\n def auth(self): ...\n def __init__(self, organization, username, password): ...\n def set_token(self, ret): ...\n\n self.username = username\n self.password = password\n self.supported_factors = factor.factors(organization)\n self.session_token = None\n", "repository": "Nextdoor/nd_okta_auth", "test_name": "test_auth", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000529.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "tei", "tests": "import unittest\n\nclass Test_tei(unittest.TestCase):\n def test_get_tei(self):\n \"\"\"Test TSPacket.tei method.\"\"\"\n tei = self.tsp.tei()\n assert tei == 0\n", "method_code": " def tei(self):\n \"\"\"Return TEI flag.\"\"\"\n return (self.raw_pkt[1] & 128) >> 7\n ", "context": "class TSPacket(object):\n def tei(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_tei", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000530.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "pusi", "tests": "import unittest\n\nclass Test_pusi(unittest.TestCase):\n def test_get_pusi(self):\n \"\"\"Test TSPacket.pusi method.\"\"\"\n pusi = self.tsp.pusi()\n assert pusi == 0\n", "method_code": " def pusi(self):\n \"\"\"Return PUSI flag.\"\"\"\n return (self.raw_pkt[1] & 64) >> 6\n ", "context": "class TSPacket(object):\n def pusi(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_pusi", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000531.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "tp", "tests": "import unittest\n\nclass Test_tp(unittest.TestCase):\n def test_get_tp(self):\n \"\"\"Test TSPacket.tp method.\"\"\"\n tp = self.tsp.tp()\n assert tp == 0\n", "method_code": " def tp(self):\n \"\"\"Return TP flag.\"\"\"\n return (self.raw_pkt[1] & 32) >> 5\n ", "context": "class TSPacket(object):\n def tp(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_tp", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000532.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "pid", "tests": "import unittest\n\nclass Test_pid(unittest.TestCase):\n def test_get_pid(self):\n \"\"\"Test TSPacket.pid method.\"\"\"\n pid = self.tsp.pid()\n assert pid == 1\n", "method_code": " def pid(self):\n \"\"\"Return PID.\"\"\"\n tmp, = struct.unpack('!H', self.raw_pkt[1:3])\n return tmp & 8191\n ", "context": "class TSPacket(object):\n def pid(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_pid", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000533.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "tsc", "tests": "import unittest\n\nclass Test_tsc(unittest.TestCase):\n def test_get_tsc(self):\n \"\"\"Test TSPacket.tsc method.\"\"\"\n tsc = self.tsp.tsc()\n assert tsc == 0\n", "method_code": " def tsc(self):\n \"\"\"Return TSC.\"\"\"\n return (self.raw_pkt[3] & 192) >> 6\n ", "context": "class TSPacket(object):\n def tsc(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_tsc", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000534.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "afc", "tests": "import unittest\n\nclass Test_afc(unittest.TestCase):\n def test_get_afc(self):\n \"\"\"Test TSPacket.afc method.\"\"\"\n afc = self.tsp.afc()\n assert afc == 3\n", "method_code": " def afc(self):\n \"\"\"Return AFC.\"\"\"\n return (self.raw_pkt[3] & 48) >> 4\n ", "context": "class TSPacket(object):\n def afc(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_afc", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000535.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "cc", "tests": "import unittest\n\nclass Test_cc(unittest.TestCase):\n def test_get_cc(self):\n \"\"\"Test TSPacket.cc method.\"\"\"\n cc = self.tsp.cc()\n assert cc == 0\n", "method_code": " def cc(self):\n \"\"\"Return CC.\"\"\"\n return self.raw_pkt[3] & 15\n ", "context": "class TSPacket(object):\n def cc(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_cc", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000536.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "header", "tests": "import unittest\n\nclass Test_header(unittest.TestCase):\n def test_get_header(self):\n \"\"\"Test TSPacket.header method.\"\"\"\n hdr = self.tsp.header()\n assert len(hdr) == 4\n", "method_code": " def header(self):\n \"\"\"Return only the packet header.\"\"\"\n return self.raw_pkt[0:4]\n ", "context": "class TSPacket(object):\n def header(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_header", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000537.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "body", "tests": "import unittest\n\nclass Test_body(unittest.TestCase):\n def test_get_body(self):\n \"\"\"Test TSPacket.body method.\"\"\"\n body = self.tsp.body()\n assert len(body) == 184\n", "method_code": " def body(self):\n \"\"\"Return only the packet body.\"\"\"\n return self.raw_pkt[4:]\n ", "context": "class TSPacket(object):\n def body(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_body", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000538.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "has_payload", "tests": "import unittest\n\nclass Test_has_payload(unittest.TestCase):\n def test_has_payload(self):\n \"\"\"Test TSPacket.has_payload method.\"\"\"\n assert self.tsp.has_payload()\n", "method_code": " def has_payload(self):\n \"\"\"Return True if the packet contains payload, return False otherwise.\"\"\"\n return self.afc() & 1 != 0\n ", "context": "class TSPacket(object):\n def has_payload(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_has_payload", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000539.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "payload", "tests": "import unittest\n\nclass Test_payload(unittest.TestCase):\n def test_get_payload(self):\n \"\"\"Test TSPacket.payload method.\"\"\"\n payload = self.tsp.payload()\n assert len(payload) == 179\n", "method_code": " def payload(self):\n \"\"\"Return the packet payload.\"\"\"\n if self.has_payload():\n if self.has_adaptation_field():\n af_len = self.body()[0]\n return self.body()[af_len + 1:]\n else:\n return self.body()\n else:\n return None\n ", "context": "class TSPacket(object):\n def payload(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def has_adaptation_field(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_payload", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000540.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "has_adaptation_field", "tests": "import unittest\n\nclass Test_has_adaptation_field(unittest.TestCase):\n def test_has_adaptation_field(self):\n \"\"\"Test TSPacket.has_adaptation_field method.\"\"\"\n assert self.tsp.has_adaptation_field()\n", "method_code": " def has_adaptation_field(self):\n \"\"\"Return True if the packet contains an adaptation field, return False otherwise.\"\"\"\n return self.afc() & 2 != 0\n ", "context": "class TSPacket(object):\n def has_adaptation_field(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_has_adaptation_field", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000541.py"} {"focal_file": "TSPacket.py", "focal_class": null, "focal_method": "adaptation_field", "tests": "import unittest\n\nclass Test_adaptation_field(unittest.TestCase):\n def test_get_adaptation_field(self):\n \"\"\"Test TSPacket.adaptation_field method.\"\"\"\n af = self.tsp.adaptation_field()\n assert len(af) == 4\n", "method_code": " def adaptation_field(self):\n \"\"\"Return the adaptation field.\"\"\"\n if self.has_adaptation_field():\n af_len = self.body()[0]\n return self.body()[:af_len]\n else:\n return None\n ", "context": "class TSPacket(object):\n def adaptation_field(self): ...\n def __init__(self, init=None): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n def header(self): ...\n def body(self): ...\n def sync_byte(self): ...\n def tei(self): ...\n def pusi(self): ...\n def tp(self): ...\n def pid(self): ...\n def tsc(self): ...\n def afc(self): ...\n def cc(self): ...\n def has_sync_byte(self): ...\n def has_payload(self): ...\n def payload(self): ...\n def has_adaptation_field(self): ...\n\n _LENGTH = 188\n _SYNC_BYTE = bytes.fromhex('47')\n _NULL_PKT_HDR = bytes.fromhex('471FFFFF')\n", "repository": "dondamage/SPyTS", "test_name": "test_get_adaptation_field", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000542.py"} {"focal_file": "retools/cache.py", "focal_class": null, "focal_method": "add_region", "tests": "import unittest\n\nclass Test_add_region(unittest.TestCase):\n def test_add_region(self):\n CR = self._makeOne()\n CR.add_region('short_term', 60)\n eq_(CR.regions['short_term']['expires'], 60)\n\n def test_no_region(self):\n from retools.exc import CacheConfigurationError\n\n @raises(CacheConfigurationError)\n def test_it():\n CR = self._makeOne()\n CR.add_region('short_term', 60)\n\n def dummy_func():\n return 'This is a value: %s' % time.time()\n decorated = self._decorateFunc(dummy_func, 'long_term')\n decorated()\n test_it()\n", "method_code": " def add_region(cls, name, expires, redis_expiration=60 * 60 * 24 * 7):\n \"\"\"Add a cache region to the current configuration\n \n :param name: The name of the cache region\n :type name: string\n :param expires: The expiration in seconds.\n :type expires: integer\n :param redis_expiration: How long the Redis key expiration is\n set for. Defaults to 1 week.\n :type redis_expiration: integer\n \n \"\"\"\n cls.regions[name] = dict(expires=expires, redis_expiration=redis_expiration)\n ", "context": "class CacheRegion(object):\n @classmethod\n def add_region(cls, name, expires, redis_expiration=60 * 60 * 24 * 7): ...\n def _add_tracking(cls, pipeline, region, namespace, key): ...\n def invalidate(cls, region): ...\n def load(cls, region, namespace, key, regenerate=True, callable=None, statistics=None): ...\n\n regions = {}\n enabled = True\n statistics = True\n", "repository": "0x1997/retools", "test_name": "test_add_region", "smells": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000543.py"} {"focal_file": "retools/cache.py", "focal_class": null, "focal_method": "invalidate_region", "tests": "import unittest\n\nclass Test_invalidate_region(unittest.TestCase):\n def test_invalidate_region_empty(self):\n mock_redis = Mock(spec=redis.client.Redis)\n mock_redis.smembers.return_value = set([])\n invalidate_region = self._makeOne()\n with patch('retools.global_connection._redis', mock_redis):\n CR = self._makeCR()\n CR.add_region('short_term', expires=600)\n invalidate_region('short_term')\n eq_(len(mock_redis.method_calls), 1)\n\n def test_invalidate_small_region(self):\n mock_redis = Mock(spec=redis.client.Redis)\n results = [set(['keyspace']), set(['a_func'])]\n\n def side_effect(*args):\n return results.pop()\n mock_redis.smembers.side_effect = side_effect\n invalidate_region = self._makeOne()\n with patch('retools.global_connection._redis', mock_redis):\n CR = self._makeCR()\n CR.add_region('short_term', expires=600)\n invalidate_region('short_term')\n calls = mock_redis.method_calls\n eq_(calls[0][1], ('retools:short_term:namespaces',))\n eq_(len(calls), 6)\n", "method_code": "def invalidate_region(region):\n \"\"\"Invalidate all the namespace's in a given region\n\n .. note::\n\n This does not actually *clear* the region of data, but\n just sets the value to expire on next access.\n\n :param region: Region name\n :type region: string\n\n \"\"\"\n CacheRegion.invalidate(region)", "context": "def invalidate_region(region): ...\ndef invalidate_region(region): ...\ndef invalidate_callable(callable, *args): ...\ndef cache_region(region, *deco_args, **kwargs): ...\n", "repository": "0x1997/retools", "test_name": "test_invalidate_region_empty", "smells": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000544.py"} {"focal_file": "src/frvcpy/translator.py", "focal_class": null, "focal_method": "translate", "tests": "import unittest\n\nclass Test_translate(unittest.TestCase):\n def test_translation(self):\n \"\"\"Translate an instance, compare it to a known reference\"\"\"\n frvcp_instance = translator.translate(self.MANUSCRIPT_INSTANCE)\n assertDeepAlmostEqual(self, frvcp_instance, self.ref_instance, 3)\n", "method_code": "def translate(from_filename, to_filename: str=None, v_type: Any=None, depot_charging: bool=True) -> Optional[dict]:\n \"\"\"Translate a VRP-REP instance into an instance compatible with frvcpy.\n\n Args:\n from_filename: filename (str) of the instance to be translated\n to_filename: filename (str) of the translated instance to be written. If\n not specified, the function returns the instance in a Python dictionary.\n v_type: the value of the `type` attribute of the vehicle_profile from the\n instance to be used (what vehicle type to solve the FRVCP for)\n depot_charging: whether the EV is allowed to recharge at the depot\n (True by default)\n\n Returns:\n If to_filename is specified, writes the translated instance to file and\n returns None. Otherwise (to_filename not specified) returns the\n necessary instance parameters in a dict.\n \"\"\"\n with open(from_filename) as f_xml:\n doc = xmltodict.parse(f_xml.read())\n instance_xml = doc['instance']\n network = instance_xml['network']\n nodes = network['nodes']['node']\n requests = instance_xml['requests']['request']\n ev = instance_xml['fleet']['vehicle_profile']\n if isinstance(ev, list):\n if v_type is None:\n print('INFO: Multiple vehicle_profiles found, but no type specified. ' + f'Using first type listed in the instance ({ev[0]['@type']}).')\n ev = ev[0]\n else:\n good_evs = [v for v in ev if v['@type'] == v_type]\n if len(good_evs) >= 2:\n raise ValueError(f'Multiple vehicle profiles of type {v_type} found')\n if len(good_evs) <= 0:\n raise ValueError(f'No vehicle profile found with specified type {v_type}')\n ev = good_evs[0]\n elif v_type is not None:\n if ev['@type'] != v_type:\n raise ValueError(f\"EV type (ev['@type']) does not match specified type ({v_type})\")\n _warn_unused_els(instance_xml)\n dist_type = None\n if 'euclidean' in network:\n dist_type = 'euclidean'\n elif 'manhattan' in network:\n dist_type = 'manhattan'\n if dist_type is None:\n print('WARNING: An unrecognized (or no) distance type was listed in the instance. ' + \"Assuming Euclidean distance calculations. ('euclidean' and 'manhattan' are \" + 'supported; for all others, manual instance translation necessary.')\n dist_type = 'euclidean'\n precision_type = _get_precision_type(network)\n if precision_type is not None:\n print('WARNING: Using default Python precision. ' + f\"Precision type '{precision_type}' ignored.\")\n _check_reqd_ev_info(ev)\n speed = float(ev['speed_factor'])\n consump_rate = float(ev['custom']['consumption_rate'])\n max_q = float(ev['custom']['battery_capacity'])\n cfs = ev['custom']['charging_functions']['function']\n if not isinstance(cfs, (list,)):\n cfs = [cfs]\n type_to_speed = _get_type_to_speed(cfs)\n max_t = float(ev['max_travel_time']) if 'max_travel_time' in ev else None\n if depot_charging:\n fastest = [t for t, r in type_to_speed.items() if r == 0][0]\n nodes.append({'@id': str(len(nodes)), 'cx': nodes[0]['cx'], 'cy': nodes[0]['cy'], '@type': '2', 'custom': {'cs_type': fastest}})\n print(f\"INFO: Depot assumed to be a CS with the instance's fastest \" + \"charging type (fastest found was '{fastest}').\")\n css = [node for node in nodes if node['@type'] == '2']\n unrec_nodetypes = {node['@type'] for node in nodes if node['@type'] not in ['0', '1', '2']}\n if unrec_nodetypes:\n print(f'WARNING: Unrecognized node types found: {unrec_nodetypes}')\n print(f\"INFO: Only nodes' service_time is preserved from requests. All other info ignored.\")\n process_times = [0 for _ in nodes]\n process_times = _get_process_times(process_times, requests)\n req_nodes = [int(r['@node']) for r in requests]\n if len(req_nodes) != len(set(req_nodes)):\n print('WARNING: Nodes can only have one request. Ignoring duplicate requests.\\n\\t' + 'For nodes with multiple requests, please add additional (dummy) nodes to the instance.')\n instance = {}\n instance['max_q'] = max_q\n if max_t is not None:\n instance['t_max'] = max_t\n instance['css'] = [{'node_id': int(cs['@id']), 'cs_type': type_to_speed[cs['custom']['cs_type']]} for cs in css]\n instance['process_times'] = process_times\n instance['breakpoints_by_type'] = [{'cs_type': type_to_speed[cfs[k]['@cs_type']], 'time': [float(bpt['charging_time']) for bpt in cfs[k]['breakpoint']], 'charge': [float(bpt['battery_level']) for bpt in cfs[k]['breakpoint']]} for k in range(len(cfs))]\n instance['energy_matrix'] = [[_e(i, j, consump_rate, dist_type) for j in nodes] for i in nodes]\n instance['time_matrix'] = [[_t(i, j, speed, dist_type) for j in nodes] for i in nodes]\n if to_filename is not None:\n with open(to_filename, 'w') as instance_file:\n json.dump(instance, instance_file)\n return None\n return instance", "context": "def translate(from_filename, to_filename: str=None, v_type: Any=None, depot_charging: bool=True) -> Optional[dict]: ...\ndef _dist(i_node, j_node, dist_type) -> float: ...\ndef _t(i_node, j_node, speed, dist_type) -> float: ...\ndef _e(i_node, j_node, consump_rate, dist_type) -> float: ...\ndef _get_type_to_speed(cfs): ...\ndef _get_precision_type(network_el): ...\ndef _warn_unused_els(instance_el): ...\ndef _check_reqd_ev_info(ev_el): ...\ndef _get_process_times(process_times, requests): ...\ndef translate(from_filename, to_filename: str=None, v_type: Any=None, depot_charging: bool=True) -> Optional[dict]: ...\ndef main(): ...\n", "repository": "INFORMSJoC/2020.1035", "test_name": "test_translation", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000545.py"} {"focal_file": "test/py/ganeti.jqueue_unittest.py", "focal_class": null, "focal_method": "CalcPriority", "tests": "import unittest\n\nclass Test_CalcPriority(unittest.TestCase):\n def testPriority(self):\n job_id = 4283\n ops = [opcodes.OpTagsGet(priority=constants.OP_PRIO_DEFAULT), opcodes.OpTestDelay()]\n\n def _Check(job):\n self.assertEqual(job.id, job_id)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n self.assert_(repr(job).startswith('<'))\n job = jqueue._QueuedJob(None, job_id, ops, True)\n _Check(job)\n self.assert_(compat.all((op.priority == constants.OP_PRIO_DEFAULT for op in job.ops)))\n self.assertEqual(job.CalcPriority(), constants.OP_PRIO_DEFAULT)\n job.ops[0].priority -= 1\n _Check(job)\n self.assertEqual(job.CalcPriority(), constants.OP_PRIO_DEFAULT - 1)\n job.ops[0].status = constants.OP_STATUS_SUCCESS\n _Check(job)\n self.assertEqual(job.CalcPriority(), constants.OP_PRIO_DEFAULT)\n job.ops[1].priority -= 10\n self.assertEqual(job.CalcPriority(), constants.OP_PRIO_DEFAULT - 10)\n job.ops[0].status = constants.OP_STATUS_RUNNING\n job.ops[0].priority -= 19\n self.assertEqual(job.CalcPriority(), constants.OP_PRIO_DEFAULT - 20)\n", "method_code": " def CalcPriority(self):\n return self._priority\n ", "context": "class _IdOnlyFakeJob():\n def CalcPriority(self): ...\n def __init__(self, job_id, priority=NotImplemented): ...\n\n self.id = str(job_id)\n self._priority = priority\n", "repository": "itminedu/snf-ganeti", "test_name": "testPriority", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000546.py"} {"focal_file": "test/py/ganeti.jqueue_unittest.py", "focal_class": null, "focal_method": "CalcStatus", "tests": "import unittest\n\nclass Test_CalcStatus(unittest.TestCase):\n def testCalcStatus(self):\n\n def _Queued(ops):\n self.assert_(compat.all((op.status == constants.OP_STATUS_QUEUED for op in ops)))\n\n def _Waitlock1(ops):\n ops[0].status = constants.OP_STATUS_WAITING\n\n def _Waitlock2(ops):\n ops[0].status = constants.OP_STATUS_SUCCESS\n ops[1].status = constants.OP_STATUS_SUCCESS\n ops[2].status = constants.OP_STATUS_WAITING\n\n def _Running(ops):\n ops[0].status = constants.OP_STATUS_SUCCESS\n ops[1].status = constants.OP_STATUS_RUNNING\n for op in ops[2:]:\n op.status = constants.OP_STATUS_QUEUED\n\n def _Canceling1(ops):\n ops[0].status = constants.OP_STATUS_SUCCESS\n ops[1].status = constants.OP_STATUS_SUCCESS\n for op in ops[2:]:\n op.status = constants.OP_STATUS_CANCELING\n\n def _Canceling2(ops):\n for op in ops:\n op.status = constants.OP_STATUS_CANCELING\n\n def _Canceled(ops):\n for op in ops:\n op.status = constants.OP_STATUS_CANCELED\n\n def _Error1(ops):\n for idx, op in enumerate(ops):\n if idx > 3:\n op.status = constants.OP_STATUS_ERROR\n else:\n op.status = constants.OP_STATUS_SUCCESS\n\n def _Error2(ops):\n for op in ops:\n op.status = constants.OP_STATUS_ERROR\n\n def _Success(ops):\n for op in ops:\n op.status = constants.OP_STATUS_SUCCESS\n tests = {constants.JOB_STATUS_QUEUED: [_Queued], constants.JOB_STATUS_WAITING: [_Waitlock1, _Waitlock2], constants.JOB_STATUS_RUNNING: [_Running], constants.JOB_STATUS_CANCELING: [_Canceling1, _Canceling2], constants.JOB_STATUS_CANCELED: [_Canceled], constants.JOB_STATUS_ERROR: [_Error1, _Error2], constants.JOB_STATUS_SUCCESS: [_Success]}\n\n def _NewJob():\n job = jqueue._QueuedJob(None, 1, [opcodes.OpTestDelay() for _ in range(10)], True)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n self.assert_(compat.all((op.status == constants.OP_STATUS_QUEUED for op in job.ops)))\n return job\n for status in constants.JOB_STATUS_ALL:\n sttests = tests[status]\n assert sttests\n for fn in sttests:\n job = _NewJob()\n fn(job.ops)\n self.assertEqual(job.CalcStatus(), status)\n", "method_code": " def CalcStatus(self):\n return self._status\n ", "context": "class _FakeJob():\n def CalcStatus(self): ...\n def __init__(self, job_id, status): ...\n def SetStatus(self, status): ...\n def AddLogEntry(self, msg): ...\n def GetLogEntries(self, newer_than): ...\n\n self.id = job_id\n self.writable = False\n self._status = status\n self._log = []\n", "repository": "itminedu/snf-ganeti", "test_name": "testCalcStatus", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000547.py"} {"focal_file": "test/py/ganeti.jqueue_unittest.py", "focal_class": null, "focal_method": "_TestCancelWhileSomething", "tests": "import unittest\n\nclass Test_TestCancelWhileSomething(unittest.TestCase):\n def testCancelWhileWaitlockWithTimeout(self):\n\n def fn(_):\n raise mcpu.LockAcquireTimeout()\n self._TestCancelWhileSomething(fn)\n", "method_code": " def _TestCancelWhileSomething(self, cb):\n queue = _FakeQueueForProc()\n ops = [opcodes.OpTestDummy(result='Res%s' % i, fail=False) for i in range(5)]\n job_id = 24314\n job = self._CreateJob(queue, job_id, ops)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n \n def _BeforeStart(timeout, priority):\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_WAITING)\n success, _ = job.Cancel()\n self.assert_(success)\n self.assert_(compat.all((op.status == constants.OP_STATUS_CANCELING for op in job.ops)))\n cb(queue)\n \n def _AfterStart(op, cbs):\n self.fail('Should not reach this')\n opexec = _FakeExecOpCodeForProc(queue, _BeforeStart, _AfterStart)\n self.assertEqual(jqueue._JobProcessor(queue, opexec, job)(), jqueue._JobProcessor.FINISHED)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_CANCELED)\n self.assert_(job.start_timestamp)\n self.assert_(job.end_timestamp)\n self.assertFalse(compat.all((op.start_timestamp and op.end_timestamp for op in job.ops)))\n return queue\n ", "context": "class TestJobProcessor(unittest.TestCase_JobProcessorTestUtils):\n def _TestCancelWhileSomething(self, cb): ...\n def _GenericCheckJob(self, job): ...\n def testSuccess(self): ...\n def testOpcodeError(self): ...\n def testCancelWhileInQueue(self): ...\n def testCancelWhileWaitlockInQueue(self): ...\n def testCancelWhileWaitlock(self): ...\n def testCancelWhileWaitlockWithTimeout(self): ...\n def testCancelWhileRunning(self): ...\n def testPartiallyRun(self): ...\n def _TestPartial(self, job, successcount): ...\n def testProcessorOnRunningJob(self): ...\n def testLogMessages(self): ...\n def _CheckLogMessages(self, job, count): ...\n def testSubmitManyJobs(self): ...\n def testJobDependency(self): ...\n def testJobDependencyCancel(self): ...\n def testJobDependencyWrongstatus(self): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "testCancelWhileWaitlockWithTimeout", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000548.py"} {"focal_file": "test/py/ganeti.jqueue_unittest.py", "focal_class": null, "focal_method": "_TestPartial", "tests": "import unittest\n\nclass Test_TestPartial(unittest.TestCase):\n def testPartiallyRun(self):\n queue = _FakeQueueForProc()\n opexec = _FakeExecOpCodeForProc(queue, None, None)\n for job_id, successcount in [(30697, 1), (2552, 4), (12489, 9)]:\n ops = [opcodes.OpTestDummy(result='Res%s' % i, fail=False) for i in range(10)]\n job = self._CreateJob(queue, job_id, ops)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n for _ in range(successcount):\n self.assertEqual(jqueue._JobProcessor(queue, opexec, job)(), jqueue._JobProcessor.DEFER)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n self.assert_(job.ops_iter)\n newjob = jqueue._QueuedJob.Restore(queue, job.Serialize(), True, False)\n self.assertFalse(newjob.ops_iter)\n self._TestPartial(newjob, successcount)\n", "method_code": " def _TestPartial(self, job, successcount):\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n self.assertEqual(job.start_timestamp, job.ops[0].start_timestamp)\n queue = _FakeQueueForProc()\n opexec = _FakeExecOpCodeForProc(queue, None, None)\n for remaining in reversed(range(len(job.ops) - successcount)):\n result = jqueue._JobProcessor(queue, opexec, job)()\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertRaises(IndexError, queue.GetNextUpdate)\n if remaining == 0:\n self.assertEqual(result, jqueue._JobProcessor.FINISHED)\n break\n self.assertEqual(result, jqueue._JobProcessor.DEFER)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n self.assertRaises(IndexError, queue.GetNextUpdate)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_SUCCESS)\n self.assert_(compat.all((op.start_timestamp and op.end_timestamp for op in job.ops)))\n self._GenericCheckJob(job)\n self.assertEqual(jqueue._JobProcessor(queue, opexec, job)(), jqueue._JobProcessor.FINISHED)\n self.assertRaises(IndexError, queue.GetNextUpdate)\n job2 = jqueue._QueuedJob.Restore(queue, job.Serialize(), True, False)\n self.assertEqual(jqueue._JobProcessor(queue, opexec, job2)(), jqueue._JobProcessor.FINISHED)\n self.assertRaises(IndexError, queue.GetNextUpdate)\n ", "context": "class TestJobProcessor(unittest.TestCase_JobProcessorTestUtils):\n def _TestPartial(self, job, successcount): ...\n def _GenericCheckJob(self, job): ...\n def testSuccess(self): ...\n def testOpcodeError(self): ...\n def testCancelWhileInQueue(self): ...\n def testCancelWhileWaitlockInQueue(self): ...\n def testCancelWhileWaitlock(self): ...\n def _TestCancelWhileSomething(self, cb): ...\n def testCancelWhileWaitlockWithTimeout(self): ...\n def testCancelWhileRunning(self): ...\n def testPartiallyRun(self): ...\n def testProcessorOnRunningJob(self): ...\n def testLogMessages(self): ...\n def _CheckLogMessages(self, job, count): ...\n def testSubmitManyJobs(self): ...\n def testJobDependency(self): ...\n def testJobDependencyCancel(self): ...\n def testJobDependencyWrongstatus(self): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "testPartiallyRun", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000549.py"} {"focal_file": "test/py/ganeti.jqueue_unittest.py", "focal_class": null, "focal_method": "_CheckLogMessages", "tests": "import unittest\n\nclass Test_CheckLogMessages(unittest.TestCase):\n def testLogMessages(self):\n queue = _FakeQueueForProc()\n messages = {1: [(None, 'Hello'), (None, 'World'), (constants.ELOG_MESSAGE, 'there')], 4: [(constants.ELOG_JQUEUE_TEST, (1, 2, 3)), (constants.ELOG_JQUEUE_TEST, ('other', 'type'))]}\n ops = [opcodes.OpTestDummy(result='Logtest%s' % i, fail=False, messages=messages.get(i, [])) for i in range(5)]\n job = self._CreateJob(queue, 29386, ops)\n\n def _BeforeStart(timeout, priority):\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertRaises(IndexError, queue.GetNextUpdate)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_WAITING)\n\n def _AfterStart(op, cbs):\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertRaises(IndexError, queue.GetNextUpdate)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_RUNNING)\n self.assertRaises(AssertionError, cbs.Feedback, 'too', 'many', 'arguments')\n for log_type, msg in op.messages:\n self.assertRaises(IndexError, queue.GetNextUpdate)\n if log_type:\n cbs.Feedback(log_type, msg)\n else:\n cbs.Feedback(msg)\n self.assertEqual(queue.GetNextUpdate(), (job, False))\n self.assertRaises(IndexError, queue.GetNextUpdate)\n opexec = _FakeExecOpCodeForProc(queue, _BeforeStart, _AfterStart)\n for remaining in reversed(range(len(job.ops))):\n self.assertRaises(IndexError, queue.GetNextUpdate)\n result = jqueue._JobProcessor(queue, opexec, job)()\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertRaises(IndexError, queue.GetNextUpdate)\n if remaining == 0:\n self.assertEqual(result, jqueue._JobProcessor.FINISHED)\n break\n self.assertEqual(result, jqueue._JobProcessor.DEFER)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n self.assertRaises(IndexError, queue.GetNextUpdate)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_SUCCESS)\n logmsgcount = sum((len(m) for m in messages.values()))\n self._CheckLogMessages(job, logmsgcount)\n newjob = jqueue._QueuedJob.Restore(queue, job.Serialize(), True, False)\n self._CheckLogMessages(newjob, logmsgcount)\n", "method_code": " def _CheckLogMessages(self, job, count):\n self.assertEqual(job.log_serial, count)\n assert count > 3\n self.assert_(job.GetLogEntries(3))\n self.assertFalse(job.GetLogEntries(count))\n self.assertFalse(job.GetLogEntries(count + 3))\n ", "context": "class TestJobProcessor(unittest.TestCase_JobProcessorTestUtils):\n def _CheckLogMessages(self, job, count): ...\n def _GenericCheckJob(self, job): ...\n def testSuccess(self): ...\n def testOpcodeError(self): ...\n def testCancelWhileInQueue(self): ...\n def testCancelWhileWaitlockInQueue(self): ...\n def testCancelWhileWaitlock(self): ...\n def _TestCancelWhileSomething(self, cb): ...\n def testCancelWhileWaitlockWithTimeout(self): ...\n def testCancelWhileRunning(self): ...\n def testPartiallyRun(self): ...\n def _TestPartial(self, job, successcount): ...\n def testProcessorOnRunningJob(self): ...\n def testLogMessages(self): ...\n def testSubmitManyJobs(self): ...\n def testJobDependency(self): ...\n def testJobDependencyCancel(self): ...\n def testJobDependencyWrongstatus(self): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "testLogMessages", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000550.py"} {"focal_file": "test/py/ganeti.jqueue_unittest.py", "focal_class": null, "focal_method": "GetNextSubmittedJob", "tests": "import unittest\n\nclass Test_GetNextSubmittedJob(unittest.TestCase):\n def testSubmitManyJobs(self):\n queue = _FakeQueueForProc()\n job_id = 15656\n ops = [opcodes.OpTestDummy(result='Res0', fail=False, submit_jobs=[]), opcodes.OpTestDummy(result='Res1', fail=False, submit_jobs=[[opcodes.OpTestDummy(result='r1j0', fail=False)]]), opcodes.OpTestDummy(result='Res2', fail=False, submit_jobs=[[opcodes.OpTestDummy(result='r2j0o0', fail=False), opcodes.OpTestDummy(result='r2j0o1', fail=False), opcodes.OpTestDummy(result='r2j0o2', fail=False), opcodes.OpTestDummy(result='r2j0o3', fail=False)], [opcodes.OpTestDummy(result='r2j1', fail=False)], [opcodes.OpTestDummy(result='r2j3o0', fail=False), opcodes.OpTestDummy(result='r2j3o1', fail=False)]])]\n job = self._CreateJob(queue, job_id, ops)\n\n def _BeforeStart(timeout, priority):\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertRaises(IndexError, queue.GetNextUpdate)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_WAITING)\n self.assertFalse(job.cur_opctx)\n\n def _AfterStart(op, cbs):\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertRaises(IndexError, queue.GetNextUpdate)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_RUNNING)\n self.assertFalse(job.cur_opctx)\n success, _ = job.Cancel()\n self.assertFalse(success)\n opexec = _FakeExecOpCodeForProc(queue, _BeforeStart, _AfterStart)\n for idx in range(len(ops)):\n self.assertRaises(IndexError, queue.GetNextUpdate)\n result = jqueue._JobProcessor(queue, opexec, job)()\n self.assertEqual(queue.GetNextUpdate(), (job, True))\n self.assertRaises(IndexError, queue.GetNextUpdate)\n if idx == len(ops) - 1:\n self.assertEqual(result, jqueue._JobProcessor.FINISHED)\n else:\n self.assertEqual(result, jqueue._JobProcessor.DEFER)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_QUEUED)\n self.assert_(job.start_timestamp)\n self.assertFalse(job.end_timestamp)\n self.assertRaises(IndexError, queue.GetNextUpdate)\n for idx, submitted_ops in enumerate((job_ops for op in ops for job_ops in op.submit_jobs)):\n self.assertEqual(queue.GetNextSubmittedJob(), (1000 + idx, submitted_ops))\n self.assertRaises(IndexError, queue.GetNextSubmittedJob)\n self.assertEqual(job.CalcStatus(), constants.JOB_STATUS_SUCCESS)\n self._GenericCheckJob(job)\n self.assertEqual(jqueue._JobProcessor(queue, opexec, job)(), jqueue._JobProcessor.FINISHED)\n self.assertRaises(IndexError, queue.GetNextUpdate)\n", "method_code": " def GetNextSubmittedJob(self):\n return self._submitted.pop(0)\n ", "context": "class _FakeQueueForProc():\n def GetNextSubmittedJob(self): ...\n def __init__(self, depmgr=None): ...\n def GetNextUpdate(self): ...\n def UpdateJobUnlocked(self, job, replicate=True): ...\n def SubmitManyJobs(self, jobs): ...\n\n self._updates = []\n self._submitted = []\n self._submit_count = itertools.count(1000)\n", "repository": "itminedu/snf-ganeti", "test_name": "testSubmitManyJobs", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000551.py"} {"focal_file": "test/py/ganeti.objects_unittest.py", "focal_class": null, "focal_method": "_AssertIPolicyIsFull", "tests": "import unittest\n\nclass Test_AssertIPolicyIsFull(unittest.TestCase):\n def testDefaultIPolicy(self):\n objects.InstancePolicy.CheckParameterSyntax(constants.IPOLICY_DEFAULTS, True)\n self._AssertIPolicyIsFull(constants.IPOLICY_DEFAULTS)\n", "method_code": " def _AssertIPolicyIsFull(self, policy):\n self.assertEqual(frozenset(policy.keys()), constants.IPOLICY_ALL_KEYS)\n self.assertTrue(len(policy[constants.ISPECS_MINMAX]) > 0)\n for minmax in policy[constants.ISPECS_MINMAX]:\n self.assertEqual(frozenset(minmax.keys()), constants.ISPECS_MINMAX_KEYS)\n for key in constants.ISPECS_MINMAX_KEYS:\n self.assertEqual(frozenset(minmax[key].keys()), constants.ISPECS_PARAMETERS)\n self.assertEqual(frozenset(policy[constants.ISPECS_STD].keys()), constants.ISPECS_PARAMETERS)\n ", "context": "class TestInstancePolicy(unittest.TestCase):\n def _AssertIPolicyIsFull(self, policy): ...\n def setUp(self): ...\n def testDefaultIPolicy(self): ...\n def _AssertPolicyIsBad(self, ipolicy, do_check_std=None): ...\n def testCheckISpecSyntax(self): ...\n def testCheckISpecParamSyntax(self): ...\n def testCheckDiskTemplates(self): ...\n def testCheckParameterSyntax(self): ...\n def testFillIPolicyEmpty(self): ...\n def _AssertISpecsMerged(self, default_spec, diff_spec, merged_spec): ...\n def _AssertIPolicyMerged(self, default_pol, diff_pol, merged_pol): ...\n def testFillIPolicy(self): ...\n def testFillIPolicyKeepsUnknown(self): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "testDefaultIPolicy", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000552.py"} {"focal_file": "test/py/ganeti.tools.prepare_node_join_unittest.py", "focal_class": null, "focal_method": "_TestDryRun", "tests": "import unittest\n\nclass Test_TestDryRun(unittest.TestCase):\n def testDryRunRsa(self):\n self._TestDryRun({constants.SSHS_SSH_HOST_KEY: [(constants.SSHK_RSA, 'rsapriv', 'rsapub')]})\n\n def testDryRunDsa(self):\n self._TestDryRun({constants.SSHS_SSH_HOST_KEY: [(constants.SSHK_DSA, 'dsapriv', 'dsapub')]})\n\n def testDryRunEcdsa(self):\n self._TestDryRun({constants.SSHS_SSH_HOST_KEY: [(constants.SSHK_ECDSA, 'ecdsapriv', 'ecdsapub')]})\n", "method_code": " def _TestDryRun(self, data):\n prepare_node_join.UpdateSshDaemon(data, True, _runcmd_fn=NotImplemented, _keyfiles=self.keyfiles)\n self.assertEqual(os.listdir(self.tmpdir), [])\n ", "context": "class TestUpdateSshDaemon(unittest.TestCase):\n def _TestDryRun(self, data): ...\n def setUp(self): ...\n def tearDown(self): ...\n def testNoKeys(self): ...\n def testDryRunRsa(self): ...\n def testDryRunDsa(self): ...\n def testDryRunEcdsa(self): ...\n def _RunCmd(self, fail, cmd, interactive=NotImplemented): ...\n def _TestUpdate(self, failcmd): ...\n def testSuccess(self): ...\n def testFailure(self): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "testDryRunRsa", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000553.py"} {"focal_file": "test/py/ganeti.utils_unittest.py", "focal_class": null, "focal_method": "Drbd", "tests": "import unittest\n\nclass Test_Drbd(unittest.TestCase):\n def testOrDrbd(self):\n self.assertTrue(utils.AnyDiskOfType([Drbd()], [constants.DT_DISKLESS, constants.DT_DRBD8]))\n", "method_code": "def Drbd():\n return Disk(constants.DT_DRBD8)", "context": "def Drbd(): ...\ndef Disk(dev_type): ...\ndef Drbd(): ...\ndef Rbd(): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "testOrDrbd", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000554.py"} {"focal_file": "test/py/ganeti.utils_unittest.py", "focal_class": null, "focal_method": "Rbd", "tests": "import unittest\n\nclass Test_Rbd(unittest.TestCase):\n def testOrRbd(self):\n self.assertTrue(utils.AnyDiskOfType([Rbd()], [constants.DT_RBD, constants.DT_DRBD8]))\n\n def testNotRbd(self):\n self.assertFalse(utils.AnyDiskOfType([Rbd()], [constants.DT_DRBD8]))\n", "method_code": "def Rbd():\n return Disk(constants.DT_RBD)", "context": "def Rbd(): ...\ndef Disk(dev_type): ...\ndef Drbd(): ...\ndef Rbd(): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "testOrRbd", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000555.py"} {"focal_file": "test/py/ganeti.workerpool_unittest.py", "focal_class": null, "focal_method": "_CheckNoTasks", "tests": "import unittest\n\nclass Test_CheckNoTasks(unittest.TestCase):\n def testNoTasks(self):\n wp = workerpool.WorkerPool('Test', 3, CountingBaseWorker)\n try:\n self._CheckWorkerCount(wp, 3)\n self._CheckNoTasks(wp)\n finally:\n wp.TerminateWorkers()\n self._CheckWorkerCount(wp, 0)\n\n def testDeferTask(self):\n wp = workerpool.WorkerPool('Test', 1, DeferringWorker)\n try:\n self._CheckWorkerCount(wp, 1)\n ctx = DeferringTaskContext()\n rnd = random.Random(14921)\n data = {}\n num2taskid = {}\n for i in range(1, 333):\n ctx.lock.acquire()\n try:\n if i % 5 == 0:\n ctx.samepriodefer[i] = True\n finally:\n ctx.lock.release()\n prio = int(rnd.random() * 30)\n num2taskid[i] = 1000 * i\n wp.AddTask((ctx, i, prio), priority=50, task_id=num2taskid[i])\n data.setdefault(prio, set()).add(i)\n if i % 24 == 0:\n time.sleep(0.001)\n if i % 31 == 0:\n wp.Quiesce()\n wp.Quiesce()\n self._CheckNoTasks(wp)\n ctx.lock.acquire()\n try:\n self.assertEqual(data, ctx.prioresult)\n all_order_ids = []\n for num, numordertaskid in ctx.num2ordertaskid.items():\n order_ids = map(compat.fst, numordertaskid)\n self.assertFalse(utils.FindDuplicates(order_ids), msg='Order ID has been reused')\n all_order_ids.extend(order_ids)\n for task_id in map(compat.snd, numordertaskid):\n self.assertEqual(task_id, num2taskid[num], msg='Task %s used different task IDs' % num)\n self.assertFalse(utils.FindDuplicates(all_order_ids), msg='Order ID has been reused')\n finally:\n ctx.lock.release()\n self._CheckWorkerCount(wp, 1)\n finally:\n wp.TerminateWorkers()\n self._CheckWorkerCount(wp, 0)\n", "method_code": " def _CheckNoTasks(self, wp):\n wp._lock.acquire()\n try:\n self.assertFalse(wp._tasks)\n self.assertFalse(wp._taskdata)\n finally:\n wp._lock.release()\n ", "context": "class TestWorkerpool(unittest.TestCase):\n def _CheckNoTasks(self, wp): ...\n def testCounting(self): ...\n def testNoTasks(self): ...\n def testNoTasksQuiesce(self): ...\n def testChecksum(self): ...\n def testAddManyTasks(self): ...\n def testManyTasksSequence(self): ...\n def _CheckWorkerCount(self, wp, num_workers): ...\n def testPriorityChecksum(self): ...\n def testPriorityListManyTasks(self): ...\n def testPriorityListSingleTasks(self): ...\n def testDeferTask(self): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "testNoTasks", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000556.py"} {"focal_file": "test/py/ganeti.workerpool_unittest.py", "focal_class": null, "focal_method": "UpdateChecksum", "tests": "import unittest\n\nclass Test_UpdateChecksum(unittest.TestCase):\n def testChecksum(self):\n wp = workerpool.WorkerPool('Test', 1, ChecksumBaseWorker)\n try:\n self._CheckWorkerCount(wp, 1)\n ctx = ChecksumContext()\n checksum = ChecksumContext.CHECKSUM_START\n for i in range(1, 100):\n checksum = ChecksumContext.UpdateChecksum(checksum, i)\n wp.AddTask((ctx, i))\n wp.Quiesce()\n self._CheckNoTasks(wp)\n ctx.lock.acquire()\n try:\n self.assertEqual(checksum, ctx.checksum)\n finally:\n ctx.lock.release()\n finally:\n wp.TerminateWorkers()\n self._CheckWorkerCount(wp, 0)\n", "method_code": " def UpdateChecksum(current, value):\n return zlib.adler32(str(value), current)\n ", "context": "class CountingContext(object):\n @staticmethod\n def UpdateChecksum(current, value): ...\n def __init__(self): ...\n def DoneTask(self): ...\n def GetDoneTasks(self): ...\n\n self._lock = threading.Condition(threading.Lock())\n self.done = 0\n", "repository": "itminedu/snf-ganeti", "test_name": "testChecksum", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000557.py"} {"focal_file": "test/py/ganeti.workerpool_unittest.py", "focal_class": null, "focal_method": "GetDoneTasks", "tests": "import unittest\n\nclass Test_GetDoneTasks(unittest.TestCase):\n def testAddManyTasks(self):\n ctx = CountingContext()\n wp = workerpool.WorkerPool('Test', 3, CountingBaseWorker)\n try:\n self._CheckWorkerCount(wp, 3)\n wp.AddManyTasks([(ctx, 'Hello world %s' % i) for i in range(10)])\n wp.AddTask((ctx, 'A separate hello'))\n wp.AddTask((ctx, 'Once more, hi!'))\n wp.AddManyTasks([(ctx, 'Hello world %s' % i) for i in range(10)])\n wp.Quiesce()\n self._CheckNoTasks(wp)\n finally:\n wp.TerminateWorkers()\n self._CheckWorkerCount(wp, 0)\n self.assertEquals(ctx.GetDoneTasks(), 22)\n", "method_code": " def GetDoneTasks(self):\n self._lock.acquire()\n try:\n return self.done\n finally:\n self._lock.release()\n ", "context": "class CountingContext(object):\n def GetDoneTasks(self): ...\n def __init__(self): ...\n def DoneTask(self): ...\n def UpdateChecksum(current, value): ...\n\n self._lock = threading.Condition(threading.Lock())\n self.done = 0\n", "repository": "itminedu/snf-ganeti", "test_name": "testAddManyTasks", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000558.py"} {"focal_file": "test/py/cmdlib/cluster_unittest.py", "focal_class": null, "focal_method": "_AssertCertFiles", "tests": "import unittest\n\nclass Test_AssertCertFiles(unittest.TestCase):\n @patchPathutils('cluster')\n def testNonMasterFails(self, pathutils):\n self._InitPathutils(pathutils)\n num_nodes = 3\n for _ in range(num_nodes):\n self.cfg.AddNewNode()\n nodes = self.cfg.GetAllNodesInfo()\n master_uuid = self.cfg.GetMasterNode()\n self._failed_node = [node_uuid for node_uuid in nodes if node_uuid != master_uuid][1]\n self.rpc.call_node_crypto_tokens = self._partiallyFailingRpc\n op = opcodes.OpClusterRenewCrypto(node_certificates=True)\n self.ExecOpCode(op)\n self._AssertCertFiles(pathutils)\n cluster = self.cfg.GetClusterInfo()\n self.assertEqual(num_nodes, len(cluster.candidate_certs))\n nodes = self.cfg.GetAllNodesInfo()\n for node_uuid, _ in nodes.items():\n if node_uuid == self._failed_node:\n self.assertTrue(node_uuid not in cluster.candidate_certs)\n else:\n self.assertTrue(node_uuid in cluster.candidate_certs)\n", "method_code": " def _AssertCertFiles(self, pathutils):\n \"\"\"Check if the correct certificates exist and don't exist on the master.\n \n \"\"\"\n self.assertTrue(os.path.exists(pathutils.NODED_CERT_FILE))\n self.assertTrue(os.path.exists(pathutils.NODED_CLIENT_CERT_FILE))\n ", "context": "class TestLUClusterRenewCrypto(CmdlibTestCase):\n def _AssertCertFiles(self, pathutils): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _GetFakeDigest(self, uuid): ...\n def _InitPathutils(self, pathutils): ...\n def _CompletelySuccessfulRpc(self, node_uuid, _): ...\n def testSuccessfulCase(self, pathutils): ...\n def _partiallyFailingRpc(self, node_uuid, _): ...\n def testNonMasterFails(self, pathutils): ...\n def testOfflineNodes(self, pathutils): ...\n def _RpcSuccessfulAfterRetries(self, node_uuid, _): ...\n def _RpcSuccessfulAfterRetriesNonMaster(self, node_uuid, _): ...\n def _NonMasterRetries(self, pathutils, max_retries): ...\n def testNonMasterRetriesSuccess(self, pathutils): ...\n def testNonMasterRetriesFail(self, pathutils): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000559.py"} {"focal_file": "test/py/cmdlib/cluster_unittest.py", "focal_class": null, "focal_method": "_NonMasterRetries", "tests": "import unittest\n\nclass Test_NonMasterRetries(unittest.TestCase):\n @patchPathutils('cluster')\n def testNonMasterRetriesSuccess(self, pathutils):\n cluster = self._NonMasterRetries(pathutils, 2)\n self.assertEqual(2, len(cluster.candidate_certs.values()))\n\n @patchPathutils('cluster')\n def testNonMasterRetriesFail(self, pathutils):\n cluster = self._NonMasterRetries(pathutils, 5)\n self.assertEqual(1, len(cluster.candidate_certs.values()))\n self.assertTrue(self._master_uuid in cluster.candidate_certs)\n", "method_code": " def _NonMasterRetries(self, pathutils, max_retries):\n self._InitPathutils(pathutils)\n self._master_uuid = self.cfg.GetMasterNode()\n self._max_retries = max_retries\n self._retries = 0\n self.rpc.call_node_crypto_tokens = self._RpcSuccessfulAfterRetriesNonMaster\n self.cfg.AddNewNode()\n op = opcodes.OpClusterRenewCrypto(node_certificates=True)\n self.ExecOpCode(op)\n self._AssertCertFiles(pathutils)\n return self.cfg.GetClusterInfo()\n ", "context": "class TestLUClusterRenewCrypto(CmdlibTestCase):\n def _NonMasterRetries(self, pathutils, max_retries): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _GetFakeDigest(self, uuid): ...\n def _InitPathutils(self, pathutils): ...\n def _AssertCertFiles(self, pathutils): ...\n def _CompletelySuccessfulRpc(self, node_uuid, _): ...\n def testSuccessfulCase(self, pathutils): ...\n def _partiallyFailingRpc(self, node_uuid, _): ...\n def testNonMasterFails(self, pathutils): ...\n def testOfflineNodes(self, pathutils): ...\n def _RpcSuccessfulAfterRetries(self, node_uuid, _): ...\n def _RpcSuccessfulAfterRetriesNonMaster(self, node_uuid, _): ...\n def testNonMasterRetriesSuccess(self, pathutils): ...\n def testNonMasterRetriesFail(self, pathutils): ...\n", "repository": "itminedu/snf-ganeti", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000560.py"} {"focal_file": "test/py/cmdlib/cmdlib_unittest.py", "focal_class": null, "focal_method": "_TestSet", "tests": "import unittest\n\nclass Test_TestSet(unittest.TestCase):\n def testSet(self):\n diff_policy = {constants.IPOLICY_VCPU_RATIO: 3, constants.IPOLICY_DTS: [constants.DT_FILE]}\n self._TestSet(self._OLD_GROUP_POLICY, diff_policy, True)\n self._TestSetSpecs(self._OLD_GROUP_POLICY, True)\n self._TestSet({}, diff_policy, True)\n self._TestSetSpecs({}, True)\n self._TestSet(self._OLD_CLUSTER_POLICY, diff_policy, False)\n self._TestSetSpecs(self._OLD_CLUSTER_POLICY, False)\n", "method_code": " def _TestSet(self, old_policy, diff_policy, isgroup):\n new_policy = common.GetUpdatedIPolicy(old_policy, diff_policy, group_policy=isgroup)\n for key in diff_policy:\n self.assertTrue(key in new_policy)\n self.assertEqual(new_policy[key], diff_policy[key])\n for key in old_policy:\n if not key in diff_policy:\n self.assertTrue(key in new_policy)\n self.assertEqual(new_policy[key], old_policy[key])\n ", "context": "class TestGetUpdatedIPolicy(unittest.TestCase):\n def _TestSet(self, old_policy, diff_policy, isgroup): ...\n def _TestSetSpecs(self, old_policy, isgroup): ...\n def testSet(self): ...\n def testUnset(self): ...\n def testUnsetEmpty(self): ...\n def _TestInvalidKeys(self, old_policy, isgroup): ...\n def testInvalidKeys(self): ...\n def testInvalidValues(self): ...\n\n _OLD_CLUSTER_POLICY = {constants.IPOLICY_VCPU_RATIO: 1.5, constants.ISPECS_MINMAX: [{constants.ISPECS_MIN: {constants.ISPEC_MEM_SIZE: 32768, constants.ISPEC_CPU_COUNT: 8, constants.ISPEC_DISK_COUNT: 1, constants.ISPEC_DISK_SIZE: 1024, constants.ISPEC_NIC_COUNT: 1, constants.ISPEC_SPINDLE_USE: 1}, constants.ISPECS_MAX: {constants.ISPEC_MEM_SIZE: 65536, constants.ISPEC_CPU_COUNT: 10, constants.ISPEC_DISK_COUNT: 5, constants.ISPEC_DISK_SIZE: 1024 * 1024, constants.ISPEC_NIC_COUNT: 3, constants.ISPEC_SPINDLE_USE: 12}}, constants.ISPECS_MINMAX_DEFAULTS], constants.ISPECS_STD: constants.IPOLICY_DEFAULTS[constants.ISPECS_STD]}\n _OLD_GROUP_POLICY = {constants.IPOLICY_SPINDLE_RATIO: 2.5, constants.ISPECS_MINMAX: [{constants.ISPECS_MIN: {constants.ISPEC_MEM_SIZE: 128, constants.ISPEC_CPU_COUNT: 1, constants.ISPEC_DISK_COUNT: 1, constants.ISPEC_DISK_SIZE: 1024, constants.ISPEC_NIC_COUNT: 1, constants.ISPEC_SPINDLE_USE: 1}, constants.ISPECS_MAX: {constants.ISPEC_MEM_SIZE: 32768, constants.ISPEC_CPU_COUNT: 8, constants.ISPEC_DISK_COUNT: 5, constants.ISPEC_DISK_SIZE: 1024 * 1024, constants.ISPEC_NIC_COUNT: 3, constants.ISPEC_SPINDLE_USE: 12}}]}\n", "repository": "itminedu/snf-ganeti", "test_name": "testSet", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000561.py"} {"focal_file": "test/py/cmdlib/cmdlib_unittest.py", "focal_class": null, "focal_method": "_TestInvalidKeys", "tests": "import unittest\n\nclass Test_TestInvalidKeys(unittest.TestCase):\n def testInvalidKeys(self):\n self._TestInvalidKeys(self._OLD_GROUP_POLICY, True)\n self._TestInvalidKeys(self._OLD_CLUSTER_POLICY, False)\n", "method_code": " def _TestInvalidKeys(self, old_policy, isgroup):\n INVALID_KEY = 'this_key_shouldnt_be_allowed'\n INVALID_DICT = {INVALID_KEY: 3}\n invalid_policy = INVALID_DICT\n self.assertRaises(errors.OpPrereqError, common.GetUpdatedIPolicy, old_policy, invalid_policy, group_policy=isgroup)\n invalid_ispecs = {constants.ISPECS_MINMAX: [INVALID_DICT]}\n self.assertRaises(errors.TypeEnforcementError, common.GetUpdatedIPolicy, old_policy, invalid_ispecs, group_policy=isgroup)\n if isgroup:\n invalid_for_group = {constants.ISPECS_STD: constants.IPOLICY_DEFAULTS[constants.ISPECS_STD]}\n self.assertRaises(errors.OpPrereqError, common.GetUpdatedIPolicy, old_policy, invalid_for_group, group_policy=isgroup)\n good_ispecs = self._OLD_CLUSTER_POLICY[constants.ISPECS_MINMAX]\n invalid_ispecs = copy.deepcopy(good_ispecs)\n invalid_policy = {constants.ISPECS_MINMAX: invalid_ispecs}\n for minmax in invalid_ispecs:\n for key in constants.ISPECS_MINMAX_KEYS:\n ispec = minmax[key]\n ispec[INVALID_KEY] = None\n self.assertRaises(errors.TypeEnforcementError, common.GetUpdatedIPolicy, old_policy, invalid_policy, group_policy=isgroup)\n del ispec[INVALID_KEY]\n for par in constants.ISPECS_PARAMETERS:\n oldv = ispec[par]\n ispec[par] = 'this_is_not_good'\n self.assertRaises(errors.TypeEnforcementError, common.GetUpdatedIPolicy, old_policy, invalid_policy, group_policy=isgroup)\n ispec[par] = oldv\n common.GetUpdatedIPolicy(old_policy, invalid_policy, group_policy=isgroup)\n ", "context": "class TestGetUpdatedIPolicy(unittest.TestCase):\n def _TestInvalidKeys(self, old_policy, isgroup): ...\n def _TestSetSpecs(self, old_policy, isgroup): ...\n def _TestSet(self, old_policy, diff_policy, isgroup): ...\n def testSet(self): ...\n def testUnset(self): ...\n def testUnsetEmpty(self): ...\n def testInvalidKeys(self): ...\n def testInvalidValues(self): ...\n\n _OLD_CLUSTER_POLICY = {constants.IPOLICY_VCPU_RATIO: 1.5, constants.ISPECS_MINMAX: [{constants.ISPECS_MIN: {constants.ISPEC_MEM_SIZE: 32768, constants.ISPEC_CPU_COUNT: 8, constants.ISPEC_DISK_COUNT: 1, constants.ISPEC_DISK_SIZE: 1024, constants.ISPEC_NIC_COUNT: 1, constants.ISPEC_SPINDLE_USE: 1}, constants.ISPECS_MAX: {constants.ISPEC_MEM_SIZE: 65536, constants.ISPEC_CPU_COUNT: 10, constants.ISPEC_DISK_COUNT: 5, constants.ISPEC_DISK_SIZE: 1024 * 1024, constants.ISPEC_NIC_COUNT: 3, constants.ISPEC_SPINDLE_USE: 12}}, constants.ISPECS_MINMAX_DEFAULTS], constants.ISPECS_STD: constants.IPOLICY_DEFAULTS[constants.ISPECS_STD]}\n _OLD_GROUP_POLICY = {constants.IPOLICY_SPINDLE_RATIO: 2.5, constants.ISPECS_MINMAX: [{constants.ISPECS_MIN: {constants.ISPEC_MEM_SIZE: 128, constants.ISPEC_CPU_COUNT: 1, constants.ISPEC_DISK_COUNT: 1, constants.ISPEC_DISK_SIZE: 1024, constants.ISPEC_NIC_COUNT: 1, constants.ISPEC_SPINDLE_USE: 1}, constants.ISPECS_MAX: {constants.ISPEC_MEM_SIZE: 32768, constants.ISPEC_CPU_COUNT: 8, constants.ISPEC_DISK_COUNT: 5, constants.ISPEC_DISK_SIZE: 1024 * 1024, constants.ISPEC_NIC_COUNT: 3, constants.ISPEC_SPINDLE_USE: 12}}]}\n", "repository": "itminedu/snf-ganeti", "test_name": "testInvalidKeys", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000562.py"} {"focal_file": "organizer_app.py", "focal_class": null, "focal_method": "get_extensions", "tests": "import unittest\n\nclass Test_get_extensions(unittest.TestCase):\n def test_move_files_no_extension(self):\n extensions = self.organizer.get_extensions(self.files)\n self.organizer.create_folders(extensions, self.test_dir)\n self.organizer.move_files(self.files, self.test_dir)\n self.assertTrue(isfile(f'{self.test_dir}/Other/No extension/noext.'))\n\n def test_get_extensions(self):\n extensions = self.organizer.get_extensions(self.files)\n self.assertEqual({'Jpg', 'No extension', 'Mp3', 'Mp4', 'Py'}, extensions)\n", "method_code": " def get_extensions(files):\n \"\"\"return a list of all the extensions in the directory\"\"\"\n extensions = set()\n for file in files:\n extension = file.split('.')[1].lower().capitalize()\n if extension:\n extensions.add(extension)\n elif not extension and (not file.startswith('.')):\n extensions.add('No extension')\n logging.info(f'extensions found: {extensions}')\n return extensions\n ", "context": "class FileOrganizer():\n @staticmethod\n def get_extensions(files): ...\n def __init__(self): ...\n def get_new_name(file_path): ...\n def get_type(self, extension): ...\n def move_rename(self, src, dst): ...\n def get_files_list(path): ...\n def create_folders(self, extensions, path): ...\n def move_files(self, files, path): ...\n def run_app(self, path): ...\n\n self.files_list = []\n self.extensions_list = []\n", "repository": "AcrobaticPanicc/Auto-File-Organizer", "test_name": "test_move_files_no_extension", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000563.py"} {"focal_file": "organizer_app.py", "focal_class": null, "focal_method": "get_new_name", "tests": "import unittest\n\nclass Test_get_new_name(unittest.TestCase):\n def test_get_new_name(self):\n new_name = self.organizer.get_new_name(self.file_path)\n self.assertEqual(f'{self.test_dir}/play (2).py', new_name)\n", "method_code": " def get_new_name(file_path):\n \"\"\"return a new file name. used in case the file already exists in DST folder\"\"\"\n file_name, ext = splitext(file_path)\n if not ext:\n new_file_name = file_name + ' ' + '(2)'\n return new_file_name\n else:\n new_file_name = file_name + ' ' + '(2)' + ext\n return new_file_name\n ", "context": "class FileOrganizer():\n @staticmethod\n def get_new_name(file_path): ...\n def __init__(self): ...\n def get_type(self, extension): ...\n def move_rename(self, src, dst): ...\n def get_files_list(path): ...\n def get_extensions(files): ...\n def create_folders(self, extensions, path): ...\n def move_files(self, files, path): ...\n def run_app(self, path): ...\n\n self.files_list = []\n self.extensions_list = []\n", "repository": "AcrobaticPanicc/Auto-File-Organizer", "test_name": "test_get_new_name", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000564.py"} {"focal_file": "organizer_app.py", "focal_class": null, "focal_method": "get_files_list", "tests": "import unittest\n\nclass Test_get_files_list(unittest.TestCase):\n def test_get_files_list(self):\n files_list = self.organizer.get_files_list(self.test_dir)\n self.assertEqual(['img.jpg', 'play.py', 'music.mp3', 'IMG_2328.mp4', 'noext.'], files_list)\n", "method_code": " def get_files_list(path):\n \"\"\"return a list of all the files in the directory\"\"\"\n files = []\n for file in listdir(path):\n if isfile(join(path, file)) and (not file.startswith('.')):\n files.append(file)\n logging.info(f'Files found: {files}')\n return files\n ", "context": "class FileOrganizer():\n @staticmethod\n def get_files_list(path): ...\n def __init__(self): ...\n def get_new_name(file_path): ...\n def get_type(self, extension): ...\n def move_rename(self, src, dst): ...\n def get_extensions(files): ...\n def create_folders(self, extensions, path): ...\n def move_files(self, files, path): ...\n def run_app(self, path): ...\n\n self.files_list = []\n self.extensions_list = []\n", "repository": "AcrobaticPanicc/Auto-File-Organizer", "test_name": "test_get_files_list", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000565.py"} {"focal_file": "organizer_app.py", "focal_class": null, "focal_method": "create_folders", "tests": "import unittest\n\nclass Test_create_folders(unittest.TestCase):\n def test_create_folder_audio(self):\n self.organizer.create_folders(self.extensions, self.test_dir)\n self.assertTrue(isdir(f'{self.test_dir}/audio'))\n\n def test_create_folder_other(self):\n self.organizer.create_folders(self.extensions, self.test_dir)\n self.assertTrue(isdir(f'{self.test_dir}/Other/otherext'))\n\n def test_create_folder_no_ext(self):\n self.organizer.create_folders(self.extensions, self.test_dir)\n self.assertTrue(isdir(f'{self.test_dir}/No extension'))\n", "method_code": " def create_folders(self, extensions, path):\n \"\"\"create folders by the types of the files by extensions\"\"\"\n for extension in extensions:\n file_type = self.get_type(extension)['type']\n if file_type != 'Other':\n makedirs(f'{path}/{file_type}', exist_ok=True)\n logging.info(f'folder created {f'{path}/{file_type}'}')\n else:\n makedirs(f'{path}/Other/{extension}', exist_ok=True)\n logging.info(f'folder created f\"{path}/Other/{extension}\"')\n ", "context": "class FileOrganizer():\n def create_folders(self, extensions, path): ...\n def __init__(self): ...\n def get_new_name(file_path): ...\n def get_type(self, extension): ...\n def move_rename(self, src, dst): ...\n def get_files_list(path): ...\n def get_extensions(files): ...\n def move_files(self, files, path): ...\n def run_app(self, path): ...\n\n self.files_list = []\n self.extensions_list = []\n", "repository": "AcrobaticPanicc/Auto-File-Organizer", "test_name": "test_create_folder_audio", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000566.py"} {"focal_file": "getNotebooks.py", "focal_class": null, "focal_method": "create_db", "tests": "import unittest\n\nclass Test_create_db(unittest.TestCase):\n def test_create_db(self):\n getNotebooks.init_wf()\n getNotebooks.create_db()\n", "method_code": "def create_db():\n sql = queries.create_merged_db()\n conn = create_connection(wf.datafile(MERGED_DB))\n cur = conn.cursor()\n lines = sql.splitlines()\n for line in lines:\n if line is not '':\n cur.execute(str(line))\n conn.commit()", "context": "def create_db(): ...\ndef get_page_path(ni): ...\ndef get_parent_row(parent_goid): ...\ndef get_parent_path(item): ...\ndef get_row_by_guid(uid): ...\ndef get_row_by_goid(goid): ...\ndef get_children(ni): ...\ndef create_db(): ...\ndef update_db(): ...\ndef reset_db(): ...\ndef update_path_map(): ...\ndef update_notebook_items(): ...\ndef get_page_name(GUID): ...\ndef populate_query(args): ...\ndef run_query(sql): ...\ndef create_connection(db_file): ...\ndef get_results(sql): ...\ndef build_wf_items(results, args): ...\ndef parse_args(): ...\ndef encode_url(url): ...\ndef open_url(url): ...\ndef clear_config(): ...\ndef init_wf(): ...\ndef main(wf): ...\n", "repository": "kevin-funderburg/alfred-microsoft-onenote-navigator", "test_name": "test_create_db", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000567.py"} {"focal_file": "getNotebooks.py", "focal_class": null, "focal_method": "get_children", "tests": "import unittest\n\nclass Test_get_children(unittest.TestCase):\n def test_get_children(self):\n getNotebooks.init_wf()\n item = getNotebooks.NotebookItem(getNotebooks.get_row_by_goid('{9E1EACD4-A21C-B947-9E83-C599172503C6}{20}'))\n children = getNotebooks.get_children(item)\n", "method_code": "def get_children(ni):\n results = run_query(queries.get_children(ni))\n return results", "context": "def get_children(ni): ...\ndef get_page_path(ni): ...\ndef get_parent_row(parent_goid): ...\ndef get_parent_path(item): ...\ndef get_row_by_guid(uid): ...\ndef get_row_by_goid(goid): ...\ndef get_children(ni): ...\ndef create_db(): ...\ndef update_db(): ...\ndef reset_db(): ...\ndef update_path_map(): ...\ndef update_notebook_items(): ...\ndef get_page_name(GUID): ...\ndef populate_query(args): ...\ndef run_query(sql): ...\ndef create_connection(db_file): ...\ndef get_results(sql): ...\ndef build_wf_items(results, args): ...\ndef parse_args(): ...\ndef encode_url(url): ...\ndef open_url(url): ...\ndef clear_config(): ...\ndef init_wf(): ...\ndef main(wf): ...\n", "repository": "kevin-funderburg/alfred-microsoft-onenote-navigator", "test_name": "test_get_children", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000568.py"} {"focal_file": "getNotebooks.py", "focal_class": null, "focal_method": "get_page_name", "tests": "import unittest\n\nclass Test_get_page_name(unittest.TestCase):\n def test_get_page_name(self):\n getNotebooks.init_wf()\n getNotebooks.get_page_name('{F79D225A-2386-9B48-9D84-68A8AD85A679}')\n", "method_code": "def get_page_name(GUID):\n conn = create_connection(wf.datafile(MERGED_DB))\n conn.text_factory = unicode\n cur = conn.cursor()\n cur.execute(str('SELECT * FROM Entities WHERE GUID = \"{0}\"'.format(GUID)))\n r = cur.fetchone()\n return r", "context": "def get_page_name(GUID): ...\ndef get_page_path(ni): ...\ndef get_parent_row(parent_goid): ...\ndef get_parent_path(item): ...\ndef get_row_by_guid(uid): ...\ndef get_row_by_goid(goid): ...\ndef get_children(ni): ...\ndef create_db(): ...\ndef update_db(): ...\ndef reset_db(): ...\ndef update_path_map(): ...\ndef update_notebook_items(): ...\ndef get_page_name(GUID): ...\ndef populate_query(args): ...\ndef run_query(sql): ...\ndef create_connection(db_file): ...\ndef get_results(sql): ...\ndef build_wf_items(results, args): ...\ndef parse_args(): ...\ndef encode_url(url): ...\ndef open_url(url): ...\ndef clear_config(): ...\ndef init_wf(): ...\ndef main(wf): ...\n", "repository": "kevin-funderburg/alfred-microsoft-onenote-navigator", "test_name": "test_get_page_name", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000569.py"} {"focal_file": "getNotebooks.py", "focal_class": null, "focal_method": "open_url", "tests": "import unittest\n\nclass Test_open_url(unittest.TestCase):\n def test_open_url(self):\n getNotebooks.init_wf()\n item = getNotebooks.NotebookItem(getNotebooks.get_row_by_guid('{8392576E-34AB-2F40-A1F3-46B5ECF3E17A}'))\n url = getNotebooks.make_url(item)\n getNotebooks.open_url(url)\n\n @unittest.expectedFailure\n def test_open_url_fail(self):\n with self.assertRaises(Exception, getNotebooks.open_url(None)) as cm:\n the_exception = cm.exception\n print(the_exception)\n", "method_code": "def open_url(url):\n run_command(['open', encode_url(url)])", "context": "def open_url(url): ...\ndef get_page_path(ni): ...\ndef get_parent_row(parent_goid): ...\ndef get_parent_path(item): ...\ndef get_row_by_guid(uid): ...\ndef get_row_by_goid(goid): ...\ndef get_children(ni): ...\ndef create_db(): ...\ndef update_db(): ...\ndef reset_db(): ...\ndef update_path_map(): ...\ndef update_notebook_items(): ...\ndef get_page_name(GUID): ...\ndef populate_query(args): ...\ndef run_query(sql): ...\ndef create_connection(db_file): ...\ndef get_results(sql): ...\ndef build_wf_items(results, args): ...\ndef parse_args(): ...\ndef encode_url(url): ...\ndef open_url(url): ...\ndef clear_config(): ...\ndef init_wf(): ...\ndef main(wf): ...\n", "repository": "kevin-funderburg/alfred-microsoft-onenote-navigator", "test_name": "test_open_url", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_000570.py"} {"focal_file": "traceview/api.py", "focal_class": null, "focal_method": "_build_query_params", "tests": "import unittest\n\nclass Test_build_query_params(unittest.TestCase):\n def test_build_query_params(self):\n actual = self.api._build_query_params({'foo': 'bar', 'lol': 5})\n expected = {'key': 'ABC123', 'foo': 'bar', 'lol': 5}\n self.assertEqual(actual, expected)\n\n def test_build_query_params_bad_args(self):\n actual = self.api._build_query_params([])\n self.assertNotEqual(actual, None)\n self.assertIsInstance(actual, dict)\n\n def test_build_query_params_no_args(self):\n actual = self.api._build_query_params()\n expected = {'key': 'ABC123'}\n self.assertEqual(actual, expected)\n", "method_code": " def _build_query_params(self, params=None):\n \"\"\" Builds and returns a Dictionary of query parameters.\n \n :params: (optional) Dictionary of query parameters.\n \n \"\"\"\n if not isinstance(params, dict):\n params = {}\n params.update({'key': self._api_key})\n return params\n ", "context": "class Api(object):\n def _build_query_params(self, params=None): ...\n def __init__(self, api_key, after_request=None): ...\n def get(self, path, *args, **kwargs): ...\n def post(self, path, *args, **kwargs): ...\n def delete(self, path, *args, **kwargs): ...\n def _request(self, method, path, *args, **kwargs): ...\n def _url(self, path): ...\n\n self._api_key = api_key\n self._after_request = after_request\n\n AUTHORITY = 'https://api.tv.appneta.com'\n VERSION = 'api-v2'\n __methods = ['get', 'post', 'delete']\n", "repository": "danriti/python-traceview", "test_name": "test_build_query_params", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000571.py"} {"focal_file": "traceview/api.py", "focal_class": null, "focal_method": "_url", "tests": "import unittest\n\nclass Test_url(unittest.TestCase):\n def test_url(self):\n self.assertEqual(self.api._url('lol'), 'https://api.tv.appneta.com/api-v2/lol')\n", "method_code": " def _url(self, path):\n return '{0}/{1}/{2}'.format(self.AUTHORITY, self.VERSION, path)\n ", "context": "class Api(object):\n def _url(self, path): ...\n def __init__(self, api_key, after_request=None): ...\n def get(self, path, *args, **kwargs): ...\n def post(self, path, *args, **kwargs): ...\n def delete(self, path, *args, **kwargs): ...\n def _request(self, method, path, *args, **kwargs): ...\n def _build_query_params(self, params=None): ...\n\n self._api_key = api_key\n self._after_request = after_request\n\n AUTHORITY = 'https://api.tv.appneta.com'\n VERSION = 'api-v2'\n __methods = ['get', 'post', 'delete']\n", "repository": "danriti/python-traceview", "test_name": "test_url", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000572.py"} {"focal_file": "traceview/api.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n @with_httmock(traceview_api_mock)\n def test_request_get(self):\n results = self.api.get('lol')\n self.assertNotEqual(results, None)\n self.assertIsInstance(results, dict)\n", "method_code": " def get(self, path, *args, **kwargs):\n \"\"\" Perform a HTTP GET request.\n \n :param dict kwargs: (optional) Query parameters for the request.\n \n \"\"\"\n return self._request(*args, method='get', path=path, **kwargs)\n ", "context": "class Api(object):\n def get(self, path, *args, **kwargs): ...\n def __init__(self, api_key, after_request=None): ...\n def post(self, path, *args, **kwargs): ...\n def delete(self, path, *args, **kwargs): ...\n def _request(self, method, path, *args, **kwargs): ...\n def _url(self, path): ...\n def _build_query_params(self, params=None): ...\n\n self._api_key = api_key\n self._after_request = after_request\n\n AUTHORITY = 'https://api.tv.appneta.com'\n VERSION = 'api-v2'\n __methods = ['get', 'post', 'delete']\n", "repository": "danriti/python-traceview", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000573.py"} {"focal_file": "traceview/api.py", "focal_class": null, "focal_method": "post", "tests": "import unittest\n\nclass Test_post(unittest.TestCase):\n @with_httmock(traceview_api_mock)\n def test_request_post(self):\n results = self.api.post('lol')\n self.assertNotEqual(results, None)\n self.assertIsInstance(results, dict)\n", "method_code": " def post(self, path, *args, **kwargs):\n \"\"\" Perform a HTTP POST request.\n \n :param dict kwargs: (optional) Query parameters for the request.\n \n \"\"\"\n return self._request(*args, method='post', path=path, **kwargs)\n ", "context": "class Api(object):\n def post(self, path, *args, **kwargs): ...\n def __init__(self, api_key, after_request=None): ...\n def get(self, path, *args, **kwargs): ...\n def delete(self, path, *args, **kwargs): ...\n def _request(self, method, path, *args, **kwargs): ...\n def _url(self, path): ...\n def _build_query_params(self, params=None): ...\n\n self._api_key = api_key\n self._after_request = after_request\n\n AUTHORITY = 'https://api.tv.appneta.com'\n VERSION = 'api-v2'\n __methods = ['get', 'post', 'delete']\n", "repository": "danriti/python-traceview", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000574.py"} {"focal_file": "traceview/api.py", "focal_class": null, "focal_method": "delete", "tests": "import unittest\n\nclass Test_delete(unittest.TestCase):\n @with_httmock(traceview_api_mock)\n def test_request_delete(self):\n results = self.api.delete('lol')\n self.assertNotEqual(results, None)\n self.assertIsInstance(results, dict)\n", "method_code": " def delete(self, path, *args, **kwargs):\n \"\"\" Perform a HTTP DELETE request.\n \n :param dict kwargs: (optional) Query paramters for the request.\n \n \"\"\"\n return self._request(*args, method='delete', path=path, **kwargs)\n ", "context": "class Api(object):\n def delete(self, path, *args, **kwargs): ...\n def __init__(self, api_key, after_request=None): ...\n def get(self, path, *args, **kwargs): ...\n def post(self, path, *args, **kwargs): ...\n def _request(self, method, path, *args, **kwargs): ...\n def _url(self, path): ...\n def _build_query_params(self, params=None): ...\n\n self._api_key = api_key\n self._after_request = after_request\n\n AUTHORITY = 'https://api.tv.appneta.com'\n VERSION = 'api-v2'\n __methods = ['get', 'post', 'delete']\n", "repository": "danriti/python-traceview", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000575.py"} {"focal_file": "traceview/formatters.py", "focal_class": null, "focal_method": "tuplify", "tests": "import unittest\n\nclass Test_tuplify(unittest.TestCase):\n def test_tuplify_length(self):\n actual = tuplify(self.results)\n self.assertEqual(actual.total_requests, 980)\n self.assertEqual(actual.reqs_per_time_period, '0.27/sec')\n\n def test_tuplify_name(self):\n actual = tuplify(self.results, 'Lol')\n self.assertEqual(actual[0].__class__.__name__, 'LolTuple')\n\n def test_tuplify_list(self):\n results = [u'Default', u'gif_snarfer', u'box_salmond_ca', u'heheh']\n actual = tuplify(results)\n self.assertEqual(actual, results)\n", "method_code": "def tuplify(results, class_name='Result'):\n \"\"\" Formats API results into :class:`namedtuple` objects. Supports\n tuplifying results that are either timeseries data or objects (dicts).\n\n :param results: TraceView API results.\n :param str class_name: (optional) Prefix string for name of the namedtuple.\n\n Usage::\n\n >>> import traceview\n >>> from traceview.formatters import tuplify\n >>> tv = traceview.TraceView('API KEY HERE', tuplify)\n >>> tv.total_requests.summary('APP NAME HERE')\n ResultTuple(reqs_per_time_period=u'19.53/sec', total_requests=70293.0)\n\n \"\"\"\n if 'fields' in results and 'items' in results:\n return _tuplify_timeseries(results, class_name)\n if hasattr(results, 'keys'):\n return _tuplify_dict(results, class_name)\n return results", "context": "def tuplify(results, class_name='Result'): ...\ndef identity(results): ...\ndef tuplify(results, class_name='Result'): ...\ndef _tuplify_timeseries(results, class_name): ...\ndef _tuplify_dict(results, class_name): ...\n", "repository": "danriti/python-traceview", "test_name": "test_tuplify_length", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000576.py"} {"focal_file": "python/src/mapreduce/context.py", "focal_class": null, "focal_method": "append", "tests": "import unittest\n\nclass Test_append(unittest.TestCase):\n def testAppend(self):\n \"\"\"Test append method.\"\"\"\n self.assertEquals([], self.list.items)\n self.assertEquals(0, self.list.size)\n self.list.append('abc', 100)\n self.assertEquals(['abc'], self.list.items)\n self.assertEquals(100, self.list.size)\n", "method_code": " def append(self, item, item_size):\n \"\"\"Add new item to the list.\n \n Args:\n item: an item to add to the list.\n item_size: item size in bytes as int.\n \"\"\"\n self.items.append(item)\n self.length += 1\n self.size += item_size\n ", "context": "class ItemList(object):\n def append(self, item, item_size): ...\n def __init__(self): ...\n def clear(self): ...\n def entities(self): ...\n\n self.items = []\n self.length = 0\n self.size = 0\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testAppend", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000577.py"} {"focal_file": "python/src/mapreduce/context.py", "focal_class": null, "focal_method": "clear", "tests": "import unittest\n\nclass Test_clear(unittest.TestCase):\n def testClear(self):\n \"\"\"Test clear method.\"\"\"\n self.list.append('abc', 100)\n self.assertEquals(['abc'], self.list.items)\n self.assertEquals(100, self.list.size)\n self.list.clear()\n self.assertEquals([], self.list.items)\n self.assertEquals(0, self.list.size)\n", "method_code": " def clear(self):\n \"\"\"Clear item list.\"\"\"\n self.items = []\n self.length = 0\n self.size = 0\n ", "context": "class ItemList(object):\n def clear(self): ...\n def __init__(self): ...\n def append(self, item, item_size): ...\n def entities(self): ...\n\n self.items = []\n self.length = 0\n self.size = 0\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testClear", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000578.py"} {"focal_file": "python/src/mapreduce/context.py", "focal_class": "mapreduce.context.Counters", "focal_method": "increment", "tests": "import unittest\n\nclass Test_mapreduce_context_Counters_increment(unittest.TestCase):\n def testIncrement(self):\n \"\"\"Test increment() method.\"\"\"\n m = mox.Mox()\n shard_state = m.CreateMockAnything()\n counters_map = m.CreateMockAnything()\n shard_state.counters_map = counters_map\n counters = context.Counters(shard_state)\n counters_map.increment('test', 19)\n m.ReplayAll()\n try:\n counters.increment('test', 19)\n m.VerifyAll()\n finally:\n m.UnsetStubs()\n", "method_code": " def increment(self, counter_name, delta=1):\n \"\"\"Increment counter value.\n \n Args:\n counter_name: name of the counter as string.\n delta: increment delta as int.\n \"\"\"\n self._shard_state.counters_map.increment(counter_name, delta)\n ", "context": "class Counters(object):\n def increment(self, counter_name, delta=1): ...\n def __init__(self, shard_state): ...\n def flush(self): ...\n\n self._shard_state = shard_state\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testIncrement", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000579.py"} {"focal_file": "python/src/mapreduce/context.py", "focal_class": "mapreduce.context.Counters", "focal_method": "flush", "tests": "import unittest\n\nclass Test_mapreduce_context_Counters_flush(unittest.TestCase):\n def testFlush(self):\n \"\"\"Test flush() method.\"\"\"\n counters = context.Counters(None)\n counters.flush()\n", "method_code": " def flush(self):\n \"\"\"Flush(apply) all changed to datastore.\"\"\"\n self.__flush_puts()\n self.__flush_deletes()\n self.__flush_ndb_puts()\n self.__flush_ndb_deletes()\n ", "context": "class MutationPool(object):\n def flush(self): ...\n def __init__(self, max_pool_size=MAX_POOL_SIZE, max_entity_count=MAX_ENTITY_COUNT, mapreduce_spec=None): ...\n def put(self, entity): ...\n def ndb_put(self, entity): ...\n def delete(self, entity): ...\n def ndb_delete(self, entity_or_key): ...\n def __flush_puts(self): ...\n def __flush_deletes(self): ...\n def __flush_ndb_puts(self): ...\n def __flush_ndb_deletes(self): ...\n def __create_config(self): ...\n\n self.max_pool_size = max_pool_size\n self.max_entity_count = max_entity_count\n self.force_writes = bool(params.get('force_ops_writes', False))\n self.puts = ItemList()\n self.deletes = ItemList()\n self.ndb_puts = ItemList()\n self.ndb_deletes = ItemList()\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testFlush", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000580.py"} {"focal_file": "python/src/mapreduce/main.py", "focal_class": null, "focal_method": "create_application", "tests": "import unittest\n\nclass Test_create_application(unittest.TestCase):\n def testCreateApplication(self):\n \"\"\"Test create_application function.\n\n Verify that it gets all import right.\n \"\"\"\n main.create_application()\n", "method_code": "def create_application():\n \"\"\"Create new WSGIApplication and register all handlers.\n\n Returns:\n an instance of webapp.WSGIApplication with all mapreduce handlers\n registered.\n \"\"\"\n return webapp.WSGIApplication(create_handlers_map(), debug=True)", "context": "def create_application(): ...\ndef create_handlers_map(): ...\ndef create_application(): ...\ndef main(): ...\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testCreateApplication", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000581.py"} {"focal_file": "python/src/mapreduce/model.py", "focal_class": null, "focal_method": "get_value_for_datastore", "tests": "import unittest\n\nclass Test_get_value_for_datastore(unittest.TestCase):\n def testGetValueForDatastore(self):\n \"\"\"Test get_value_for_datastore method.\"\"\"\n e = TestEntity()\n self.assertEquals(None, TestEntity.json_property.get_value_for_datastore(e))\n e.json_property = TestJsonType(5)\n self.assertEquals(u'{\"size\": 5}', TestEntity.json_property.get_value_for_datastore(e))\n e.empty_json_property = EmptyDictJsonType()\n self.assertEquals(None, TestEntity.empty_json_property.get_value_for_datastore(e))\n", "method_code": " def get_value_for_datastore(self, model_instance):\n \"\"\"Gets value for datastore.\n \n Args:\n model_instance: instance of the model class.\n \n Returns:\n datastore-compatible value.\n \"\"\"\n value = super(JsonProperty, self).get_value_for_datastore(model_instance)\n if not value:\n return None\n json_value = value\n if not isinstance(value, dict):\n json_value = value.to_json()\n if not json_value:\n return None\n return datastore_types.Text(simplejson.dumps(json_value, sort_keys=True, cls=JsonEncoder))\n ", "context": "class JsonProperty(db.UnindexedProperty):\n def get_value_for_datastore(self, model_instance): ...\n def __init__(self, data_type, default=None, **kwargs): ...\n def make_value_from_datastore(self, value): ...\n def validate(self, value): ...\n def empty(self, value): ...\n def default_value(self): ...\n\n self.data_type = data_type\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testGetValueForDatastore", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000582.py"} {"focal_file": "python/src/mapreduce/model.py", "focal_class": null, "focal_method": "make_value_from_datastore", "tests": "import unittest\n\nclass Test_make_value_from_datastore(unittest.TestCase):\n def testMakeValueFromDatastore(self):\n \"\"\"Test make_value_from_datastore method.\"\"\"\n self.assertEquals(None, TestEntity.json_property.make_value_from_datastore(None))\n self.assertEquals(TestJsonType, type(TestEntity.json_property.make_value_from_datastore('{\"size\":4}')))\n self.assertTrue(4, TestEntity.json_property.make_value_from_datastore('{\"size\":4}').size)\n", "method_code": " def make_value_from_datastore(self, value):\n \"\"\"Convert value from datastore representation.\n \n Args:\n value: datastore value.\n \n Returns:\n value to store in the model.\n \"\"\"\n if value is None:\n return None\n json = simplejson.loads(value, cls=JsonDecoder)\n if self.data_type == dict:\n return json\n return self.data_type.from_json(json)\n ", "context": "class JsonProperty(db.UnindexedProperty):\n def make_value_from_datastore(self, value): ...\n def __init__(self, data_type, default=None, **kwargs): ...\n def get_value_for_datastore(self, model_instance): ...\n def validate(self, value): ...\n def empty(self, value): ...\n def default_value(self): ...\n\n self.data_type = data_type\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testMakeValueFromDatastore", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000583.py"} {"focal_file": "python/src/mapreduce/model.py", "focal_class": null, "focal_method": "set_processed_counts", "tests": "import unittest\n\nclass Test_set_processed_counts(unittest.TestCase):\n def testSetProcessedCounts(self):\n \"\"\"Test set_processed_counts method.\"\"\"\n mapreduce_state = model.MapreduceState.create_new()\n mapreduce_state.set_processed_counts([1, 2])\n self.assertTrue(mapreduce_state.chart_url.startswith('http://chart.apis.google.com/chart?'))\n self.assertEquals({u'cht': [u'bvg'], u'chs': [u'300x200'], u'chxr': [u'0,0,2.1'], u'chxt': [u'y,x'], u'chd': [u's:d6'], u'chbh': [u'a'], u'chxl': [u'0:|0|2|1:|0|1'], u'chco': [u'0000ff']}, urlparse.parse_qs(urlparse.urlparse(mapreduce_state.chart_url).query))\n", "method_code": " def set_processed_counts(self, shards_processed):\n \"\"\"Updates a chart url to display processed count for each shard.\n \n Args:\n shards_processed: list of integers with number of processed entities in\n each shard\n \"\"\"\n chart = google_chart_api.BarChart(shards_processed)\n shard_count = len(shards_processed)\n if shards_processed:\n stride_length = max(1, shard_count / 16)\n chart.bottom.labels = []\n for x in xrange(shard_count):\n if x % stride_length == 0 or x == shard_count - 1:\n chart.bottom.labels.append(x)\n else:\n chart.bottom.labels.append('')\n chart.left.labels = ['0', str(max(shards_processed))]\n chart.left.min = 0\n self.chart_width = min(700, max(300, shard_count * 20))\n self.chart_url = chart.display.Url(self.chart_width, 200)\n ", "context": "class MapreduceState(db.Model):\n def set_processed_counts(self, shards_processed): ...\n def kind(cls): ...\n def get_key_by_job_id(cls, mapreduce_id): ...\n def get_by_job_id(cls, mapreduce_id): ...\n def get_processed(self): ...\n def create_new(mapreduce_id=None, gettime=datetime.datetime.now): ...\n def new_mapreduce_id(): ...\n\n RESULT_SUCCESS = 'success'\n RESULT_FAILED = 'failed'\n RESULT_ABORTED = 'aborted'\n _RESULTS = frozenset([RESULT_SUCCESS, RESULT_FAILED, RESULT_ABORTED])\n mapreduce_spec = JsonProperty(MapreduceSpec, indexed=False)\n active = db.BooleanProperty(default=True, indexed=False)\n last_poll_time = db.DateTimeProperty(required=True)\n counters_map = JsonProperty(CountersMap, default=CountersMap(), indexed=False)\n app_id = db.StringProperty(required=False, indexed=True)\n writer_state = JsonProperty(dict, indexed=False)\n chart_url = db.TextProperty(default='')\n chart_width = db.IntegerProperty(default=300, indexed=False)\n sparkline_url = db.TextProperty(default='')\n result_status = db.StringProperty(required=False, choices=_RESULTS)\n active_shards = db.IntegerProperty(default=0, indexed=False)\n failed_shards = db.IntegerProperty(default=0, indexed=False)\n aborted_shards = db.IntegerProperty(default=0, indexed=False)\n start_time = db.DateTimeProperty(auto_now_add=True)\n processed = property(get_processed)\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testSetProcessedCounts", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000584.py"} {"focal_file": "python/src/mapreduce/model.py", "focal_class": null, "focal_method": "copy_from", "tests": "import unittest\n\nclass Test_copy_from(unittest.TestCase):\n def testCopyFrom(self):\n \"\"\"Test copy_from method.\"\"\"\n state = model.ShardState.create_new('my-map-job1', 14)\n state.active = False\n state.counters_map.increment('foo', 2)\n state.result_status = 'failed'\n state.mapreduce_id = 'mapreduce_id'\n state.update_time = datetime.datetime.now()\n state.shard_description = 'shard_description'\n state.last_work_item = 'last_work_item'\n another_state = model.ShardState.create_new('my-map-job1', 14)\n another_state.copy_from(state)\n self.assertEquals(state.active, another_state.active)\n self.assertEquals(state.counters_map, another_state.counters_map)\n self.assertEquals(state.result_status, another_state.result_status)\n self.assertEquals(state.mapreduce_id, another_state.mapreduce_id)\n self.assertEquals(state.update_time, another_state.update_time)\n self.assertEquals(state.shard_description, another_state.shard_description)\n self.assertEquals(state.last_work_item, another_state.last_work_item)\n", "method_code": " def copy_from(self, other_state):\n \"\"\"Copy data from another shard state entity to self.\"\"\"\n for prop in self.properties().values():\n setattr(self, prop.name, getattr(other_state, prop.name))\n ", "context": "class ShardState(db.Model):\n def copy_from(self, other_state): ...\n def __str__(self): ...\n def reset_for_retry(self): ...\n def advance_for_next_slice(self): ...\n def set_for_abort(self): ...\n def set_for_success(self): ...\n def get_shard_number(self): ...\n def get_shard_id(self): ...\n def kind(cls): ...\n def shard_id_from_number(cls, mapreduce_id, shard_number): ...\n def get_key_by_shard_id(cls, shard_id): ...\n def get_by_shard_id(cls, shard_id): ...\n def find_by_mapreduce_state(cls, mapreduce_state): ...\n def calculate_keys_by_mapreduce_state(cls, mapreduce_state): ...\n def find_by_mapreduce_id(cls, mapreduce_id): ...\n def create_new(cls, mapreduce_id, shard_number): ...\n\n RESULT_SUCCESS = 'success'\n RESULT_FAILED = 'failed'\n RESULT_ABORTED = 'aborted'\n _RESULTS = frozenset([RESULT_SUCCESS, RESULT_FAILED, RESULT_ABORTED])\n active = db.BooleanProperty(default=True, indexed=False)\n counters_map = JsonProperty(CountersMap, default=CountersMap(), indexed=False)\n result_status = db.StringProperty(choices=_RESULTS, indexed=False)\n retries = db.IntegerProperty(default=0, indexed=False)\n writer_state = JsonProperty(dict, indexed=False)\n slice_id = db.IntegerProperty(default=0, indexed=False)\n slice_start_time = db.DateTimeProperty(indexed=False)\n slice_request_id = db.ByteStringProperty(indexed=False)\n slice_retries = db.IntegerProperty(default=0, indexed=False)\n acquired_once = db.BooleanProperty(default=False, indexed=False)\n mapreduce_id = db.StringProperty(required=True)\n update_time = db.DateTimeProperty(auto_now=True, indexed=False)\n shard_description = db.TextProperty(default='')\n last_work_item = db.TextProperty(default='')\n shard_number = property(get_shard_number)\n shard_id = property(get_shard_id)\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testCopyFrom", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000585.py"} {"focal_file": "python/src/mapreduce/model.py", "focal_class": "mapreduce.model.CountersMap", "focal_method": "increment", "tests": "import unittest\n\nclass Test_mapreduce_model_CountersMap_increment(unittest.TestCase):\n def testIncrementCounter(self):\n \"\"\"Test increment_counter method.\"\"\"\n countres_map = model.CountersMap()\n self.assertEquals(0, countres_map.get('counter1'))\n self.assertEquals(10, countres_map.increment('counter1', 10))\n self.assertEquals(10, countres_map.get('counter1'))\n self.assertEquals(20, countres_map.increment('counter1', 10))\n self.assertEquals(20, countres_map.get('counter1'))\n", "method_code": " def increment(self, counter_name, delta):\n \"\"\"Increment counter value.\n \n Args:\n counter_name: counter name as String.\n delta: increment delta as Integer.\n \n Returns:\n new counter value.\n \"\"\"\n current_value = self.counters.get(counter_name, 0)\n new_value = current_value + delta\n self.counters[counter_name] = new_value\n return new_value\n ", "context": "class CountersMap(JsonMixin):\n def increment(self, counter_name, delta): ...\n def __init__(self, initial_map=None): ...\n def __repr__(self): ...\n def get(self, counter_name): ...\n def add_map(self, counters_map): ...\n def sub_map(self, counters_map): ...\n def clear(self): ...\n def to_json(self): ...\n def from_json(cls, json): ...\n def to_dict(self): ...\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testIncrementCounter", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000586.py"} {"focal_file": "python/src/mapreduce/model.py", "focal_class": "mapreduce.model.CountersMap", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_mapreduce_model_CountersMap_to_json(unittest.TestCase):\n def testToJson(self):\n \"\"\"Test to_json method.\"\"\"\n counters_map = model.CountersMap()\n counters_map.increment('1', 5)\n counters_map.increment('2', 7)\n self.assertEquals({'counters': {'1': 5, '2': 7}}, counters_map.to_json())\n", "method_code": " def to_json(self):\n \"\"\"Serializes all the data in this map into json form.\n \n Returns:\n json-compatible data representation.\n \"\"\"\n return {'counters': self.counters}\n ", "context": "class CountersMap(JsonMixin):\n def to_json(self): ...\n def __init__(self, initial_map=None): ...\n def __repr__(self): ...\n def get(self, counter_name): ...\n def increment(self, counter_name, delta): ...\n def add_map(self, counters_map): ...\n def sub_map(self, counters_map): ...\n def clear(self): ...\n def from_json(cls, json): ...\n def to_dict(self): ...\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testToJson", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000587.py"} {"focal_file": "python/src/mapreduce/model.py", "focal_class": "mapreduce.model.CountersMap", "focal_method": "clear", "tests": "import unittest\n\nclass Test_mapreduce_model_CountersMap_clear(unittest.TestCase):\n def testClear(self):\n \"\"\"Test clear method.\"\"\"\n counters_map = model.CountersMap()\n counters_map.increment('1', 5)\n counters_map.clear()\n self.assertEquals(0, counters_map.get('1'))\n", "method_code": " def clear(self):\n \"\"\"Clear all values.\"\"\"\n self.counters = {}\n ", "context": "class CountersMap(JsonMixin):\n def clear(self): ...\n def __init__(self, initial_map=None): ...\n def __repr__(self): ...\n def get(self, counter_name): ...\n def increment(self, counter_name, delta): ...\n def add_map(self, counters_map): ...\n def sub_map(self, counters_map): ...\n def to_json(self): ...\n def from_json(cls, json): ...\n def to_dict(self): ...\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testClear", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000588.py"} {"focal_file": "python/src/mapreduce/context.py", "focal_class": "mapreduce.context.Context", "focal_method": "increment", "tests": "import unittest\n\nclass Test_mapreduce_context_Context_increment(unittest.TestCase):\n def testIncrement(self):\n \"\"\"Test applying Increment operation.\"\"\"\n m = mox.Mox()\n ctx = context.Context(None, None)\n ctx.counters = m.CreateMock(context.Counters)\n operation = op.counters.Increment('test', 12)\n ctx.counters.increment('test', 12)\n m.ReplayAll()\n try:\n operation(ctx)\n m.VerifyAll()\n finally:\n m.UnsetStubs()\n", "method_code": " def increment(self, counter_name, delta=1):\n \"\"\"Increment counter value.\n \n Args:\n counter_name: name of the counter as string.\n delta: increment delta as int.\n \"\"\"\n self._shard_state.counters_map.increment(counter_name, delta)\n ", "context": "class Counters(object):\n def increment(self, counter_name, delta=1): ...\n def __init__(self, shard_state): ...\n def flush(self): ...\n\n self._shard_state = shard_state\n", "repository": "johnwlockwood/appengine-mapreduce", "test_name": "testIncrement", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000589.py"} {"focal_file": "clustering.py", "focal_class": null, "focal_method": "get_distance", "tests": "import unittest\n\nclass Test_get_distance(unittest.TestCase):\n def test_get_distance(self):\n coord0 = Coordinate(2.5, 3)\n coord1 = Coordinate(10, -2)\n distance = get_distance(coord0, coord1)\n self.assertAlmostEqual(9.01387818866, distance)\n", "method_code": "def get_distance(coordinate_0, coordinate_1):\n diff_x = coordinate_0.x - coordinate_1.x\n diff_y = coordinate_0.y - coordinate_1.y\n return math.sqrt(diff_x ** 2 + diff_y ** 2)", "context": "def get_distance(coordinate_0, coordinate_1): ...\ndef get_distance(coordinate_0, coordinate_1): ...\ndef get_max_distance(coordinates): ...\ndef cluster_points(scattered_points, filename, problem_inspector): ...\n", "repository": "dwave-examples/clustering", "test_name": "test_get_distance", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000590.py"} {"focal_file": "clustering.py", "focal_class": null, "focal_method": "get_max_distance", "tests": "import unittest\n\nclass Test_get_max_distance(unittest.TestCase):\n def test_get_max_distance(self):\n coords = [Coordinate(-1, 0), Coordinate(-0.5, 3), Coordinate(-4, 4)]\n max_distance = get_max_distance(coords)\n self.assertEqual(5, max_distance)\n", "method_code": "def get_max_distance(coordinates):\n max_distance = 0\n for i, coord0 in enumerate(coordinates[:-1]):\n for coord1 in coordinates[i + 1:]:\n distance = get_distance(coord0, coord1)\n max_distance = max(max_distance, distance)\n return max_distance", "context": "def get_max_distance(coordinates): ...\ndef get_distance(coordinate_0, coordinate_1): ...\ndef get_max_distance(coordinates): ...\ndef cluster_points(scattered_points, filename, problem_inspector): ...\n", "repository": "dwave-examples/clustering", "test_name": "test_get_max_distance", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000591.py"} {"focal_file": "Mondrian_Forest.py", "focal_class": null, "focal_method": "update_life_time", "tests": "import unittest\n\nclass Test_update_life_time(unittest.TestCase):\n def test_update_life_time(self):\n lbda = 1\n self.mf.update_life_time(lbda, set_seeds=list(range(self.n_tree)))\n tree = Mondrian_Tree(self.linear_dims)\n tree.update_life_time(lbda, set_seed=0)\n self.assertEqual(tree._num_leaves, self.mf.tree_list[0]._num_leaves)\n for tree in self.mf.tree_list:\n self.assertEqual(tree._life_time, lbda)\n", "method_code": " def update_life_time(self, new_life_time, set_seeds=None):\n self._avg_num_leaves = 0\n for i, tree in enumerate(self.tree_list):\n if set_seeds is not None:\n tree.update_life_time(new_life_time, set_seeds[i])\n else:\n tree.update_life_time(new_life_time)\n self._avg_num_leaves += tree._num_leaves\n self._avg_num_leaves = self._avg_num_leaves / self._num_trees\n ", "context": "class Mondrian_Forest():\n def update_life_time(self, new_life_time, set_seeds=None): ...\n def __init__(self, linear_dims, num_trees): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def input_data(self, all_data, labelled_indices, labels): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def predict(self, new_point): ...\n def al_average_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._num_dimensions = len(linear_dims)\n self._num_trees = num_trees\n self.tree_list = []\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._avg_num_leaves = 1\n self._life_time = 0\n self._al_avg_weights_adjustment = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_update_life_time", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000592.py"} {"focal_file": "Mondrian_Forest.py", "focal_class": null, "focal_method": "input_data", "tests": "import unittest\n\nclass Test_input_data(unittest.TestCase):\n def test_input_data(self):\n self.mf.input_data(self.data, self.labelled_indices, self.labels)\n for tree in self.mf.tree_list:\n self.assertTrue(self.mf.points is tree.points)\n self.assertEqual(self.mf._num_points, tree._num_points)\n\n def test_input_data_grow(self):\n lbda = 1\n self.mf.input_data(self.data, self.labelled_indices, self.labels)\n self.mf.update_life_time(lbda, set_seeds=list(range(self.n_tree)))\n for i, tree in enumerate(self.mf.tree_list):\n test_tree = Mondrian_Tree(self.linear_dims)\n test_tree.update_life_time(lbda, set_seed=i)\n test_tree.input_data(self.data, self.labelled_indices, self.labels)\n self.assertEqual(test_tree._num_leaves, tree._num_leaves)\n tree.make_full_leaf_list()\n test_tree.make_full_leaf_list()\n for j, leaf in enumerate(tree._full_leaf_list):\n self.assertEqual(tree._full_leaf_list[j].labelled_index, test_tree._full_leaf_list[j].labelled_index)\n self.assertEqual(tree._full_leaf_list[j].unlabelled_index, test_tree._full_leaf_list[j].unlabelled_index)\n", "method_code": " def input_data(self, all_data, labelled_indices, labels):\n all_data = copy.deepcopy(all_data)\n labelled_indices = copy.deepcopy(labelled_indices)\n labels = copy.deepcopy(labels)\n if len(all_data) < len(labelled_indices):\n raise ValueError('Cannot have more labelled indices than points')\n if len(labelled_indices) != len(labels):\n raise ValueError('Labelled indices list and labels list must be same length')\n for point in all_data:\n if len(point) != self._num_dimensions:\n raise ValueError('All data points must be of the dimension on which this Mondrian Tree is built ({})'.format(self._num_dimensions))\n if str(type(all_data)) == \"\":\n if self._verbose:\n print('Converting all_data to list of lists internally')\n all_data = all_data.tolist()\n if str(type(labelled_indices)) == \"\":\n if self._verbose:\n print('Converting labelled_indices to list internally')\n labelled_indices = labelled_indices.tolist()\n if str(type(labels)) == \"\":\n if self._verbose:\n print('Converting labels to list internally')\n labels = labels.tolist()\n self.points = all_data\n self._num_points = len(self.points)\n self._num_labelled = len(labels)\n temp = [None] * self._num_points\n for i, ind in enumerate(labelled_indices):\n temp[ind] = labels[i]\n self.labels = temp\n for i, tree in enumerate(self.tree_list):\n tree.input_data(all_data, labelled_indices, labels, copy_data=False)\n tree.points = self.points\n tree.labels = self.labels\n ", "context": "class Mondrian_Forest():\n def input_data(self, all_data, labelled_indices, labels): ...\n def __init__(self, linear_dims, num_trees): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seeds=None): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def predict(self, new_point): ...\n def al_average_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._num_dimensions = len(linear_dims)\n self._num_trees = num_trees\n self.tree_list = []\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._avg_num_leaves = 1\n self._life_time = 0\n self._al_avg_weights_adjustment = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_input_data", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000593.py"} {"focal_file": "Mondrian_Forest.py", "focal_class": null, "focal_method": "label_point", "tests": "import unittest\n\nclass Test_label_point(unittest.TestCase):\n def test_label_point(self):\n val = 2\n self.mf.input_data(self.data, self.labelled_indices, self.labels)\n self.mf.label_point(self.n_labelled, val)\n self.assertEqual(self.mf.labels[self.n_labelled], val)\n self.assertEqual(self.mf._num_labelled, self.n_labelled + 1)\n for tree in self.mf.tree_list:\n leaf = tree._root.leaf_for_point(self.data[self.n_labelled])\n self.assertTrue(self.n_labelled in leaf.labelled_index)\n", "method_code": " def label_point(self, index, value):\n value = copy.copy(value)\n index = copy.copy(index)\n self._num_labelled += 1\n for tree in self.tree_list:\n tree.label_point(index, value)\n ", "context": "class Mondrian_Forest():\n def label_point(self, index, value): ...\n def __init__(self, linear_dims, num_trees): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seeds=None): ...\n def input_data(self, all_data, labelled_indices, labels): ...\n def add_data_point(self, new_point, label=None): ...\n def predict(self, new_point): ...\n def al_average_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._num_dimensions = len(linear_dims)\n self._num_trees = num_trees\n self.tree_list = []\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._avg_num_leaves = 1\n self._life_time = 0\n self._al_avg_weights_adjustment = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_label_point", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000594.py"} {"focal_file": "Mondrian_Forest.py", "focal_class": null, "focal_method": "add_data_point", "tests": "import unittest\n\nclass Test_add_data_point(unittest.TestCase):\n def test_add_data_point(self):\n lbda = 1\n self.mf.input_data(self.data, self.labelled_indices, self.labels)\n self.mf.update_life_time(lbda, set_seeds=list(range(self.n_tree)))\n self.mf.add_data_point([1] * self.d)\n self.assertEqual(self.mf._num_points, self.n_points + 1)\n self.assertEqual(self.data + [[1] * self.d], self.mf.points)\n self.assertEqual(self.labels + [None] * (self.n_points - self.n_labelled) + [None], self.mf.labels)\n for tree in self.mf.tree_list:\n leaf = tree._root.leaf_for_point([1] * self.d)\n self.assertEqual(leaf.unlabelled_index[-1], self.n_points)\n self.assertEqual(len(tree.points), tree._num_points)\n\n def test_add_data_point_labelled(self):\n lbda = 1\n val = 1\n self.mf.input_data(self.data, self.labelled_indices, self.labels)\n self.mf.update_life_time(lbda, set_seeds=list(range(self.n_tree)))\n self.mf.add_data_point([1] * self.d, val)\n self.assertEqual(self.mf._num_points, self.n_points + 1)\n self.assertEqual(self.mf._num_labelled, self.n_labelled + 1)\n self.assertEqual(self.data + [[1] * self.d], self.mf.points)\n self.assertEqual(self.labels + [None] * (self.n_points - self.n_labelled) + [val], self.mf.labels)\n for tree in self.mf.tree_list:\n leaf = tree._root.leaf_for_point([1] * self.d)\n self.assertEqual(leaf.labelled_index[-1], self.n_points)\n self.assertEqual(len(tree.points), tree._num_points)\n", "method_code": " def add_data_point(self, new_point, label=None):\n new_point = copy.deepcopy(new_point)\n label = copy.deepcopy(label)\n new_point = self._test_point(new_point)\n if self.points is None:\n point_index = 0\n self.points = [new_point]\n self.labels = [label]\n else:\n point_index = len(self.labels)\n self.points.append(new_point)\n self.labels.append(label)\n self._num_points += 1\n if label is not None:\n self._num_labelled += 1\n for tree in self.tree_list:\n leaf = tree._root.leaf_for_point(new_point)\n if label is None:\n leaf.unlabelled_index.append(point_index)\n tree._num_points += 1\n else:\n leaf.labelled_index.append(point_index)\n tree._num_points += 1\n tree._num_labelled += 1\n tree._full_leaf_marginal_list_up_to_date = False\n if label is not None:\n tree._full_leaf_mean_list_up_to_date = False\n tree._full_leaf_var_list_up_to_date = False\n ", "context": "class Mondrian_Forest():\n def add_data_point(self, new_point, label=None): ...\n def __init__(self, linear_dims, num_trees): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seeds=None): ...\n def input_data(self, all_data, labelled_indices, labels): ...\n def label_point(self, index, value): ...\n def predict(self, new_point): ...\n def al_average_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._num_dimensions = len(linear_dims)\n self._num_trees = num_trees\n self.tree_list = []\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._avg_num_leaves = 1\n self._life_time = 0\n self._al_avg_weights_adjustment = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_add_data_point", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000595.py"} {"focal_file": "Mondrian_Forest.py", "focal_class": null, "focal_method": "predict", "tests": "import unittest\n\nclass Test_predict(unittest.TestCase):\n def test_predict(self):\n lbda = 0.5\n seed = 1\n self.mf.update_life_time(lbda, set_seeds=list(range(self.n_tree)))\n self.mf.input_data(self.data, self.labelled_indices, self.labels)\n random.seed(seed)\n new_point = []\n for j in range(self.d):\n new_point.append(random.random())\n pred = self.mf.predict(new_point)\n tree_preds = []\n for tree in self.mf.tree_list:\n node = tree._root.leaf_for_point(new_point)\n vals = [tree.labels[x] for x in node.labelled_index]\n tree_preds.append(sum(vals) / len(vals))\n self.assertEqual(pred, sum(tree_preds) / len(tree_preds))\n", "method_code": " def predict(self, new_point):\n tree_preds = []\n for tree in self.tree_list:\n tree.set_default_pred_global_mean()\n tree_preds.append(tree.predict(new_point))\n if type(tree_preds[0]) is not list:\n return sum(tree_preds) / self._num_trees\n else:\n preds = []\n for j in range(len(tree_preds[0])):\n val = 0\n for i in range(self._num_trees):\n val += tree_preds[i][j]\n val = val / self._num_trees\n preds.append(val)\n return preds\n ", "context": "class Mondrian_Forest():\n def predict(self, new_point): ...\n def __init__(self, linear_dims, num_trees): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seeds=None): ...\n def input_data(self, all_data, labelled_indices, labels): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def al_average_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._num_dimensions = len(linear_dims)\n self._num_trees = num_trees\n self.tree_list = []\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._avg_num_leaves = 1\n self._life_time = 0\n self._al_avg_weights_adjustment = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_predict", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000596.py"} {"focal_file": "Mondrian_Forest.py", "focal_class": null, "focal_method": "al_average_point_probabilities_adjustment", "tests": "import unittest\n\nclass Test_al_average_point_probabilities_adjustment(unittest.TestCase):\n def test_al_average_point_probabilities_adjustment(self):\n lbda = 0.5\n self.mf.update_life_time(lbda, set_seeds=list(range(self.n_tree)))\n self.mf.input_data(self.data, self.labelled_indices, self.labels)\n self.mf.al_average_point_probabilities_adjustment(21)\n self.assertAlmostEqual(sum(self.mf._al_avg_weights_adjustment), 1)\n", "method_code": " def al_average_point_probabilities_adjustment(self, num_samples_total):\n weights_list = []\n for tree in self.tree_list:\n tree.al_set_default_var_global_var()\n tree.al_calculate_leaf_proportions()\n tree.al_calculate_point_probabilities_adjustment(num_samples_total)\n weights_list.append(tree._al_point_weights_adjustment)\n avg_weights = [0] * self._num_points\n for i in range(self._num_points):\n for j in range(self._num_trees):\n val = weights_list[j][i]\n if val is not None:\n avg_weights[i] += val\n avg_weights = [x / self._num_trees for x in avg_weights]\n self._al_avg_weights_adjustment = avg_weights\n ", "context": "class Mondrian_Forest():\n def al_average_point_probabilities_adjustment(self, num_samples_total): ...\n def __init__(self, linear_dims, num_trees): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seeds=None): ...\n def input_data(self, all_data, labelled_indices, labels): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def predict(self, new_point): ...\n\n self._linear_dims = linear_dims\n self._num_dimensions = len(linear_dims)\n self._num_trees = num_trees\n self.tree_list = []\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._avg_num_leaves = 1\n self._life_time = 0\n self._al_avg_weights_adjustment = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_al_average_point_probabilities_adjustment", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000597.py"} {"focal_file": "Breiman_Tree.py", "focal_class": null, "focal_method": "calculate_leaf_statistics", "tests": "import unittest\n\nclass Test_calculate_leaf_statistics(unittest.TestCase):\n def test_leaf_statistics_var(self):\n n_reps = 20\n self.bt.input_data(self.data, self.labelled_indices, self.labels)\n for i in range(n_reps):\n self.bt.label_point(self.n_labelled + i, random.random())\n self.bt.fit_tree()\n self.bt.calculate_leaf_statistics()\n\n def test_leaf_statistics_marginal(self):\n n_reps = 20\n self.bt.input_data(self.data, self.labelled_indices, self.labels)\n for i in range(n_reps):\n self.bt.label_point(self.n_labelled + i, random.random())\n self.bt.fit_tree()\n self.bt.calculate_leaf_statistics()\n", "method_code": " def calculate_leaf_statistics(self):\n temp = Counter(self._leaf_indices)\n self._leaf_marginal = []\n self._leaf_var = []\n for key in np.unique(self._leaf_indices):\n self._leaf_marginal.append(temp[key] / self._num_points)\n temp_ind = [i for i, x in enumerate(self._leaf_indices) if x == key]\n temp_labels = [x for x in self.labels if x is not None]\n self._leaf_var.append(utils.unbiased_var(temp_labels))\n self._leaf_statistics_up_to_date = True\n ", "context": "class Breiman_Tree():\n def calculate_leaf_statistics(self): ...\n def __init__(self, min_samples_leaf=None, seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def fit_tree(self): ...\n def label_point(self, index, value): ...\n def predict(self, new_points): ...\n def al_calculate_leaf_proportions(self): ...\n def pick_new_points(self, num_samples=1): ...\n\n self.points = None\n self.labels = None\n self.labelled_indices = None\n self._num_points = 0\n self._num_labelled = 0\n self.tree = DecisionTreeRegressor(random_state=self.seed, min_samples_leaf=self.min_samples_leaf)\n self._leaf_indices = []\n self._leaf_marginal = []\n self._leaf_var = []\n self._al_proportions = []\n self._leaf_statistics_up_to_date = False\n self._leaf_proportions_up_to_date = False\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_leaf_statistics_var", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000598.py"} {"focal_file": "Breiman_Tree.py", "focal_class": null, "focal_method": "al_calculate_leaf_proportions", "tests": "import unittest\n\nclass Test_al_calculate_leaf_proportions(unittest.TestCase):\n def test_leaf_proportions(self):\n n_reps = 20\n self.bt.input_data(self.data, self.labelled_indices, self.labels)\n for i in range(n_reps):\n self.bt.label_point(self.n_labelled + i, random.random())\n self.bt.fit_tree()\n self.bt.calculate_leaf_statistics()\n self.bt.al_calculate_leaf_proportions()\n", "method_code": " def al_calculate_leaf_proportions(self):\n if not self._leaf_statistics_up_to_date:\n self.calculate_leaf_statistics()\n al_proportions = []\n for i, val in enumerate(self._leaf_var):\n al_proportions.append(np.sqrt(self._leaf_var[i] * self._leaf_marginal[i]))\n al_proportions = np.array(al_proportions) / sum(al_proportions)\n self._al_proportions = al_proportions\n self._leaf_proportions_up_to_date = True\n ", "context": "class Breiman_Tree():\n def al_calculate_leaf_proportions(self): ...\n def __init__(self, min_samples_leaf=None, seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def fit_tree(self): ...\n def label_point(self, index, value): ...\n def predict(self, new_points): ...\n def calculate_leaf_statistics(self): ...\n def pick_new_points(self, num_samples=1): ...\n\n self.points = None\n self.labels = None\n self.labelled_indices = None\n self._num_points = 0\n self._num_labelled = 0\n self.tree = DecisionTreeRegressor(random_state=self.seed, min_samples_leaf=self.min_samples_leaf)\n self._leaf_indices = []\n self._leaf_marginal = []\n self._leaf_var = []\n self._al_proportions = []\n self._leaf_statistics_up_to_date = False\n self._leaf_proportions_up_to_date = False\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_leaf_proportions", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000599.py"} {"focal_file": "Breiman_Tree.py", "focal_class": null, "focal_method": "pick_new_points", "tests": "import unittest\n\nclass Test_pick_new_points(unittest.TestCase):\n def test_pick_new_points(self):\n n_reps = 20\n self.bt.input_data(self.data, self.labelled_indices, self.labels)\n new_point = self.n_labelled\n for i in range(n_reps):\n self.bt.label_point(new_point, random.random())\n self.bt.fit_tree()\n self.bt.calculate_leaf_statistics()\n self.bt.al_calculate_leaf_proportions()\n new_point = self.bt.pick_new_points()[0]\n print(new_point)\n", "method_code": " def pick_new_points(self, num_samples=1):\n if not self._leaf_proportions_up_to_date:\n self.al_calculate_leaf_proportions()\n temp = Counter(np.array(self._leaf_indices)[[x for x in range(self._num_points) if self.labels[x] is None]])\n point_proportions = {}\n for i, key in enumerate(np.unique(self._leaf_indices)):\n point_proportions[key] = self._al_proportions[i] / max(1, temp[key])\n temp_probs = np.array([point_proportions[key] for key in self._leaf_indices])\n temp_probs[self.labelled_indices] = 0\n temp_probs = temp_probs / sum(temp_probs)\n leaves_to_sample = np.random.choice(self._leaf_indices, num_samples, p=temp_probs, replace=False)\n points_to_label = []\n for leaf in leaves_to_sample:\n possible_points = [x for i, x in enumerate(range(self._num_points)) if self._leaf_indices[i] == leaf and self.labels[i] is None]\n points_to_label.append(np.random.choice(possible_points))\n return points_to_label\n ", "context": "class Breiman_Tree():\n def pick_new_points(self, num_samples=1): ...\n def __init__(self, min_samples_leaf=None, seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def fit_tree(self): ...\n def label_point(self, index, value): ...\n def predict(self, new_points): ...\n def calculate_leaf_statistics(self): ...\n def al_calculate_leaf_proportions(self): ...\n\n self.points = None\n self.labels = None\n self.labelled_indices = None\n self._num_points = 0\n self._num_labelled = 0\n self.tree = DecisionTreeRegressor(random_state=self.seed, min_samples_leaf=self.min_samples_leaf)\n self._leaf_indices = []\n self._leaf_marginal = []\n self._leaf_var = []\n self._al_proportions = []\n self._leaf_statistics_up_to_date = False\n self._leaf_proportions_up_to_date = False\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_pick_new_points", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_000600.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "update_life_time", "tests": "import unittest\n\nclass Test_update_life_time(unittest.TestCase):\n def test_update_first_life_time_0p1(self):\n temp = Mondrian_Tree([[0, 1]] * 5)\n temp.update_life_time(0.1, set_seed=1)\n self.assertEqual(temp._num_leaves, 3)\n\n def test_update_first_life_time_0p5(self):\n temp = Mondrian_Tree([[0, 1]] * 5)\n temp.update_life_time(0.5, set_seed=1)\n self.assertEqual(temp._num_leaves, 8)\n\n def test_update_first_life_time_1(self):\n temp = Mondrian_Tree([[0, 1]] * 5)\n temp.update_life_time(1, set_seed=1)\n self.assertEqual(temp._num_leaves, 36)\n\n def test_update_life_time_tuned(self):\n self.mt1.update_life_time(self.a * self.n_labelled ** (1 / (2 + self.d) - 1), set_seed=1)\n self.assertEqual(self.mt1._num_leaves, 2)\n\n def test_update_life_time_with_data(self):\n lbda = 0.5\n lbda2 = 1\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.update_life_time(lbda2, set_seed=100)\n self.mt1.make_full_leaf_list()\n for node in self.mt1._full_leaf_list:\n linear_dims = node.linear_dims\n for ind in node.labelled_index:\n point = self.mt1.points[ind]\n for dim in range(self.d):\n self.assertTrue(point[dim] >= linear_dims[dim][0])\n self.assertTrue(point[dim] <= linear_dims[dim][1])\n for ind in node.unlabelled_index:\n point = self.mt1.points[ind]\n for dim in range(self.d):\n self.assertTrue(point[dim] >= linear_dims[dim][0])\n self.assertTrue(point[dim] <= linear_dims[dim][1])\n", "method_code": " def update_life_time(self, new_life_time, set_seed=None):\n \"\"\"Function for updating the tree with a new life time parameter, potentially \n growing the tree. Grows until the next split would occur after the new life\n time, moving any data within the tree into the new leaves.\n \"\"\"\n new_life_time = copy.copy(new_life_time)\n if new_life_time < self._life_time:\n raise ValueError('The new life time {} must be larger than the old one {}. This implementation does not support pruning of trees'.format(new_life_time, self._life_time))\n old_life_time = self._life_time\n self._life_time = new_life_time\n self._full_leaf_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self._active_learning_proportions_up_to_date = False\n if set_seed is not None:\n random.seed(set_seed)\n next_split_time = old_life_time + random.expovariate(self._root.subtree_linear_dim)\n while next_split_time < self._life_time:\n self._num_leaves += 1\n curr_node = self._root\n while not curr_node.is_leaf():\n left_prob = curr_node.left_child.subtree_linear_dim\n right_prob = curr_node.right_child.subtree_linear_dim\n left_prob = left_prob / (left_prob + right_prob)\n right_prob = right_prob / (left_prob + right_prob)\n rand_split_val = random.random()\n if self._verbose:\n print('Probability of going left is {}\\n Probability of going right is {}\\n Random value is {}').format(left_prob, right_prob, rand_split_val)\n if rand_split_val < left_prob:\n curr_node = curr_node.left_child\n if self._verbose:\n print('Going left')\n else:\n curr_node = curr_node.right_child\n if self._verbose:\n print('Going right')\n dimension_probs = []\n for pair in curr_node.linear_dims:\n dimension_probs.append(abs(pair[1] - pair[0]) / curr_node.subtree_linear_dim)\n split_dim = utils.choices(range(self._num_dimensions), weights=dimension_probs)[0]\n split_interval = curr_node.linear_dims[split_dim]\n split_val = random.uniform(split_interval[0], split_interval[1])\n left_linear_dims = copy.deepcopy(curr_node.linear_dims)\n left_linear_dims[split_dim] = [split_interval[0], split_val]\n right_linear_dims = copy.deepcopy(curr_node.linear_dims)\n right_linear_dims[split_dim] = [split_val, split_interval[1]]\n new_left_node = LeafNode(linear_dims=left_linear_dims, parent_branch=0)\n new_right_node = LeafNode(linear_dims=right_linear_dims, parent_branch=1)\n new_split_node = SplitNode(split_dim=split_dim, split_val=split_val, left_child=new_left_node, right_child=new_right_node, parent_node=curr_node.parent_node, parent_branch=curr_node.parent_branch, subtree_linear_dim=curr_node.subtree_linear_dim)\n new_split_node.left_child.parent_node = new_split_node\n new_split_node.right_child.parent_node = new_split_node\n if curr_node.parent_node is not None:\n if curr_node.parent_branch == 0:\n curr_node.parent_node.left_child = new_split_node\n else:\n curr_node.parent_node.right_child = new_split_node\n else:\n self._root = new_split_node\n subtree_lin_dim_change = new_left_node.subtree_linear_dim + new_right_node.subtree_linear_dim - curr_node.subtree_linear_dim\n new_split_node.percolate_subtree_linear_dim_change(subtree_lin_dim_change)\n for ind in curr_node.labelled_index:\n new_split_node.leaf_for_point(self.points[ind]).extend_labelled_index([ind])\n for ind in curr_node.unlabelled_index:\n new_split_node.leaf_for_point(self.points[ind]).extend_unlabelled_index([ind])\n next_split_time = next_split_time + random.expovariate(self._root.subtree_linear_dim)\n ", "context": "class Mondrian_Tree():\n def update_life_time(self, new_life_time, set_seed=None): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_update_first_life_time_0p1", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000601.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "_test_point", "tests": "import unittest\n\nclass Test_test_point(unittest.TestCase):\n def test__test_point(self):\n with self.assertRaises(ValueError):\n self.mt1._test_point([])\n self.mt1._test_point([1, 2, 3, 4, 5])\n with self.assertRaises(TypeError):\n self.mt1._test_point(1)\n self.mt1._test_point({})\n self.mt1._test_point('abc')\n good_point = [1] * self.d\n self.assertEqual(good_point, self.mt1._test_point(good_point))\n self.assertEqual(good_point, self.mt1._test_point(np.array(good_point)))\n", "method_code": " def _test_point(self, new_point):\n \"\"\"Tests an input point, raising errors if it's a bad type and converting it from\n a numpy array to a list if needed \n \"\"\"\n try:\n len(new_point)\n except TypeError:\n raise TypeError('Given point has no len(), so probably is not a vector representing a data point. Try turning it into a list, tuple or numpy array where each entry is a dimension.')\n if len(new_point) != self._num_dimensions:\n raise ValueError('Data point is not of the correct length. Must be the same dimension as the dimensions used to build the Mondrian Tree when it was initialized.')\n if str(type(new_point)) == \"\":\n if self._verbose:\n print('Converting new_point to list internally')\n new_point = new_point.tolist()\n if type(new_point) not in [list, tuple]:\n raise TypeError('Please input the new point as a list, tuple or numpy array')\n return new_point\n ", "context": "class Mondrian_Tree():\n def _test_point(self, new_point): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test__test_point", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000602.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "input_data", "tests": "import unittest\n\nclass Test_input_data(unittest.TestCase):\n def test_input_data_empty_root(self):\n self.mt1.input_data([], [], [])\n self.assertEqual(self.mt1._num_points, 0)\n\n def test_input_data_empty(self):\n lbda = 1\n self.mt1.update_life_time(lbda, set_seed=1)\n self.mt1.input_data([], [], [])\n self.assertEqual(self.mt1._num_points, 0)\n\n def test_input_data_root_labels(self):\n self.mt1.input_data([[0] * self.d], [0], [3.141])\n self.assertEqual(self.mt1._num_points, 1)\n self.assertEqual(self.mt1.labels, [3.141])\n self.assertEqual(self.mt1._root.unlabelled_index, [])\n self.assertEqual(self.mt1._root.labelled_index, [0])\n\n def test_input_data(self):\n lbda = 0.5\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.assertEqual(self.mt1._num_points, self.n_points)\n self.assertEqual(self.mt1._num_labelled, self.n_labelled)\n self.mt1.make_full_leaf_list()\n for node in self.mt1._full_leaf_list:\n linear_dims = node.linear_dims\n for ind in node.labelled_index:\n point = self.mt1.points[ind]\n for dim in range(self.d):\n self.assertTrue(point[dim] >= linear_dims[dim][0])\n self.assertTrue(point[dim] <= linear_dims[dim][1])\n for ind in node.unlabelled_index:\n point = self.mt1.points[ind]\n for dim in range(self.d):\n self.assertTrue(point[dim] >= linear_dims[dim][0])\n self.assertTrue(point[dim] <= linear_dims[dim][1])\n\n def test_input_data_with_numpy(self):\n lbda = 0.5\n self.mt1.update_life_time(lbda, set_seed=100)\n np_data = np.array(self.data)\n np_labels = np.array(self.labels)\n self.mt1.input_data(np_data, self.labelled_indices, np_labels)\n self.assertEqual(self.mt1._num_points, self.n_points)\n self.assertEqual(self.mt1._num_labelled, self.n_labelled)\n self.mt1.make_full_leaf_list()\n for node in self.mt1._full_leaf_list:\n linear_dims = node.linear_dims\n for ind in node.labelled_index:\n point = self.mt1.points[ind]\n for dim in range(self.d):\n self.assertTrue(point[dim] >= linear_dims[dim][0])\n self.assertTrue(point[dim] <= linear_dims[dim][1])\n for ind in node.unlabelled_index:\n point = self.mt1.points[ind]\n for dim in range(self.d):\n self.assertTrue(point[dim] >= linear_dims[dim][0])\n self.assertTrue(point[dim] <= linear_dims[dim][1])\n", "method_code": " def input_data(self, all_data, labelled_indices, labels, copy_data=True):\n \"\"\"Puts in data for Mondrian Tree. \n all_data should be a list of lists (or numpy array, points by row) with all data points, \n labelled_indices should be a list of the indicies for data points which we have the\n labels for, and labels should be an equal length list of those points labels.\n \n Should work with inputting things as numpy arrays, but this is the only place you can \n safely use numpy arrays. \n \"\"\"\n if copy_data:\n all_data = copy.deepcopy(all_data)\n labelled_indices = copy.deepcopy(labelled_indices)\n labels = copy.deepcopy(labels)\n if len(all_data) < len(labelled_indices):\n raise ValueError('Cannot have more labelled indicies than points')\n if len(labelled_indices) != len(labels):\n raise ValueError('Labelled indicies list and labels list must be same length')\n for point in all_data:\n if len(point) != self._num_dimensions:\n raise ValueError('All data points must be of the dimension on which this Mondrian Tree is built ({})'.format(self._num_dimensions))\n if str(type(all_data)) == \"\":\n if self._verbose:\n print('Converting all_data to list of lists internally')\n all_data = all_data.tolist()\n if str(type(labelled_indices)) == \"\":\n if self._verbose:\n print('Converting labelled_indices to list internally')\n labelled_indices = labelled_indices.tolist()\n if str(type(labels)) == \"\":\n if self._verbose:\n print('Converting labels to list internally')\n labels = labels.tolist()\n self.points = all_data\n self._num_points = len(self.points)\n self._num_labelled = len(labels)\n temp = [None] * self._num_points\n for i, ind in enumerate(labelled_indices):\n temp[ind] = labels[i]\n self.labels = temp\n unlabelled_indices = [x for x in range(self._num_points) if x not in labelled_indices]\n if self._root.is_leaf():\n self._root.labelled_index = list(labelled_indices)\n self._root.unlabelled_index = unlabelled_indices\n else:\n for i in labelled_indices:\n curr_leaf = self._root.leaf_for_point(self.points[i])\n curr_leaf.labelled_index.append(i)\n for i in unlabelled_indices:\n curr_leaf = self._root.leaf_for_point(self.points[i])\n curr_leaf.unlabelled_index.append(i)\n ", "context": "class Mondrian_Tree():\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_input_data_empty_root", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000603.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "label_point", "tests": "import unittest\n\nclass Test_label_point(unittest.TestCase):\n def test_label_point_root(self):\n val = 1\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.label_point(self.n_labelled, val)\n self.assertEqual(self.mt1.labels[self.n_labelled], val)\n self.assertEqual(self.mt1._num_labelled, self.n_labelled + 1)\n leaf = self.mt1._root.leaf_for_point(self.data[self.n_labelled])\n self.assertTrue(self.n_labelled in leaf.labelled_index)\n\n def test_label_point_empty(self):\n with self.assertRaises(RuntimeError):\n self.mt1.label_point(1, 1)\n\n def test_label_point_too_big(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n with self.assertRaises(ValueError):\n self.mt1.label_point(self.n_points + 1, 1)\n\n def test_label_point(self):\n val = 1\n lbda = 0.5\n seed = 1\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.label_point(self.n_labelled, val)\n self.assertEqual(self.mt1.labels[self.n_labelled], val)\n self.assertEqual(self.mt1._num_labelled, self.n_labelled + 1)\n leaf = self.mt1._root.leaf_for_point(self.data[self.n_labelled])\n self.assertTrue(self.n_labelled in leaf.labelled_index)\n", "method_code": " def label_point(self, index, value):\n \"\"\"Adds a label to a specific data point. Throws an error if that point\n is already labelled. \n \"\"\"\n if self.labels is None:\n raise RuntimeError('No data in the tree')\n if len(self.labels) <= index:\n raise ValueError('Index {} larger than size of data in tree'.format(index))\n value = copy.copy(value)\n index = copy.copy(index)\n self.labels[index] = value\n leaf = self._root.leaf_for_point(self.points[index])\n leaf.make_labelled(index)\n self._num_labelled += 1\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n ", "context": "class Mondrian_Tree():\n def label_point(self, index, value): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_label_point_root", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000604.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "add_data_point", "tests": "import unittest\n\nclass Test_add_data_point(unittest.TestCase):\n def test_add_data_point_bad(self):\n with self.assertRaises(TypeError):\n self.mt1.add_data_point(1)\n\n def test_add_data_point_empty(self):\n self.mt1.add_data_point([1] * self.d)\n self.assertEqual([[1] * self.d], self.mt1.points)\n self.assertEqual([None], self.mt1.labels)\n self.assertEqual(self.mt1._root.unlabelled_index, [0])\n self.assertEqual(self.mt1._root.labelled_index, [])\n\n def test_add_data_point_empty_2(self):\n self.mt1.add_data_point([1] * self.d, 2)\n self.assertEqual([[1] * self.d], self.mt1.points)\n self.assertEqual([2], self.mt1.labels)\n self.assertEqual(self.mt1._root.unlabelled_index, [])\n self.assertEqual(self.mt1._root.labelled_index, [0])\n\n def test_add_data_point(self):\n lbda = 0.5\n seed = 1\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.add_data_point([1] * self.d)\n self.assertEqual(self.data + [[1] * self.d], self.mt1.points)\n self.assertEqual(self.labels + [None] * (self.n_points - self.n_labelled) + [None], self.mt1.labels)\n leaf = self.mt1._root.leaf_for_point([1] * self.d)\n self.assertEqual(leaf.unlabelled_index[-1], self.n_points)\n self.assertEqual(len(self.mt1.points), self.mt1._num_points)\n\n def test_add_data_point_labelled(self):\n lbda = 0.5\n seed = 1\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.add_data_point([1] * self.d, 1)\n self.assertEqual(self.data + [[1] * self.d], self.mt1.points)\n self.assertEqual(self.labels + [None] * (self.n_points - self.n_labelled) + [1], self.mt1.labels)\n leaf = self.mt1._root.leaf_for_point([1] * self.d)\n self.assertEqual(leaf.labelled_index[-1], self.n_points)\n self.assertEqual(len(self.mt1.points), self.mt1._num_points)\n self.assertEqual(self.n_labelled + 1, self.mt1._num_labelled)\n", "method_code": " def add_data_point(self, new_point, label=None):\n \"\"\"Adds an additional data point to the tree, with the option of adding a label\n as well. Automatically makes it the _num_points-th point.\n \n Does NOT automatically grow the tree larger so you need to do that yourself.\n \"\"\"\n new_point = copy.deepcopy(new_point)\n label = copy.deepcopy(label)\n new_point = self._test_point(new_point)\n if self.points is None:\n point_index = 0\n self.points = [new_point]\n self.labels = [label]\n else:\n point_index = len(self.labels)\n self.points.append(new_point)\n self.labels.append(label)\n leaf = self._root.leaf_for_point(new_point)\n if label is None:\n leaf.unlabelled_index.append(point_index)\n self._num_points += 1\n else:\n leaf.labelled_index.append(point_index)\n self._num_points += 1\n self._num_labelled += 1\n self._full_leaf_marginal_list_up_to_date = False\n if label is not None:\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n ", "context": "class Mondrian_Tree():\n def add_data_point(self, new_point, label=None): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_add_data_point_bad", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000605.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "make_full_leaf_list", "tests": "import unittest\n\nclass Test_make_full_leaf_list(unittest.TestCase):\n def test_make_full_leaf_list_root(self):\n self.mt1.make_full_leaf_list()\n self.assertEqual(len(self.mt1._full_leaf_list), 1)\n\n def test_make_full_leaf_list(self):\n lbda = 1\n self.mt1.update_life_time(lbda, set_seed=1)\n self.mt1.make_full_leaf_list()\n self.assertEqual(len(self.mt1._full_leaf_list), self.mt1._num_leaves)\n\n def test_predict_leaf_list(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.make_full_leaf_list()\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n random.seed(seed)\n new_point = []\n for j in range(self.d):\n new_point.append(random.random())\n pred = self.mt1.predict(new_point)\n node = self.mt1._root.leaf_for_point(new_point)\n vals = [self.labels[x] for x in node.labelled_index]\n self.assertEqual(pred, sum(vals) / len(vals))\n", "method_code": " def make_full_leaf_list(self):\n \"\"\"Makes a list with pointers to every leaf in the tree. Likely to be expensive so \n only do this if you're pre-building a tree for extensive use later. Not needed for\n things like prediction, but needed for cell statistics and active learning.\n \"\"\"\n full_leaf_list = []\n \n def internal_dfs(node):\n if node.is_leaf():\n full_leaf_list.append(node)\n else:\n internal_dfs(node.left_child)\n internal_dfs(node.right_child)\n internal_dfs(self._root)\n self._full_leaf_list = full_leaf_list\n for i, node in enumerate(self._full_leaf_list):\n node.full_leaf_list_pos = i\n self._full_leaf_list_up_to_date = True\n ", "context": "class Mondrian_Tree():\n def make_full_leaf_list(self): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_make_full_leaf_list_root", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000606.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "make_full_leaf_var_list", "tests": "import unittest\n\nclass Test_make_full_leaf_var_list(unittest.TestCase):\n def test_make_full_leaf_var_list_root(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_var_list()\n self.assertEqual(utils.unbiased_var(self.labels), self.mt1._full_leaf_var_list[0])\n\n def test_make_full_leaf_var_list_empty(self):\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_var_list()\n self.assertEqual(0, self.mt1._full_leaf_var_list[0])\n\n def test_make_full_leaf_var_list(self):\n lbda = 0.5\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_var_list()\n for i, node in enumerate(self.mt1._full_leaf_list):\n node_labels = [self.mt1.labels[x] for x in node.labelled_index]\n if len(node_labels) != 0:\n temp_mean = sum(node_labels) / len(node_labels)\n temp_var = 1 / (len(node_labels) - 1) * sum([(x - temp_mean) ** 2 for x in node_labels])\n self.assertTrue(abs(self.mt1._full_leaf_var_list[i] - temp_var) < 1e-09)\n else:\n self.assertEqual(self.mt1._full_leaf_var_list[i], 0)\n", "method_code": " def make_full_leaf_var_list(self):\n if not self._full_leaf_list_up_to_date:\n print('Making full leaf list. Please wait')\n self.make_full_leaf_list()\n print('Done!')\n var_list = []\n for i, node in enumerate(self._full_leaf_list):\n label_list = [self.labels[x] for x in node.labelled_index]\n var_list.append(utils.unbiased_var(label_list))\n self._full_leaf_var_list = var_list\n self._full_leaf_var_list_up_to_date = True\n ", "context": "class Mondrian_Tree():\n def make_full_leaf_var_list(self): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_make_full_leaf_var_list_root", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000607.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "make_full_leaf_mean_list", "tests": "import unittest\n\nclass Test_make_full_leaf_mean_list(unittest.TestCase):\n def test_make_full_leaf_mean_list_root(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_mean_list()\n self.assertEqual(sum(self.labels) / self.n_labelled, self.mt1._full_leaf_mean_list[0])\n\n def test_make_full_leaf_mean_list_empty(self):\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_mean_list()\n self.assertEqual(0, self.mt1._full_leaf_mean_list[0])\n\n def test_make_full_leaf_mean_list(self):\n lbda = 0.5\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_mean_list()\n for i, node in enumerate(self.mt1._full_leaf_list):\n node_labels = [self.mt1.labels[x] for x in node.labelled_index]\n if len(node_labels) != 0:\n temp_mean = sum(node_labels) / len(node_labels)\n self.assertTrue(abs(self.mt1._full_leaf_mean_list[i] - temp_mean) < 1e-09)\n else:\n self.assertEqual(self.mt1._full_leaf_mean_list[i], 0)\n", "method_code": " def make_full_leaf_mean_list(self):\n if not self._full_leaf_list_up_to_date:\n print('Making full leaf list. Please wait')\n self.make_full_leaf_list()\n print('Done!')\n mean_list = []\n for i, node in enumerate(self._full_leaf_list):\n label_list = [self.labels[x] for x in node.labelled_index]\n if len(label_list) != 0:\n mean_list.append(sum(label_list) / len(label_list))\n else:\n mean_list.append(0)\n self._full_leaf_mean_list = mean_list\n self._full_leaf_mean_list_up_to_date = True\n ", "context": "class Mondrian_Tree():\n def make_full_leaf_mean_list(self): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_make_full_leaf_mean_list_root", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000608.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "make_full_leaf_marginal_list", "tests": "import unittest\n\nclass Test_make_full_leaf_marginal_list(unittest.TestCase):\n def test_make_full_leaf_marginal_list_root(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_marginal_list()\n self.assertEqual(1, self.mt1._full_leaf_marginal_list[0])\n\n def test_make_full_leaf_marginal_list_empty(self):\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_marginal_list()\n self.assertEqual(0, self.mt1._full_leaf_marginal_list[0])\n\n def test_make_full_leaf_marginal_list(self):\n lbda = 0.5\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.make_full_leaf_list()\n self.mt1.make_full_leaf_marginal_list()\n for i, node in enumerate(self.mt1._full_leaf_list):\n node_points = [self.mt1.points[x] for x in node.labelled_index] + [self.mt1.points[x] for x in node.unlabelled_index]\n temp_marginal = len(node_points) / self.mt1._num_points\n self.assertTrue(abs(self.mt1._full_leaf_marginal_list[i] - temp_marginal) < 1e-09)\n", "method_code": " def make_full_leaf_marginal_list(self):\n if not self._full_leaf_list_up_to_date:\n print('Making full leaf list. Please wait')\n self.make_full_leaf_list()\n print('Done!')\n if self._num_points == 0:\n self._full_leaf_marginal_list = [0] * self._num_leaves\n else:\n marginal_list = []\n for i, node in enumerate(self._full_leaf_list):\n points_list = [self.points[x] for x in node.unlabelled_index] + [self.points[x] for x in node.labelled_index]\n marginal_list.append(len(points_list) / self._num_points)\n self._full_leaf_marginal_list = marginal_list\n self._full_leaf_marginal_list_up_to_date = True\n ", "context": "class Mondrian_Tree():\n def make_full_leaf_marginal_list(self): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_make_full_leaf_marginal_list_root", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000609.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "get_points_in_same_leaf", "tests": "import unittest\n\nclass Test_get_points_in_same_leaf(unittest.TestCase):\n def test_predict_and_get_point_in_same_leaf_bad_input(self):\n with self.assertRaises(TypeError):\n self.mt1.predict(1)\n self.mt1.get_points_in_same_leaf(1)\n\n def test_predict_and_get_point_in_same_leaf_bad_input_2(self):\n with self.assertRaises(TypeError):\n self.mt1.predict('abc')\n self.mt1.get_points_in_same_leaf('abc')\n\n def test_predict_and_get_point_in_same_leaf_bad_length(self):\n with self.assertRaises(ValueError):\n self.mt1.predict([])\n self.mt1.get_points_in_same_leaf([])\n\n def test_get_point_in_same_leaf_labelled(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.make_full_leaf_list()\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n random.seed(seed)\n new_point = []\n for j in range(self.d):\n new_point.append(random.random())\n labelled_list = self.mt1.get_points_in_same_leaf(new_point)\n node = self.mt1._root.leaf_for_point(new_point)\n self.assertEqual(labelled_list, node.labelled_index)\n\n def test_get_point_in_same_leaf_unlabelled(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.make_full_leaf_list()\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n random.seed(seed)\n new_point = []\n for j in range(self.d):\n new_point.append(random.random())\n unlabelled_list = self.mt1.get_points_in_same_leaf(new_point, 'unlabelled')\n node = self.mt1._root.leaf_for_point(new_point)\n self.assertEqual(unlabelled_list, node.unlabelled_index)\n\n def test_get_point_in_same_leaf_bad_list_name(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=100)\n self.mt1.make_full_leaf_list()\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n random.seed(seed)\n new_point = []\n for j in range(self.d):\n new_point.append(random.random())\n with self.assertWarns(UserWarning):\n labelled_list = self.mt1.get_points_in_same_leaf(new_point, 'neither')\n node = self.mt1._root.leaf_for_point(new_point)\n self.assertEqual(labelled_list, node.labelled_index)\n", "method_code": " def get_points_in_same_leaf(self, new_point, which_index_list='labelled'):\n \"\"\"Gets the labelled and unlabelled point index lists for a given data point. If you want\n to predict something other than the mean (say the median), or say sample from the tree's\n predicted conditional distribution, you can use this to help implement whatever you want.\n \n Returns the labelled or unlabelled index lists. Labelled is the default. Pick using \n 'labelled' or 'unlabelled'\n \"\"\"\n new_point = copy.deepcopy(new_point)\n new_point = self._test_point(new_point)\n correct_leaf = self._root.leaf_for_point(new_point)\n if which_index_list == 'labelled':\n return correct_leaf.labelled_index\n elif which_index_list == 'unlabelled':\n return correct_leaf.unlabelled_index\n else:\n warnings.warn(\"WARNING: which_index_list was not 'labelled' or 'unlabelled'. Defaulting to return labelled index list.\")\n return correct_leaf.labelled_index\n ", "context": "class Mondrian_Tree():\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_predict_and_get_point_in_same_leaf_bad_input", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000610.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "predict", "tests": "import unittest\n\nclass Test_predict(unittest.TestCase):\n def test_predict_empty(self):\n with self.assertWarns(UserWarning):\n self.mt1.predict([0.5] * self.d)\n", "method_code": " def predict(self, new_point):\n \"\"\"Make prediction for a data point using the mean of that leaf. If a list of points is\n given returns a list of predictions.\n \"\"\"\n try:\n if len(new_point) == 0:\n raise ValueError('No data in this new_point')\n except TypeError:\n raise TypeError('Given object has no len() so it is not a point or list of points.')\n depth = lambda L: isinstance(L, list) and max(map(depth, L)) + 1\n new_point_depth = depth(new_point)\n if new_point_depth > 2:\n raise ValueError('Input has too many nested structures')\n if new_point_depth == 2 or (str(type(new_point)) == \"\" and len(new_point.shape) == 2):\n preds = []\n for i in range(len(new_point)):\n preds.append(self.predict(new_point[i]))\n return preds\n new_point = copy.deepcopy(new_point)\n new_point = self._test_point(new_point)\n correct_leaf = self._root.leaf_for_point(new_point)\n if len(correct_leaf.labelled_index) == 0:\n warnings.warn('WARNING: No labelled data in this leaf. The value of {} is returned by default but really should not be considered an actual prediction unless you set it with data using. the .prediction_default_value instance variable.Possible solutions to this are to sample data within that leaf, build smaller trees, or use the global data average as your prediction. But whatever solution you use dependent on what you are doing. You should be able to catch this warning and handle it automatically using the warning module with a try/except statement.'.format(self.prediction_default_value))\n return self.prediction_default_value\n elif self._full_leaf_mean_list_up_to_date:\n return self._full_leaf_mean_list[correct_leaf.full_leaf_list_pos]\n else:\n temp_lis = [self.labels[x] for x in correct_leaf.labelled_index]\n return sum(temp_lis) / len(temp_lis)\n ", "context": "class Mondrian_Tree():\n def predict(self, new_point): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_predict_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000611.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "set_default_pred_global_mean", "tests": "import unittest\n\nclass Test_set_default_pred_global_mean(unittest.TestCase):\n def test_set_default_pred_global_mean_empty(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.make_full_leaf_list()\n self.mt1.prediction_default_value = 1\n self.mt1.set_default_pred_global_mean()\n self.assertEqual(self.mt1.prediction_default_value, 0)\n\n def test_set_default_pred_global_mean(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.make_full_leaf_list()\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.set_default_pred_global_mean()\n self.assertEqual(self.mt1.prediction_default_value, sum(self.labels) / self.n_labelled)\n", "method_code": " def set_default_pred_global_mean(self):\n \"\"\"Calculates the global mean for all labelled points and sets the default prediction\n to that.\n \"\"\"\n if self.labels is None:\n self.prediction_default_value = 0\n else:\n have_labels = [x for x in self.labels if x is not None]\n if len(have_labels) != 0:\n self.prediction_default_value = sum(have_labels) / len(have_labels)\n else:\n self.prediction_default_value = 0\n ", "context": "class Mondrian_Tree():\n def set_default_pred_global_mean(self): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_set_default_pred_global_mean_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000612.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "al_set_default_var_global_var", "tests": "import unittest\n\nclass Test_al_set_default_var_global_var(unittest.TestCase):\n def test_al_set_default_var_global_var_empty(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.make_full_leaf_list()\n self.mt1.al_default_var = 1\n self.mt1.al_set_default_var_global_var()\n self.assertEqual(self.mt1.al_default_var, 0)\n\n def test_al_set_default_var_global_var(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.make_full_leaf_list()\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_set_default_var_global_var()\n self.assertEqual(self.mt1.al_default_var, utils.unbiased_var(self.labels))\n", "method_code": " def al_set_default_var_global_var(self):\n \"\"\"Calculates the global variance for all labelled points and sets the default variance\n to that.\n \"\"\"\n if self.labels is None:\n self.al_default_var = 0\n else:\n have_labels = [x for x in self.labels if x is not None]\n if len(have_labels) != 0:\n self.al_default_var = utils.unbiased_var(have_labels)\n else:\n self.al_default_var = 0\n ", "context": "class Mondrian_Tree():\n def al_set_default_var_global_var(self): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_al_set_default_var_global_var_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000613.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "al_calculate_leaf_proportions", "tests": "import unittest\n\nclass Test_al_calculate_leaf_proportions(unittest.TestCase):\n def test_al_calculate_leaf_proportions_empty_root(self):\n with self.assertWarns(UserWarning):\n self.mt1.al_calculate_leaf_proportions()\n self.assertEqual(self.mt1._al_proportions, [1])\n\n def test_al_calculate_leaf_proportions_empty(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n with self.assertWarns(UserWarning):\n self.mt1.al_calculate_leaf_proportions()\n self.assertEqual(self.mt1._al_proportions, [1 / self.mt1._num_leaves] * self.mt1._num_leaves)\n\n def test_al_calculate_leaf_proportions_root(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n self.assertEqual(self.mt1._al_proportions, [1])\n\n def test_al_calculate_leaf_proportions(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n temp_prop_list = []\n for i, node in enumerate(self.mt1._full_leaf_list):\n node_points = [x for x in node.labelled_index] + [x for x in node.unlabelled_index]\n if len(node_points) != 0:\n temp_var = utils.unbiased_var([self.labels[x] for x in node.labelled_index])\n temp_prop_list.append(math.sqrt(temp_var * (len(node_points) / self.n_points)))\n else:\n self.assertEqual(self.mt1._al_proportions[i], 0)\n normalizer = sum(temp_prop_list)\n temp_prop_list = [x / normalizer for x in temp_prop_list]\n for i, val in enumerate(temp_prop_list):\n self.assertTrue(abs(self.mt1._al_proportions[i] - val) < 1e-09)\n", "method_code": " def al_calculate_leaf_proportions(self):\n \"\"\"Calculates estimates of the leaf proportions, using estimates for leaf variances and\n marginal probabilities, as described in \n \"\"\"\n if not self._full_leaf_list_up_to_date:\n self.make_full_leaf_list()\n if not self._full_leaf_var_list_up_to_date:\n self.make_full_leaf_var_list()\n if not self._full_leaf_marginal_list_up_to_date:\n self.make_full_leaf_marginal_list()\n al_var_list = copy.copy(self._full_leaf_var_list)\n for i, val in enumerate(al_var_list):\n if val == 0:\n al_var_list[i] = self.al_default_var\n al_proportions = []\n if self._num_points == 0:\n warnings.warn('WARNING: No data points in tree. Returning uniform over all leaves')\n self._al_proportions = [1 / self._num_leaves] * self._num_leaves\n self._al_proportions_up_to_date = True\n elif sum(al_var_list) == 0:\n warnings.warn('WARNING: No non-zero variance. Returning uniform over all leaves')\n self._al_proportions = [1 / self._num_leaves] * self._num_leaves\n self._al_proportions_up_to_date = True\n else:\n for i, node in enumerate(self._full_leaf_list):\n al_proportions.append(math.sqrt(self._full_leaf_marginal_list[i] * al_var_list[i]))\n normalizer = sum(al_proportions)\n al_proportions = [x / normalizer for x in al_proportions]\n self._al_proportions = al_proportions\n self._al_proportions_up_to_date = True\n ", "context": "class Mondrian_Tree():\n def al_calculate_leaf_proportions(self): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_al_calculate_leaf_proportions_empty_root", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000614.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "al_calculate_leaf_number_new_labels", "tests": "import unittest\n\nclass Test_al_calculate_leaf_number_new_labels(unittest.TestCase):\n def test_al_calculate_leaf_number_new_labels_empty(self):\n with self.assertRaises(ValueError):\n self.mt1.al_calculate_leaf_number_new_labels(1)\n\n def test_al_calculate_leaf_number_new_labels_too_many_labelled(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n with self.assertRaises(ValueError):\n self.mt1.al_calculate_leaf_number_new_labels(1)\n\n def test_al_calculate_leaf_number_new_labels_too_few_points(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n with self.assertRaises(ValueError):\n self.mt1.al_calculate_leaf_number_new_labels(101)\n\n def test_al_calculate_leaf_number_new_labels_bad_round_by(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n with self.assertRaises(ValueError):\n self.mt1.al_calculate_leaf_number_new_labels(21, round_by='bad')\n\n def test_al_calculate_leaf_number_new_labels_root(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n self.mt1.al_calculate_leaf_number_new_labels(21)\n self.assertEqual(self.mt1._al_leaf_number_new_labels, [1])\n\n def test_al_calculate_leaf_number_new_labels_single(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n with self.assertWarns(UserWarning):\n self.mt1.al_calculate_leaf_number_new_labels(21)\n self.assertEqual(sum(self.mt1._al_leaf_number_new_labels), 1)\n\n def test_al_calculate_leaf_number_new_labels_many(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n self.mt1.al_calculate_leaf_number_new_labels(40)\n self.assertEqual(sum(self.mt1._al_leaf_number_new_labels), 20)\n", "method_code": " def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'):\n \"\"\"Calculate how many new labelled points each leaf should get to get as close as \n possible to the proportions in _al_proportions. Since these proportions might not\n be possible with integer number of points, we have two heuristic ways of making\n integer if we have too few point. \n \n The first is to floor every number and then add one to the leaves with the highest\n fractions until we've hit our budget.\n \n The second is to floor every number and then add one to the leaves with the smallest\n number of points. This is the current default.\n \n If we have too many points, we remove from the largest leaves till we are back in our \n budget.\n \n Note these are all heuristics, and can be changed and challenged.\n \"\"\"\n num_samples_total = copy.copy(num_samples_total)\n if num_samples_total < self._num_labelled:\n raise ValueError('The total given number of samples has already been exceeded.')\n if num_samples_total > self._num_points:\n raise ValueError('The total number of samples is greater than the number of points.')\n if not self._al_proportions_up_to_date:\n print('Calculating leaf proportions. Please wait')\n self.al_calculate_leaf_proportions()\n print('Done!')\n num_samples_left = num_samples_total - self._num_labelled\n num_per_leaf_fractions = [x * num_samples_total for x in self._al_proportions]\n current_num_per_leaf = []\n unlabelled_num_per_leaf = []\n for i, node in enumerate(self._full_leaf_list):\n current_num_per_leaf.append(len(node.labelled_index))\n unlabelled_num_per_leaf.append(len(node.unlabelled_index))\n num_per_leaf = [max(0, math.floor(x) - current_num_per_leaf[i]) for i, x in enumerate(num_per_leaf_fractions)]\n full_leaves = []\n for i, num in enumerate(num_per_leaf):\n if num >= unlabelled_num_per_leaf[i]:\n num_per_leaf[i] = unlabelled_num_per_leaf[i]\n full_leaves.append(i)\n remaining_budget = num_samples_left - sum(num_per_leaf)\n if abs(remaining_budget / num_samples_left) > 0.2:\n warnings.warn('remaining_budget is = {} fraction of number of new samples. It may not be possible to get close to the optimal solution given the current locations of labelled data.'.format(round(abs(remaining_budget / num_samples_left), 3)))\n if round_by == 'highest':\n num_per_leaf_fractions = [x - math.floor(x) for x in num_per_leaf_fractions]\n for ind in full_leaves:\n num_per_leaf_fractions[ind] = 0\n while remaining_budget > 0:\n num_per_leaf[num_per_leaf_fractions.index(max(num_per_leaf_fractions))] += 1\n num_per_leaf_fractions[num_per_leaf_fractions.index(max(num_per_leaf_fractions))] = 0\n remaining_budget -= 1\n if all([x == 0 for x in num_per_leaf_fractions]):\n num_per_leaf_fractions = [x - math.floor(x) for x in num_per_leaf_fractions]\n for i, num in enumerate(num_per_leaf):\n if num >= unlabelled_num_per_leaf[i]:\n num_per_leaf[i] = unlabelled_num_per_leaf[i]\n full_leaves.append(i)\n for ind in full_leaves:\n num_per_leaf_fractions[ind] = 0\n elif round_by == 'smallest':\n total_num_per_leaf = [math.floor(x * num_samples_total) for x in self._al_proportions]\n for ind in full_leaves:\n total_num_per_leaf[ind] = float('inf')\n while remaining_budget > 0:\n num_per_leaf[total_num_per_leaf.index(min(total_num_per_leaf))] += 1\n total_num_per_leaf[total_num_per_leaf.index(min(total_num_per_leaf))] = float('inf')\n remaining_budget -= 1\n if all([math.isinf(x) for x in total_num_per_leaf]):\n total_num_per_leaf = [math.floor(x * num_samples_total) for x in self._al_proportions]\n for i, num in enumerate(num_per_leaf):\n if num >= unlabelled_num_per_leaf[i]:\n num_per_leaf[i] = unlabelled_num_per_leaf[i]\n full_leaves.append(i)\n for ind in full_leaves:\n total_num_per_leaf[ind] = float('inf')\n else:\n raise ValueError('Invalid round_by')\n total_num_per_leaf = [math.floor(x * num_samples_total) for x in self._al_proportions]\n while remaining_budget < 0:\n for i, val in enumerate(num_per_leaf):\n if val == 0:\n total_num_per_leaf[i] = float('-inf')\n num_per_leaf[total_num_per_leaf.index(max(total_num_per_leaf))] -= 1\n total_num_per_leaf[total_num_per_leaf.index(max(total_num_per_leaf))] -= 1\n remaining_budget += 1\n self._al_leaf_number_new_labels = num_per_leaf\n ", "context": "class Mondrian_Tree():\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_point_probabilities_proportions(self): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_al_calculate_leaf_number_new_labels_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000615.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "al_calculate_point_probabilities_proportions", "tests": "import unittest\n\nclass Test_al_calculate_point_probabilities_proportions(unittest.TestCase):\n def test_al_calculate_point_probabilities_proportions_empty(self):\n with self.assertWarns(UserWarning):\n self.mt1.al_calculate_leaf_proportions()\n self.mt1.al_calculate_point_probabilities_proportions()\n self.assertEqual(self.mt1._al_point_weights_proportional, [])\n\n def test_al_calculate_point_probabilities_proportions_root(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n self.mt1.al_calculate_point_probabilities_proportions()\n self.assertEqual(self.mt1._al_point_weights_proportional, [None] * 20 + [1 / (self.n_points - self.n_labelled)] * (self.n_points - self.n_labelled))\n\n def test_al_calculate_point_probabilities_proportions(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n self.mt1.al_calculate_point_probabilities_proportions()\n for i, node in enumerate(self.mt1._full_leaf_list):\n tot = 0\n for ind in node.unlabelled_index:\n tot += self.mt1._al_point_weights_proportional[ind]\n self.assertTrue(abs(tot - self.mt1._al_proportions[i]) < 1e-09)\n", "method_code": " def al_calculate_point_probabilities_proportions(self):\n \"\"\"Calculate the corresponding probabilities given to each point in order to achieve\n the correct leaf proportions. Each point is given weight of the leaf divided by the\n number of unlabelled points in the leaf.\n \"\"\"\n if not self._al_proportions_up_to_date:\n print('Calculating leaf proportions. Please wait')\n self.al_calculate_leaf_proportions()\n print('Done!')\n point_prob_list = [None] * self._num_points\n for i, node in enumerate(self._full_leaf_list):\n for ind in node.unlabelled_index:\n point_prob_list[ind] = self._al_proportions[i] / len(node.unlabelled_index)\n self._al_point_weights_proportional = point_prob_list\n ", "context": "class Mondrian_Tree():\n def al_calculate_point_probabilities_proportions(self): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_al_calculate_point_probabilities_proportions_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000616.py"} {"focal_file": "Mondrian_Tree.py", "focal_class": null, "focal_method": "al_calculate_point_probabilities_adjustment", "tests": "import unittest\n\nclass Test_al_calculate_point_probabilities_adjustment(unittest.TestCase):\n def test_al_calculate_point_probabilities_adjustment_empty(self):\n with self.assertWarns(UserWarning):\n self.mt1.al_calculate_leaf_proportions()\n with self.assertRaises(ValueError):\n self.mt1.al_calculate_point_probabilities_adjustment(1)\n self.assertEqual(self.mt1._al_point_weights_adjustment, None)\n\n def test_al_calculate_point_probabilities_adjustment_root(self):\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n self.mt1.al_calculate_point_probabilities_adjustment(21)\n for val in self.mt1._al_point_weights_adjustment:\n if val is not None:\n self.assertAlmostEqual(val, 1 / (self.n_points - self.n_labelled))\n\n def test_al_calculate_point_probabilities_adjustment(self):\n lbda = 0.5\n seed = 1\n self.mt1.update_life_time(lbda, set_seed=seed)\n self.mt1.input_data(self.data, self.labelled_indices, self.labels)\n self.mt1.al_calculate_leaf_proportions()\n self.mt1.al_calculate_point_probabilities_adjustment(21)\n self.assertAlmostEqual(sum([x for x in self.mt1._al_point_weights_adjustment if x]), 1)\n", "method_code": " def al_calculate_point_probabilities_adjustment(self, num_samples_total):\n \"\"\"Calculate the corresponding probabilities given to each point such that in expectation\n the number of points sampled from each leaf will be the leaf proportion times the \n num_samples_total.\n \n If the leaf has already had more samples than expected, gives probability 0. All \n probabilities are normalized to account for rounding issues and passive oversampling of\n leaves (NOTE: THIS ROUNDING IS AD HOC SOLUTION TO PROBLEM)\n \"\"\"\n num_samples_total = copy.copy(num_samples_total)\n if not self._al_proportions_up_to_date:\n print('Calculating leaf proportions. Please wait')\n self.al_calculate_leaf_proportions()\n print('Done!')\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n self.al_calculate_leaf_number_new_labels(num_samples_total)\n num_samples_left = num_samples_total - self._num_labelled\n point_prob_list = [None] * self._num_points\n for i, node in enumerate(self._full_leaf_list):\n num_needed = self._al_leaf_number_new_labels[i]\n for ind in node.unlabelled_index:\n point_prob_list[ind] = max(0, num_needed / (num_samples_left * len(node.unlabelled_index)))\n tot = sum([x for x in point_prob_list if x is not None])\n if tot != 0:\n for i, val in enumerate(point_prob_list):\n if val is not None:\n point_prob_list[i] = point_prob_list[i] / tot\n self._al_point_weights_adjustment = point_prob_list\n ", "context": "class Mondrian_Tree():\n def al_calculate_point_probabilities_adjustment(self, num_samples_total): ...\n def __init__(self, linear_dims, seed=None): ...\n def __str__(self): ...\n def _test_point(self, new_point): ...\n def update_life_time(self, new_life_time, set_seed=None): ...\n def input_data(self, all_data, labelled_indices, labels, copy_data=True): ...\n def label_point(self, index, value): ...\n def add_data_point(self, new_point, label=None): ...\n def make_full_leaf_list(self): ...\n def make_full_leaf_mean_list(self): ...\n def make_full_leaf_var_list(self): ...\n def make_full_leaf_marginal_list(self): ...\n def update_leaf_lists(self): ...\n def predict(self, new_point): ...\n def get_points_in_same_leaf(self, new_point, which_index_list='labelled'): ...\n def set_default_pred_global_mean(self): ...\n def al_set_default_var_global_var(self): ...\n def al_calculate_leaf_proportions(self): ...\n def al_calculate_leaf_number_new_labels(self, num_samples_total, round_by='smallest'): ...\n def al_calculate_point_probabilities_proportions(self): ...\n\n self._linear_dims = linear_dims\n self._root = LeafNode(linear_dims=self._linear_dims)\n self._num_dimensions = len(linear_dims)\n self.points = None\n self.labels = None\n self._num_points = 0\n self._num_labelled = 0\n self._life_time = 0\n self._num_leaves = 1\n self._full_leaf_list = []\n self._full_leaf_mean_list = []\n self._full_leaf_var_list = []\n self._full_leaf_marginal_list = []\n self._full_leaf_list_up_to_date = False\n self._full_leaf_mean_list_up_to_date = False\n self._full_leaf_var_list_up_to_date = False\n self._full_leaf_marginal_list_up_to_date = False\n self.prediction_default_value = 0\n self._al_proportions = []\n self._al_proportions_up_to_date = False\n self.al_default_var = 0\n self._al_point_weights_proportional = None\n self._al_point_weights_adjustment = None\n self._al_leaf_number_new_labels = None\n self._verbose = False\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_al_calculate_point_probabilities_adjustment_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000617.py"} {"focal_file": "core/SplitNode.py", "focal_class": null, "focal_method": "calculate_subtree_linear_dim", "tests": "import unittest\n\nclass Test_calculate_subtree_linear_dim(unittest.TestCase):\n def test_calculate_entire_tree_linear_dim(self):\n self.assertEqual(self.A.calculate_subtree_linear_dim(), 4.3)\n", "method_code": " def calculate_subtree_linear_dim(self):\n \"\"\"Note this is likely to be very expensive. Ideally the subtree linear dim value\n should be updated as you build the tree percolating up\n \"\"\"\n self.subtree_linear_dim = self.left_child.calculate_subtree_linear_dim() + self.right_child.calculate_subtree_linear_dim()\n return self.subtree_linear_dim\n ", "context": "class SplitNode():\n def calculate_subtree_linear_dim(self): ...\n def __init__(self, split_dim, split_val, left_child, right_child, parent_node=None, parent_branch=None, subtree_linear_dim=None): ...\n def __str__(self): ...\n def percolate_subtree_linear_dim_change(self, val): ...\n def leaf_for_point(self, data_point): ...\n def is_leaf(self): ...\n\n self.split_dim = copy.copy(split_dim)\n self.split_val = copy.copy(split_val)\n self.parent_node = parent_node\n self.parent_branch = parent_branch\n self.left_child = left_child\n self.right_child = right_child\n self.subtree_linear_dim = subtree_linear_dim\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_calculate_entire_tree_linear_dim", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000618.py"} {"focal_file": "core/SplitNode.py", "focal_class": null, "focal_method": "leaf_for_point", "tests": "import unittest\n\nclass Test_leaf_for_point(unittest.TestCase):\n def test_leaf_for_point_in_domain(self):\n self.assertEqual(self.A.leaf_for_point([0, 1]), self.B)\n\n def test_leaf_for_point_outof_domain(self):\n self.assertEqual(self.A.leaf_for_point([-1, 2]), self.B)\n", "method_code": " def leaf_for_point(self, data_point):\n if data_point[self.split_dim] < self.split_val:\n if self.left_child.is_leaf():\n return self.left_child\n else:\n return self.left_child.leaf_for_point(data_point)\n elif self.right_child.is_leaf():\n return self.right_child\n else:\n return self.right_child.leaf_for_point(data_point)\n ", "context": "class SplitNode():\n def leaf_for_point(self, data_point): ...\n def __init__(self, split_dim, split_val, left_child, right_child, parent_node=None, parent_branch=None, subtree_linear_dim=None): ...\n def __str__(self): ...\n def calculate_subtree_linear_dim(self): ...\n def percolate_subtree_linear_dim_change(self, val): ...\n def is_leaf(self): ...\n\n self.split_dim = copy.copy(split_dim)\n self.split_val = copy.copy(split_val)\n self.parent_node = parent_node\n self.parent_branch = parent_branch\n self.left_child = left_child\n self.right_child = right_child\n self.subtree_linear_dim = subtree_linear_dim\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_leaf_for_point_in_domain", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000619.py"} {"focal_file": "core/SplitNode.py", "focal_class": null, "focal_method": "percolate_subtree_linear_dim_change", "tests": "import unittest\n\nclass Test_percolate_subtree_linear_dim_change(unittest.TestCase):\n def test_percolate_subtree_linear_dim(self):\n self.A.calculate_subtree_linear_dim()\n self.D.percolate_subtree_linear_dim_change(0.5)\n self.assertEqual(self.A.subtree_linear_dim, 4.8)\n\n def test_percolate_subtree_linear_dim__2(self):\n self.A.calculate_subtree_linear_dim()\n temp_lin_dim = self.F.subtree_linear_dim\n self.F.set_linear_dims([[0, 1], [0, 1]])\n self.D.percolate_subtree_linear_dim_change(2 - temp_lin_dim)\n perc_lin_dim = copy.copy(self.A.subtree_linear_dim)\n self.A.calculate_subtree_linear_dim()\n self.assertEqual(self.A.subtree_linear_dim, perc_lin_dim)\n", "method_code": " def percolate_subtree_linear_dim_change(self, val):\n \"\"\"Changes the value of the subtree linear dimension by val for this tree\n and all it's parents. Should be the more efficient way of keeping track of\n subtree_linear_dim during tree building time.\n \"\"\"\n val = copy.copy(val)\n self.subtree_linear_dim += val\n if self.parent_node is not None:\n self.parent_node.percolate_subtree_linear_dim_change(val)\n ", "context": "class SplitNode():\n def percolate_subtree_linear_dim_change(self, val): ...\n def __init__(self, split_dim, split_val, left_child, right_child, parent_node=None, parent_branch=None, subtree_linear_dim=None): ...\n def __str__(self): ...\n def calculate_subtree_linear_dim(self): ...\n def leaf_for_point(self, data_point): ...\n def is_leaf(self): ...\n\n self.split_dim = copy.copy(split_dim)\n self.split_val = copy.copy(split_val)\n self.parent_node = parent_node\n self.parent_branch = parent_branch\n self.left_child = left_child\n self.right_child = right_child\n self.subtree_linear_dim = subtree_linear_dim\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_percolate_subtree_linear_dim", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000620.py"} {"focal_file": "core/LeafNode.py", "focal_class": null, "focal_method": "pick_new_points", "tests": "import unittest\n\nclass Test_pick_new_points(unittest.TestCase):\n def test_pick_new_points_good(self):\n self.assertEqual(self.test_leaf_good.pick_new_points(1, set_seed=1), [6])\n self.assertEqual(self.test_leaf_good.pick_new_points(2, set_seed=1), [6, 9])\n\n def test_pick_new_points_good_all(self):\n self.assertEqual(self.test_leaf_good.pick_new_points(6, set_seed=1), [6, 9, 5, 10, 8, 7])\n\n def test_pick_new_points_empty(self):\n with self.assertRaises(ValueError):\n self.test_leaf_empty.pick_new_points(1)\n\n def test_pick_new_points_self_update_true(self):\n self.test_leaf_good.pick_new_points(1, self_update=True, set_seed=1)\n self.assertEqual(self.test_leaf_good.labelled_index, [1, 2, 3, 4, 6])\n self.assertEqual(self.test_leaf_good.unlabelled_index, [5, 7, 8, 9, 10])\n\n def test_pick_new_points_self_update_false(self):\n self.test_leaf_good.pick_new_points(1, self_update=False, set_seed=1)\n self.assertEqual(self.test_leaf_good.labelled_index, [1, 2, 3, 4])\n self.assertEqual(self.test_leaf_good.unlabelled_index, [5, 6, 7, 8, 9, 10])\n", "method_code": " def pick_new_points(self, num_samples, self_update=False, set_seed=None):\n \"\"\"Returns the index of points to get labels for, and automatically adds\n them the leafs labelled points by default\n \"\"\"\n num_samples = copy.copy(num_samples)\n if num_samples > len(self.unlabelled_index):\n raise ValueError('This leaf only has {} < {} unlabelled points'.format(len(self.unlabelled_index), num_samples))\n if set_seed is not None:\n random.seed(set_seed)\n new_points = random.sample(self.unlabelled_index, num_samples)\n if self_update:\n self.extend_labelled_index(new_points)\n self.unlabelled_index = [x for x in self.unlabelled_index if x not in new_points]\n return new_points\n ", "context": "class LeafNode():\n def pick_new_points(self, num_samples, self_update=False, set_seed=None): ...\n def __init__(self, labelled_index=None, unlabelled_index=None, linear_dims=None, parent_node=None, parent_branch=None): ...\n def __str__(self): ...\n def rounded_linear_dims(self, sig_fig=2): ...\n def calculate_subtree_linear_dim(self): ...\n def make_labelled(self, index): ...\n def is_leaf(self): ...\n def leaf_for_point(self, data_point): ...\n def extend_labelled_index(self, new_labelled_list): ...\n def extend_unlabelled_index(self, new_unlabelled_list): ...\n def set_linear_dims(self, new_linear_dims): ...\n def calculate_cell_l2_diameter(self): ...\n\n self.labelled_index = copy.deepcopy(labelled_index)\n self.unlabelled_index = copy.deepcopy(unlabelled_index)\n self.linear_dims = copy.deepcopy(linear_dims)\n self.parent_node = parent_node\n self.parent_branch = parent_branch\n self.subtree_linear_dim = self.calculate_subtree_linear_dim()\n self.leaf_id = None\n self.full_leaf_list_pos = None\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_pick_new_points_good", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000621.py"} {"focal_file": "core/LeafNode.py", "focal_class": null, "focal_method": "make_labelled", "tests": "import unittest\n\nclass Test_make_labelled(unittest.TestCase):\n def test_make_labelled_not_in_unlabelled(self):\n with self.assertRaises(ValueError):\n self.test_leaf_empty.make_labelled(1)\n\n def test_make_labelled_in_unlabelled(self):\n self.test_leaf_good.make_labelled(5)\n self.assertTrue(5 not in self.test_leaf_good.unlabelled_index)\n self.assertTrue(5 in self.test_leaf_good.labelled_index)\n", "method_code": " def make_labelled(self, index):\n \"\"\"Takes a point in the unlablled_index list and moves it to the labelled one.\n If the point is not in the unlabelled_index list it returns an error.\n \"\"\"\n index = copy.copy(index)\n if index not in self.unlabelled_index:\n raise ValueError('Point {} is not in this leaf'.format(index))\n self.labelled_index.append(index)\n self.unlabelled_index.remove(index)\n ", "context": "class LeafNode():\n def make_labelled(self, index): ...\n def __init__(self, labelled_index=None, unlabelled_index=None, linear_dims=None, parent_node=None, parent_branch=None): ...\n def __str__(self): ...\n def rounded_linear_dims(self, sig_fig=2): ...\n def pick_new_points(self, num_samples, self_update=False, set_seed=None): ...\n def calculate_subtree_linear_dim(self): ...\n def is_leaf(self): ...\n def leaf_for_point(self, data_point): ...\n def extend_labelled_index(self, new_labelled_list): ...\n def extend_unlabelled_index(self, new_unlabelled_list): ...\n def set_linear_dims(self, new_linear_dims): ...\n def calculate_cell_l2_diameter(self): ...\n\n self.labelled_index = copy.deepcopy(labelled_index)\n self.unlabelled_index = copy.deepcopy(unlabelled_index)\n self.linear_dims = copy.deepcopy(linear_dims)\n self.parent_node = parent_node\n self.parent_branch = parent_branch\n self.subtree_linear_dim = self.calculate_subtree_linear_dim()\n self.leaf_id = None\n self.full_leaf_list_pos = None\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_make_labelled_not_in_unlabelled", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000622.py"} {"focal_file": "core/utils.py", "focal_class": null, "focal_method": "choices", "tests": "import unittest\n\nclass Test_choices(unittest.TestCase):\n def test_choices_empty(self):\n with self.assertRaises(ValueError):\n utils.choices([])\n\n def test_choices_uniform(self):\n random.seed(1)\n n = 10\n nreps = 1000\n counting_list = [0] * n\n for i in range(nreps):\n counting_list[utils.choices(range(n))[0]] += 1\n self.assertTrue(max(counting_list) - min(counting_list) < nreps / 10)\n\n def test_choices_weighted(self):\n random.seed(1)\n n = 10\n nreps = 1000\n counting_list = [0] * n\n for i in range(nreps):\n counting_list[utils.choices(range(n), [1 / (4 * n)] * (n - 1) + [1 - (n - 1) / (4 * n)])[0]] += 1\n self.assertTrue(counting_list[-1] > sum(counting_list) - counting_list[-1])\n", "method_code": "def choices(population, weights=None, *, cum_weights=None, k=1):\n \"\"\"Copy of source code for random.choices added to random module in 3.6\n\n Return a k sized list of population elements chosen with replacement.\n\n If the relative weights or cumulative weights are not specified,\n the selections are made with equal probability.\n\n \"\"\"\n if len(population) == 0:\n raise ValueError('Population cannot be empty')\n if cum_weights is None:\n if weights is None:\n total = len(population)\n return [population[int(random.random() * total)] for i in range(k)]\n cum_weights = list(itertools.accumulate(weights))\n elif weights is not None:\n raise TypeError('Cannot specify both weights and cumulative weights')\n if len(cum_weights) != len(population):\n raise ValueError('The number of weights does not match the population')\n total = cum_weights[-1]\n return [population[bisect(cum_weights, random.random() * total)] for i in range(k)]", "context": "def choices(population, weights=None, *, cum_weights=None, k=1): ...\ndef choices(population, weights=None, *, cum_weights=None, k=1): ...\ndef unbiased_var(label_list): ...\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_choices_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000623.py"} {"focal_file": "core/utils.py", "focal_class": null, "focal_method": "unbiased_var", "tests": "import unittest\n\nclass Test_unbiased_var(unittest.TestCase):\n def test_unbaised_var_empty(self):\n self.assertEqual(utils.unbiased_var([]), 0)\n\n def test_unbiased_var_single(self):\n self.assertEqual(utils.unbiased_var([1]), 0)\n\n def test_unbiased_var_all_equal(self):\n self.assertEqual(utils.unbiased_var([1, 1, 1, 1]), 0)\n\n def test_unbaised_var_unequal(self):\n self.assertEqual(utils.unbiased_var([1, -1, 1, -1]), 4 / 3)\n\n def test_unbaised_var_unequal_2(self):\n self.assertEqual(utils.unbiased_var(range(10)), 82.5 / 9)\n", "method_code": "def unbiased_var(label_list):\n n = len(label_list)\n if n < 2:\n return 0\n mean = sum(label_list) / n\n tot = 0\n for val in label_list:\n tot += (mean - val) ** 2\n return tot / (n - 1)", "context": "def unbiased_var(label_list): ...\ndef choices(population, weights=None, *, cum_weights=None, k=1): ...\ndef unbiased_var(label_list): ...\n", "repository": "jackrgoetz/Mondrian_Tree_AL", "test_name": "test_unbaised_var_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000624.py"} {"focal_file": "virtual/lib/python3.6/site-packages/psycopg2/tests/dbapi20.py", "focal_class": null, "focal_method": "_connect", "tests": "import unittest\n\nclass Test_connect(unittest.TestCase):\n def test_connect(self):\n con = self._connect()\n con.close()\n", "method_code": " def _connect(self):\n try:\n return self.driver.connect(*self.connect_args, **self.connect_kw_args)\n except AttributeError:\n self.fail('No connect method found in self.driver module')\n ", "context": "class DatabaseAPI20Test(unittest.TestCase):\n def _connect(self): ...\n def executeDDL1(self, cursor): ...\n def executeDDL2(self, cursor): ...\n def setUp(self): ...\n def tearDown(self): ...\n def test_connect(self): ...\n def test_apilevel(self): ...\n def test_threadsafety(self): ...\n def test_paramstyle(self): ...\n def test_Exceptions(self): ...\n def test_ExceptionsAsConnectionAttributes(self): ...\n def test_commit(self): ...\n def test_rollback(self): ...\n def test_cursor(self): ...\n def test_cursor_isolation(self): ...\n def test_description(self): ...\n def test_rowcount(self): ...\n def test_callproc(self): ...\n def test_close(self): ...\n def test_execute(self): ...\n def _paraminsert(self, cur): ...\n def test_executemany(self): ...\n def test_fetchone(self): ...\n def _populate(self): ...\n def test_fetchmany(self): ...\n def test_fetchall(self): ...\n def test_mixedfetch(self): ...\n def help_nextset_setUp(self, cur): ...\n def help_nextset_tearDown(self, cur): ...\n def test_nextset(self): ...\n def test_nextset(self): ...\n def test_arraysize(self): ...\n def test_setinputsizes(self): ...\n def test_setoutputsize_basic(self): ...\n def test_setoutputsize(self): ...\n def test_None(self): ...\n def test_Date(self): ...\n def test_Time(self): ...\n def test_Timestamp(self): ...\n def test_Binary(self): ...\n def test_STRING(self): ...\n def test_BINARY(self): ...\n def test_NUMBER(self): ...\n def test_DATETIME(self): ...\n def test_ROWID(self): ...\n\n driver = None\n connect_args = ()\n connect_kw_args = {}\n table_prefix = 'dbapi20test_'\n ddl1 = 'create table %sbooze (name varchar(20))' % table_prefix\n ddl2 = 'create table %sbarflys (name varchar(20))' % table_prefix\n xddl1 = 'drop table %sbooze' % table_prefix\n xddl2 = 'drop table %sbarflys' % table_prefix\n lowerfunc = 'lower'\n lower_func = 'lower'\n samples = ['Carlton Cold', 'Carlton Draft', 'Mountain Goat', 'Redback', 'Victoria Bitter', 'XXXX']\n", "repository": "garvinipkiss/portfolio", "test_name": "test_connect", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000625.py"} {"focal_file": "virtual/lib/python3.6/site-packages/psycopg2/tests/dbapi20.py", "focal_class": null, "focal_method": "help_nextset_setUp", "tests": "import unittest\n\nclass Test_help_nextset_setUp(unittest.TestCase):\n def test_nextset(self):\n con = self._connect()\n try:\n cur = con.cursor()\n if not hasattr(cur, 'nextset'):\n return\n try:\n self.executeDDL1(cur)\n sql = self._populate()\n for sql in self._populate():\n cur.execute(sql)\n self.help_nextset_setUp(cur)\n cur.callproc('deleteme')\n numberofrows = cur.fetchone()\n assert numberofrows[0] == len(self.samples)\n assert cur.nextset()\n names = cur.fetchall()\n assert len(names) == len(self.samples)\n s = cur.nextset()\n assert s == None, 'No more return sets, should return None'\n finally:\n self.help_nextset_tearDown(cur)\n finally:\n con.close()\n", "method_code": " def help_nextset_setUp(self, cur):\n \"\"\" Should create a procedure called deleteme\n that returns two result sets, first the \n \t number of rows in booze then \"name from booze\"\n \"\"\"\n raise NotImplementedError('Helper not implemented')\n ", "context": "class DatabaseAPI20Test(unittest.TestCase):\n def help_nextset_setUp(self, cur): ...\n def executeDDL1(self, cursor): ...\n def executeDDL2(self, cursor): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _connect(self): ...\n def test_connect(self): ...\n def test_apilevel(self): ...\n def test_threadsafety(self): ...\n def test_paramstyle(self): ...\n def test_Exceptions(self): ...\n def test_ExceptionsAsConnectionAttributes(self): ...\n def test_commit(self): ...\n def test_rollback(self): ...\n def test_cursor(self): ...\n def test_cursor_isolation(self): ...\n def test_description(self): ...\n def test_rowcount(self): ...\n def test_callproc(self): ...\n def test_close(self): ...\n def test_execute(self): ...\n def _paraminsert(self, cur): ...\n def test_executemany(self): ...\n def test_fetchone(self): ...\n def _populate(self): ...\n def test_fetchmany(self): ...\n def test_fetchall(self): ...\n def test_mixedfetch(self): ...\n def help_nextset_tearDown(self, cur): ...\n def test_nextset(self): ...\n def test_nextset(self): ...\n def test_arraysize(self): ...\n def test_setinputsizes(self): ...\n def test_setoutputsize_basic(self): ...\n def test_setoutputsize(self): ...\n def test_None(self): ...\n def test_Date(self): ...\n def test_Time(self): ...\n def test_Timestamp(self): ...\n def test_Binary(self): ...\n def test_STRING(self): ...\n def test_BINARY(self): ...\n def test_NUMBER(self): ...\n def test_DATETIME(self): ...\n def test_ROWID(self): ...\n\n driver = None\n connect_args = ()\n connect_kw_args = {}\n table_prefix = 'dbapi20test_'\n ddl1 = 'create table %sbooze (name varchar(20))' % table_prefix\n ddl2 = 'create table %sbarflys (name varchar(20))' % table_prefix\n xddl1 = 'drop table %sbooze' % table_prefix\n xddl2 = 'drop table %sbarflys' % table_prefix\n lowerfunc = 'lower'\n lower_func = 'lower'\n samples = ['Carlton Cold', 'Carlton Draft', 'Mountain Goat', 'Redback', 'Victoria Bitter', 'XXXX']\n", "repository": "garvinipkiss/portfolio", "test_name": "test_nextset", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000626.py"} {"focal_file": "pygame/tests/test_utils/arrinter.py", "focal_class": null, "focal_method": "is_contiguous", "tests": "import unittest\n\nclass Test_is_contiguous(unittest.TestCase):\n def test_is_contiguous(self):\n a = Exporter((10,), itemsize=2)\n self.assertTrue(a.is_contiguous('C'))\n self.assertTrue(a.is_contiguous('F'))\n self.assertTrue(a.is_contiguous('A'))\n a = Exporter((10, 4), itemsize=2)\n self.assertTrue(a.is_contiguous('C'))\n self.assertTrue(a.is_contiguous('A'))\n self.assertFalse(a.is_contiguous('F'))\n a = Exporter((13, 5, 11, 3), itemsize=2, strides=(330, 66, 6, 2))\n self.assertTrue(a.is_contiguous('C'))\n self.assertTrue(a.is_contiguous('A'))\n self.assertFalse(a.is_contiguous('F'))\n a = Exporter((10, 4), itemsize=2, strides=(2, 20))\n self.assertTrue(a.is_contiguous('F'))\n self.assertTrue(a.is_contiguous('A'))\n self.assertFalse(a.is_contiguous('C'))\n a = Exporter((13, 5, 11, 3), itemsize=2, strides=(2, 26, 130, 1430))\n self.assertTrue(a.is_contiguous('F'))\n self.assertTrue(a.is_contiguous('A'))\n self.assertFalse(a.is_contiguous('C'))\n a = Exporter((2, 11, 6, 4), itemsize=2, strides=(576, 48, 8, 2))\n self.assertFalse(a.is_contiguous('A'))\n a = Exporter((2, 11, 6, 4), itemsize=2, strides=(2, 4, 48, 288))\n self.assertFalse(a.is_contiguous('A'))\n a = Exporter((3, 2, 2), itemsize=2, strides=(16, 8, 4))\n self.assertFalse(a.is_contiguous('A'))\n a = Exporter((3, 2, 2), itemsize=2, strides=(4, 12, 24))\n self.assertFalse(a.is_contiguous('A'))\n", "method_code": " def is_contiguous(self, fortran):\n if fortran in 'CA':\n if self.strides[-1] == self.itemsize:\n for i in range(self.nd - 1, 0, -1):\n if self.strides[i - 1] != self.shape[i] * self.strides[i]:\n break\n else:\n return True\n if fortran in 'FA':\n if self.strides[0] == self.itemsize:\n for i in range(0, self.nd - 1):\n if self.strides[i + 1] != self.shape[i] * self.strides[i]:\n break\n else:\n return True\n return False\n ", "context": "class Exporter(object):\n def is_contiguous(self, fortran): ...\n def __init__(self, shape, typekind=None, itemsize=None, strides=None, descr=None, flags=None): ...\n\n self.typekind = typekind\n self.itemsize = itemsize\n self.nd = nd\n self.shape = tuple(shape)\n self._shape = (c_ssize_t * self.nd)(*self.shape)\n self.descr = descr\n self.flags = flags\n self._data = (c_ubyte * sz)()\n self.data = addressof(self._data)\n self._inter = PyArrayInterface(2, nd, typekind.encode('latin_1'), itemsize, flags, self._shape, self._strides, self.data, descr)\n self.len = itemsize\n\n __array_struct__ = property(lambda self: capsule_new(self._inter))\n", "repository": "beartwigsam/Pygame-for-Python-3.4", "test_name": "test_is_contiguous", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000627.py"} {"focal_file": "pygame/tests/test_utils/arrinter.py", "focal_class": null, "focal_method": "_addr_at", "tests": "import unittest\n\nclass Test_addr_at(unittest.TestCase):\n def test__addr_at(self):\n a = self.a\n self.assertEqual(a._addr_at((0, 0)), a.data)\n self.assertEqual(a._addr_at((0, 1)), a.data + 4)\n self.assertEqual(a._addr_at((1, 0)), a.data + 60)\n self.assertEqual(a._addr_at((1, 1)), a.data + 64)\n", "method_code": " def _addr_at(self, key):\n if not isinstance(key, tuple):\n key = (key,)\n if len(key) != self.nd:\n raise ValueError('wrong number of indexes')\n for i in range(self.nd):\n if not 0 <= key[i] < self.shape[i]:\n raise IndexError('index {} out of range'.format(i))\n return self.data + sum((i * s for i, s in zip(key, self.strides)))\n ", "context": "class Array(Exporter):\n def _addr_at(self, key): ...\n def __init__(self, *args, **kwds): ...\n def __getitem__(self, key): ...\n def __setitem__(self, key, value): ...\n\n self._ctype = ct\n self._ctype_p = POINTER(ct)\n\n _ctypes = {('u', 1): c_uint8, ('u', 2): c_uint16, ('u', 4): c_uint32, ('u', 8): c_uint64, ('i', 1): c_int8, ('i', 2): c_int16, ('i', 4): c_int32, ('i', 8): c_int64}\n", "repository": "beartwigsam/Pygame-for-Python-3.4", "test_name": "test__addr_at", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000628.py"} {"focal_file": "pygame/tests/test_utils/async_sub.py", "focal_class": null, "focal_method": "proc_in_time_or_kill", "tests": "import unittest\n\nclass Test_proc_in_time_or_kill(unittest.TestCase):\n def test_proc_in_time_or_kill(self):\n ret_code, response = proc_in_time_or_kill([sys.executable, '-c', 'while 1: pass'], time_out=1)\n self.assert_('rocess timed out' in ret_code)\n self.assert_('successfully terminated' in ret_code)\n", "method_code": "def proc_in_time_or_kill(cmd, time_out, wd=None, env=None):\n proc = Popen(cmd, cwd=wd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=1)\n ret_code = None\n response = []\n t = time.time()\n while ret_code is None and time.time() - t < time_out:\n ret_code = proc.poll()\n response += [proc.read_async(wait=0.1, e=0)]\n if ret_code is None:\n ret_code = '\"Process timed out (time_out = %s secs) ' % time_out\n try:\n proc.kill()\n ret_code += 'and was successfully terminated\"'\n except Exception:\n ret_code += 'and termination failed (exception: %s)\"' % (geterror(),)\n return (ret_code, ''.join(response))", "context": "def proc_in_time_or_kill(cmd, time_out, wd=None, env=None): ...\ndef geterror(): ...\ndef proc_in_time_or_kill(cmd, time_out, wd=None, env=None): ...\ndef _example(): ...\n", "repository": "beartwigsam/Pygame-for-Python-3.4", "test_name": "test_proc_in_time_or_kill", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000629.py"} {"focal_file": "spel/HERE/pytmx/util_pygame.py", "focal_class": null, "focal_method": "build_rects", "tests": "import unittest\n\nclass Test_build_rects(unittest.TestCase):\n def test_build_rects(self):\n from pytmx import util_pygame\n rects = util_pygame.build_rects(self.m, 'Grass and Water', 'tileset', None)\n self.assertEqual(rects[0], [0, 0, 240, 240])\n rects = util_pygame.build_rects(self.m, 'Grass and Water', 'tileset', 18)\n self.assertNotEqual(0, len(rects))\n", "method_code": "def build_rects(tmxmap, layer, tileset=None, real_gid=None):\n \"\"\"generate a set of non-overlapping rects that represents the distribution\n of the specified gid.\n\n useful for generating rects for use in collision detection\n\n Use at your own risk: this is experimental...will change in future\n\n GID Note: You will need to add 1 to the GID reported by Tiled.\n\n :param tmxmap: TiledMap object\n :param layer: int or string name of layer\n :param tileset: int or string name of tileset\n :param real_gid: Tiled GID of the tile + 1 (see note)\n :return: List of pygame Rect objects\n \"\"\"\n if isinstance(tileset, int):\n try:\n tileset = tmxmap.tilesets[tileset]\n except IndexError:\n msg = 'Tileset #{0} not found in map {1}.'\n logger.debug(msg.format(tileset, tmxmap))\n raise IndexError\n elif isinstance(tileset, str):\n try:\n tileset = [t for t in tmxmap.tilesets if t.name == tileset].pop()\n except IndexError:\n msg = 'Tileset \"{0}\" not found in map {1}.'\n logger.debug(msg.format(tileset, tmxmap))\n raise ValueError\n elif tileset:\n msg = 'Tileset must be either a int or string. got: {0}'\n logger.debug(msg.format(type(tileset)))\n raise TypeError\n gid = None\n if real_gid:\n try:\n gid, flags = tmxmap.map_gid(real_gid)[0]\n except IndexError:\n msg = 'GID #{0} not found'\n logger.debug(msg.format(real_gid))\n raise ValueError\n if isinstance(layer, int):\n layer_data = tmxmap.get_layer_data(layer)\n elif isinstance(layer, str):\n try:\n layer = [l for l in tmxmap.layers if l.name == layer].pop()\n layer_data = layer.data\n except IndexError:\n msg = 'Layer \"{0}\" not found in map {1}.'\n logger.debug(msg.format(layer, tmxmap))\n raise ValueError\n p = itertools.product(range(tmxmap.width), range(tmxmap.height))\n if gid:\n points = [(x, y) for x, y in p if layer_data[y][x] == gid]\n else:\n points = [(x, y) for x, y in p if layer_data[y][x]]\n rects = simplify(points, tmxmap.tilewidth, tmxmap.tileheight)\n return rects", "context": "def build_rects(tmxmap, layer, tileset=None, real_gid=None): ...\ndef handle_transformation(tile, flags): ...\ndef smart_convert(original, colorkey, pixelalpha): ...\ndef pygame_image_loader(filename, colorkey, **kwargs): ...\ndef load_pygame(filename, *args, **kwargs): ...\ndef build_rects(tmxmap, layer, tileset=None, real_gid=None): ...\ndef simplify(all_points, tilewidth, tileheight): ...\n", "repository": "beartwigsam/Pygame-for-Python-3.4", "test_name": "test_build_rects", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000630.py"} {"focal_file": "bootstrap/bootstrap.py", "focal_class": null, "focal_method": "jackknife_sample", "tests": "import unittest\n\nclass Test_jackknife_sample(unittest.TestCase):\n def testJackknifeSample(self):\n jackknife_data = jackknife_sample(self.uniform_data, 10)\n self.assertAlmostEqual(np.mean(self.uniform_data) / 10000, np.mean(jackknife_data) / 10000, 3)\n self.assertEqual(len(jackknife_data) + 1, len(self.uniform_data))\n", "method_code": "def jackknife_sample(data, index):\n \"\"\"\n Single jackknife sample of data\n\n Args:\n ---------\n data : np.array\n array of data to resample\n index : int\n Index of array to leave out in jackknife sample\n\n Returns:\n ---------\n resamples : array\n jackknife resampled data\n \"\"\"\n jackknife = np.delete(data, index)\n return jackknife", "context": "def jackknife_sample(data, index): ...\ndef bootstrap_sample(data, parametric=False): ...\ndef bootstrap_matrixsample(data, axis=0): ...\ndef jackknife_sample(data, index): ...\ndef bootstrap_statistic(data, func=np.mean, n_samples=50, parametric=False, bias_correction=False, alpha=0.05, bca=False, axis=0): ...\ndef jackknife_statistic(data, func=np.mean): ...\ndef calculate_ci(data, statistics, func=np.mean, alpha=0.05, bca=False): ...\ndef two_sample_testing(sampleA, sampleB, statistic_func=None, n_samples=50): ...\ndef compare_means(sampleA, sampleB): ...\ndef t_test_statistic(sampleA, sampleB): ...\n", "repository": "christopherjenness/bootstrap", "test_name": "testJackknifeSample", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000631.py"} {"focal_file": "bootstrap/bootstrap.py", "focal_class": null, "focal_method": "t_test_statistic", "tests": "import unittest\n\nclass Test_t_test_statistic(unittest.TestCase):\n def testTStatisticBig(self):\n t_statistic = t_test_statistic(self.normal_data2, self.normal_data)\n self.assertAlmostEqual(t_statistic / 10000, 0.007, 3)\n\n def testTStatisticZero(self):\n t_statistic = t_test_statistic(self.normal_data, self.normal_data)\n self.assertEqual(t_statistic, 0)\n", "method_code": "def t_test_statistic(sampleA, sampleB):\n \"\"\"\n Computes the t test statistic of two samples\n\n Args:\n ---------\n sampleA : np.array\n Array of data from sample A\n sampleB : np.array\n Array of data form sample B\n\n Returns:\n ---------\n t_stat : float\n t test statistic of two samples\n \"\"\"\n difference = compare_means(sampleA, sampleB)\n n = len(sampleA)\n m = len(sampleB)\n stdev = (np.var(sampleA) / n + np.var(sampleB) / m) ** 0.5\n t_stat = difference / stdev\n return t_stat", "context": "def t_test_statistic(sampleA, sampleB): ...\ndef bootstrap_sample(data, parametric=False): ...\ndef bootstrap_matrixsample(data, axis=0): ...\ndef jackknife_sample(data, index): ...\ndef bootstrap_statistic(data, func=np.mean, n_samples=50, parametric=False, bias_correction=False, alpha=0.05, bca=False, axis=0): ...\ndef jackknife_statistic(data, func=np.mean): ...\ndef calculate_ci(data, statistics, func=np.mean, alpha=0.05, bca=False): ...\ndef two_sample_testing(sampleA, sampleB, statistic_func=None, n_samples=50): ...\ndef compare_means(sampleA, sampleB): ...\ndef t_test_statistic(sampleA, sampleB): ...\n", "repository": "christopherjenness/bootstrap", "test_name": "testTStatisticBig", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000632.py"} {"focal_file": "bootstrap/bootstrap.py", "focal_class": null, "focal_method": "two_sample_testing", "tests": "import unittest\n\nclass Test_two_sample_testing(unittest.TestCase):\n def testTwoSampleZero(self):\n ASL = two_sample_testing(self.normal_data2, self.normal_data)\n self.assertEqual(ASL, 0)\n\n def testTwoSampleBig(self):\n ASL = two_sample_testing(self.normal_data, self.normal_data)\n self.assertGreater(ASL, 0.05)\n\n def testTwoSampleTTest(self):\n ASL = two_sample_testing(self.normal_data2, self.normal_data, statistic_func=t_test_statistic)\n self.assertEqual(ASL, 0)\n\n def testTwoSampleTTestBit(self):\n ASL = two_sample_testing(self.normal_data, self.normal_data, statistic_func=t_test_statistic)\n self.assertGreater(ASL, 0.05)\n", "method_code": "def two_sample_testing(sampleA, sampleB, statistic_func=None, n_samples=50):\n \"\"\"\n Compares two samples via bootstrapping to determine if they came from\n the same distribution.\n\n Args:\n ---------\n sampleA : np.array\n Array of data from sample A\n sampleB : np.array\n Array of data form sample B\n statistic_func : function\n Function that compares two data sets and retuns a statistic. Function\n must accept two args, (np.array, np.array), where each array is a\n sample.\n Example statistics_func that compares the mean of two data sets:\n lambda data1, data2: np.mean(data1) - np.mean(data2)\n n_samples : int\n number of bootstrap samples to generate\n\n Returns:\n ---------\n sig_lvl : float\n bootstrapped achieved significance level\n \"\"\"\n if statistic_func is None:\n statistic_func = compare_means\n observed_statistic = statistic_func(sampleA, sampleB)\n combined_sample = np.append(sampleA, sampleB)\n m = len(sampleA)\n counter = 0\n for sample in range(n_samples):\n boot_sample = bootstrap_sample(combined_sample)\n boot_sampleA = boot_sample[:m]\n boot_sampleB = boot_sample[m:]\n boot_statistic = statistic_func(boot_sampleA, boot_sampleB)\n if boot_statistic > observed_statistic:\n counter += 1\n ASL = counter / float(n_samples)\n return ASL", "context": "def two_sample_testing(sampleA, sampleB, statistic_func=None, n_samples=50): ...\ndef bootstrap_sample(data, parametric=False): ...\ndef bootstrap_matrixsample(data, axis=0): ...\ndef jackknife_sample(data, index): ...\ndef bootstrap_statistic(data, func=np.mean, n_samples=50, parametric=False, bias_correction=False, alpha=0.05, bca=False, axis=0): ...\ndef jackknife_statistic(data, func=np.mean): ...\ndef calculate_ci(data, statistics, func=np.mean, alpha=0.05, bca=False): ...\ndef two_sample_testing(sampleA, sampleB, statistic_func=None, n_samples=50): ...\ndef compare_means(sampleA, sampleB): ...\ndef t_test_statistic(sampleA, sampleB): ...\n", "repository": "christopherjenness/bootstrap", "test_name": "testTwoSampleZero", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000633.py"} {"focal_file": "bootstrap/bootstrap.py", "focal_class": null, "focal_method": "bootstrap_matrixsample", "tests": "import unittest\n\nclass Test_bootstrap_matrixsample(unittest.TestCase):\n def testMatrixResamplingCol(self):\n matrix_sample = np.matrix(bootstrap_matrixsample(self.matrix_data, axis=1))\n self.assertEqual(np.shape(matrix_sample), np.shape(self.matrix_data))\n self.assertAlmostEqual(np.average(matrix_sample) / 100000, np.mean(self.matrix_data) / 100000, 3)\n", "method_code": "def bootstrap_matrixsample(data, axis=0):\n \"\"\"\n Resamples a matrix by rows or columns\n\n Args:\n ---------\n data : np.matrix\n matrix of data to resample\n axis : (int) in [0, 1]\n axis to resample by\n if 0, then resample rows\n if 1, then resample columns\n\n Returns:\n ---------\n resamples : matrix\n bootstrap resampled data\n \"\"\"\n if axis == 0:\n n_rows = np.shape(data)[0]\n samples = np.random.randint(n_rows, size=n_rows)\n bootstrap_matrix = data[samples, :]\n elif axis == 1:\n n_cols = np.shape(data)[1]\n samples = np.random.randint(n_cols, size=n_cols)\n bootstrap_matrix = data[:, samples]\n return bootstrap_matrix", "context": "def bootstrap_matrixsample(data, axis=0): ...\ndef bootstrap_sample(data, parametric=False): ...\ndef bootstrap_matrixsample(data, axis=0): ...\ndef jackknife_sample(data, index): ...\ndef bootstrap_statistic(data, func=np.mean, n_samples=50, parametric=False, bias_correction=False, alpha=0.05, bca=False, axis=0): ...\ndef jackknife_statistic(data, func=np.mean): ...\ndef calculate_ci(data, statistics, func=np.mean, alpha=0.05, bca=False): ...\ndef two_sample_testing(sampleA, sampleB, statistic_func=None, n_samples=50): ...\ndef compare_means(sampleA, sampleB): ...\ndef t_test_statistic(sampleA, sampleB): ...\n", "repository": "christopherjenness/bootstrap", "test_name": "testMatrixResamplingCol", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000634.py"} {"focal_file": "bootstrap/bootstrap.py", "focal_class": null, "focal_method": "bootstrap_statistic", "tests": "import unittest\n\nclass Test_bootstrap_statistic(unittest.TestCase):\n def testBootstrapBCa(self):\n statistics, statistic, bias, sem, confidence_interval = bootstrap_statistic(self.normal_data, bca=True)\n self.assertAlmostEqual(statistic / 100000, 100 / 100000, 2)\n self.assertAlmostEqual(np.abs(bias / 100), 0.1 / 100, 3)\n self.assertAlmostEqual(sem / 100, 0.1 / 100, 3)\n self.assertEqual(len(confidence_interval), 2)\n self.assertTrue(confidence_interval[0] < confidence_interval[1])\n self.assertTrue(confidence_interval[1] - confidence_interval[0] < 5)\n\n def testBootstrapMatrix(self):\n statistics, statistic, bias, sem, confidence_interval = bootstrap_statistic(self.normal_data)\n self.assertAlmostEqual(statistic / 100000, 100 / 100000, 2)\n self.assertAlmostEqual(np.abs(bias / 100), 0.1 / 100, 3)\n self.assertAlmostEqual(sem / 100, 0.1 / 100, 3)\n self.assertEqual(len(confidence_interval), 2)\n self.assertTrue(confidence_interval[0] < confidence_interval[1])\n self.assertTrue(confidence_interval[1] - confidence_interval[0] < 5)\n", "method_code": "def bootstrap_statistic(data, func=np.mean, n_samples=50, parametric=False, bias_correction=False, alpha=0.05, bca=False, axis=0):\n \"\"\"\n Bootstraps a statistic and calculates the standard error of the statistic\n\n Args:\n ---------\n data : array or matrix\n array or matrix of data to calculate statistic and SE of statistic\n func : function\n statistical function to calculate on data\n examples: np.mean, np.median\n n_samples : int\n number of bootstrap samples to calculate statistic for\n parametric : (str) in ['normal', 'uniform']\n parametric distribution to resample from,\n If False, use nonparametric bootstrap sampling\n bias_correction : bool\n If True, bias correct bootstrap statistic\n bca : bool\n If true, use bias correction and (BCa) method to calculate bootstrap\n axis : int in [0, 1]\n if type(data) == np.matrix, axis to resample by\n if 0: resample rows\n if 1: resample columns\n\n Returns:\n ---------\n results : (float, float, float)\n The bootstrapped statistic, its bias and SEM.\n (statistic ,bias ,sem)\n \"\"\"\n plugin_estimate = func(data)\n statistics = []\n for sample in range(n_samples):\n if isinstance(data, np.matrix):\n resample = bootstrap_matrixsample(data, axis=axis)\n else:\n resample = bootstrap_sample(data, parametric=parametric)\n statistic = func(resample)\n statistics.append(statistic)\n statistic = np.mean(statistics)\n confidence_interval = calculate_ci(data, statistics, func=func, alpha=alpha, bca=bca)\n bias = statistic - plugin_estimate\n if bias_correction:\n statistic = statistic - bias\n sem = stats.sem(statistics)\n bootstrap_results = namedtuple('bootstrap_results', 'statistics statistic bias sem ci')\n results = bootstrap_results(statistics=statistics, statistic=statistic, bias=bias, sem=sem, ci=confidence_interval)\n return results", "context": "def bootstrap_statistic(data, func=np.mean, n_samples=50, parametric=False, bias_correction=False, alpha=0.05, bca=False, axis=0): ...\ndef bootstrap_sample(data, parametric=False): ...\ndef bootstrap_matrixsample(data, axis=0): ...\ndef jackknife_sample(data, index): ...\ndef bootstrap_statistic(data, func=np.mean, n_samples=50, parametric=False, bias_correction=False, alpha=0.05, bca=False, axis=0): ...\ndef jackknife_statistic(data, func=np.mean): ...\ndef calculate_ci(data, statistics, func=np.mean, alpha=0.05, bca=False): ...\ndef two_sample_testing(sampleA, sampleB, statistic_func=None, n_samples=50): ...\ndef compare_means(sampleA, sampleB): ...\ndef t_test_statistic(sampleA, sampleB): ...\n", "repository": "christopherjenness/bootstrap", "test_name": "testBootstrapBCa", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000635.py"} {"focal_file": "mt_crafting_recipe/helpers.py", "focal_class": null, "focal_method": "item_name", "tests": "import unittest\n\nclass Test_item_name(unittest.TestCase):\n def test_item_name(self):\n \"\"\"Item names should have initial colons stripped\"\"\"\n self.assertEqual(helpers.item_name('default:steel_ingot'), 'default:steel_ingot')\n self.assertEqual(helpers.item_name(':default:steel_ingot'), 'default:steel_ingot')\n self.assertEqual(helpers.item_name('default:coal 9'), 'default:coal')\n", "method_code": "def item_name(name):\n \"\"\"Item names may lead with colons. Drop 'em\"\"\"\n if name[0] == ':':\n name = name[1:]\n return name.split(' ')[0]", "context": "def item_name(name): ...\ndef item_name(name): ...\ndef group_name(name): ...\ndef map_recipe_collection(f, item): ...\ndef reduce_recipe_collection(f, item, initial): ...\ndef items_match(a, b): ...\n", "repository": "ptvirgo/mt_recipe_conflict_detector", "test_name": "test_item_name", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000636.py"} {"focal_file": "mt_crafting_recipe/helpers.py", "focal_class": null, "focal_method": "items_match", "tests": "import unittest\n\nclass Test_items_match(unittest.TestCase):\n def test_items_match(self):\n \"\"\"We should detect potential item conflicts\"\"\"\n woods = {'default:pine_wood', 'default:jungle_wood', 'default:wood'}\n metals = {'default:steel_ingot', 'default:bronze_ingot', 'default:gold_ingot'}\n everything = woods.union(metals)\n self.assertTrue(helpers.items_match('default:steel_ingot', 'default:steel_ingot'))\n self.assertFalse(helpers.items_match('default:steel_ingot', 'default:bronze_ingot'))\n self.assertTrue(helpers.items_match('default:steel_ingot', metals))\n self.assertTrue(helpers.items_match(metals, 'default:steel_ingot'))\n self.assertFalse(helpers.items_match('default:steel_ingot', woods))\n self.assertFalse(helpers.items_match(woods, 'default:steel_ingot'))\n self.assertTrue(helpers.items_match(woods, woods))\n self.assertFalse(helpers.items_match(metals, woods))\n self.assertFalse(helpers.items_match(everything, metals))\n", "method_code": "def items_match(a, b):\n \"\"\"Return True if the provided CraftItems match\"\"\"\n if type(a) is type(b):\n return a == b\n if type(a) is set:\n return items_match(b, a)\n if type(a) is str and type(b) is set:\n return a in b\n return False", "context": "def items_match(a, b): ...\ndef item_name(name): ...\ndef group_name(name): ...\ndef map_recipe_collection(f, item): ...\ndef reduce_recipe_collection(f, item, initial): ...\ndef items_match(a, b): ...\n", "repository": "ptvirgo/mt_recipe_conflict_detector", "test_name": "test_items_match", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000637.py"} {"focal_file": "qjira/headers.py", "focal_class": null, "focal_method": "get_column", "tests": "import unittest\n\nclass Test_get_column(unittest.TestCase):\n def test_get_column(self):\n self.assertTupleEqual(('project_key', 'Project'), qjira.headers.get_column('project_key'))\n", "method_code": "def get_column(key):\n \"\"\"Return tuple including column key and header\"\"\"\n return (key, get_column_header(key))", "context": "def get_column(key): ...\ndef get_column_header(key): ...\ndef get_column(key): ...\n", "repository": "andrew-hamlin-sp/jira_reporting_scripts", "test_name": "test_get_column", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000638.py"} {"focal_file": "qjira/jira.py", "focal_class": null, "focal_method": "get_browse_url", "tests": "import unittest\n\nclass Test_get_browse_url(unittest.TestCase):\n def test_get_browse_url(self):\n url = j.get_browse_url(TEST_BASE_URL, 'IIQETN-1')\n self.assertEqual('https://localhost:3000/browse/IIQETN-1', url)\n", "method_code": "def get_browse_url(baseUrl, issuekey):\n if not issuekey:\n raise ValueError\n return ISSUE_BROWSE.format(baseUrl, issuekey)", "context": "def get_browse_url(baseUrl, issuekey): ...\ndef _get_json(url, username=None, password=None, headers=HEADERS): ...\ndef _as_data(issue, reverse_sprints=False): ...\ndef default_fields(): ...\ndef get_browse_url(baseUrl, issuekey): ...\ndef get_issue(baseUrl, issuekey, username=None, password=None): ...\ndef all_issues(baseUrl, jql, username=None, password=None, progress_cb=None, reverse_sprints=False, fields=DEFAULT_FIELDS, expands=DEFAULT_EXPANDS): ...\n", "repository": "andrew-hamlin-sp/jira_reporting_scripts", "test_name": "test_get_browse_url", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000639.py"} {"focal_file": "qjira/jira.py", "focal_class": null, "focal_method": "get_issue", "tests": "import unittest\n\nclass Test_get_issue(unittest.TestCase):\n def test_get_issue(self):\n \"\"\"Test that getting a single issue urlencodes properly\"\"\"\n self.json_response = {'key': 123, 'fields': {}, 'changelog': []}\n expectedUrl = 'https://localhost:3000/rest/api/2/issue/IIQETN-1'\n j.get_issue(TEST_BASE_URL, 'IIQETN-1')\n self.assertUrlPartsEqual(expectedUrl, self.actual_url)\n", "method_code": "def get_issue(baseUrl, issuekey, username=None, password=None):\n url = ISSUE_ENDPOINT.format(baseUrl, issuekey)\n Log.debug('url = ' + url)\n return _as_data(_get_json(url, username=username, password=password))", "context": "def get_issue(baseUrl, issuekey, username=None, password=None): ...\ndef _get_json(url, username=None, password=None, headers=HEADERS): ...\ndef _as_data(issue, reverse_sprints=False): ...\ndef default_fields(): ...\ndef get_browse_url(baseUrl, issuekey): ...\ndef get_issue(baseUrl, issuekey, username=None, password=None): ...\ndef all_issues(baseUrl, jql, username=None, password=None, progress_cb=None, reverse_sprints=False, fields=DEFAULT_FIELDS, expands=DEFAULT_EXPANDS): ...\n", "repository": "andrew-hamlin-sp/jira_reporting_scripts", "test_name": "test_get_issue", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000640.py"} {"focal_file": "qjira/log.py", "focal_class": null, "focal_method": "error", "tests": "import unittest\n\nclass Test_error(unittest.TestCase):\n def test_error(self):\n with redirect_stderr(self.std_err):\n Log.error('hello')\n output = self.std_err.getvalue()\n self.assertEqual('[ERROR] hello\\n', output)\n", "method_code": " def error(msg):\n \"\"\"Log as an error\"\"\"\n Log.eprint('[ERROR] {}'.format(msg))\n ", "context": "class Log():\n @staticmethod\n def error(msg): ...\n def eprint(msg, *args, **kwargs): ...\n def isErrorEnabled(): ...\n def info(msg): ...\n def isInfoEnabled(): ...\n def debug(msg): ...\n def isDebugEnabled(): ...\n def verbose(msg): ...\n def isVerboseEnabled(): ...\n\n debugLevel = 0\n", "repository": "andrew-hamlin-sp/jira_reporting_scripts", "test_name": "test_error", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000641.py"} {"focal_file": "qjira/log.py", "focal_class": null, "focal_method": "info", "tests": "import unittest\n\nclass Test_info(unittest.TestCase):\n def test_info(self):\n Log.debugLevel = 1\n with redirect_stderr(self.std_err):\n Log.info('hello')\n self.assertEqual('[INFO] hello\\n', self.std_err.getvalue())\n", "method_code": " def info(msg):\n \"\"\"Log message when debug >= 0\"\"\"\n if Log.isInfoEnabled():\n Log.eprint('[INFO] {}'.format(msg))\n ", "context": "class Log():\n @staticmethod\n def info(msg): ...\n def eprint(msg, *args, **kwargs): ...\n def error(msg): ...\n def isErrorEnabled(): ...\n def isInfoEnabled(): ...\n def debug(msg): ...\n def isDebugEnabled(): ...\n def verbose(msg): ...\n def isVerboseEnabled(): ...\n\n debugLevel = 0\n", "repository": "andrew-hamlin-sp/jira_reporting_scripts", "test_name": "test_info", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000642.py"} {"focal_file": "qjira/log.py", "focal_class": null, "focal_method": "debug", "tests": "import unittest\n\nclass Test_debug(unittest.TestCase):\n def test_debug(self):\n Log.debugLevel = 2\n with redirect_stderr(self.std_err):\n Log.debug('hello')\n self.assertEqual('[DEBUG] hello\\n', self.std_err.getvalue())\n", "method_code": " def debug(msg):\n \"\"\"Log message when debug >= 1\"\"\"\n if Log.isDebugEnabled():\n Log.eprint('[DEBUG] {}'.format(msg))\n ", "context": "class Log():\n @staticmethod\n def debug(msg): ...\n def eprint(msg, *args, **kwargs): ...\n def error(msg): ...\n def isErrorEnabled(): ...\n def info(msg): ...\n def isInfoEnabled(): ...\n def isDebugEnabled(): ...\n def verbose(msg): ...\n def isVerboseEnabled(): ...\n\n debugLevel = 0\n", "repository": "andrew-hamlin-sp/jira_reporting_scripts", "test_name": "test_debug", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000643.py"} {"focal_file": "qjira/log.py", "focal_class": null, "focal_method": "verbose", "tests": "import unittest\n\nclass Test_verbose(unittest.TestCase):\n def test_verbose(self):\n Log.debugLevel = 3\n with redirect_stderr(self.std_err):\n Log.verbose('hello')\n self.assertEqual('[VERBOSE] hello\\n', self.std_err.getvalue())\n", "method_code": " def verbose(msg):\n \"\"\"Log message when debug >= 2\"\"\"\n if Log.isVerboseEnabled():\n Log.eprint('[VERBOSE] {}'.format(msg))\n ", "context": "class Log():\n @staticmethod\n def verbose(msg): ...\n def eprint(msg, *args, **kwargs): ...\n def error(msg): ...\n def isErrorEnabled(): ...\n def info(msg): ...\n def isInfoEnabled(): ...\n def debug(msg): ...\n def isDebugEnabled(): ...\n def isVerboseEnabled(): ...\n\n debugLevel = 0\n", "repository": "andrew-hamlin-sp/jira_reporting_scripts", "test_name": "test_verbose", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000644.py"} {"focal_file": "src/database/database.py", "focal_class": null, "focal_method": "query", "tests": "import unittest\n\nclass Test_query(unittest.TestCase):\n def test_query(self):\n query = self.database.query('INSERT INTO commands VALUES (%(name)s, %(command)s, %(server)s)')\n self.assertEqual('INSERT INTO commands VALUES (:name, :command, :server)', query)\n self.database.sql_type = SQLType.postgres\n query = self.database.query('INSERT INTO commands VALUES (%(name)s, %(command)s, %(server)s)')\n self.assertEqual('INSERT INTO commands VALUES (%(name)s, %(command)s, %(server)s)', query)\n", "method_code": " def query(self, query: str) -> str:\n if self.sql_type is SQLType.sqlite:\n query = self._convert(query)\n return query\n ", "context": "class Database():\n def query(self, query: str) -> str: ...\n def __init__(self, db_file=None, db_url=None, **kwargs): ...\n def __del__(self): ...\n def table(self, table: str): ...\n def create_table(self): ...\n def _convert(query: str) -> str: ...\n\n self.cursor = self.connection.cursor()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_query", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000645.py"} {"focal_file": "src/database/database.py", "focal_class": null, "focal_method": "table", "tests": "import unittest\n\nclass Test_table(unittest.TestCase):\n def test_table(self):\n table = self.database.table('commands')\n self.assertEqual('`commands`', table)\n self.database.sql_type = SQLType.postgres\n table = self.database.table('commands')\n self.assertEqual('\"commands\"', table)\n", "method_code": " def table(self, table: str):\n if self.sql_type is SQLType.sqlite:\n table = '`{0}`'.format(table)\n if self.sql_type is SQLType.postgres:\n table = '\"{0}\"'.format(table)\n return table\n ", "context": "class Database():\n def table(self, table: str): ...\n def __init__(self, db_file=None, db_url=None, **kwargs): ...\n def __del__(self): ...\n def query(self, query: str) -> str: ...\n def create_table(self): ...\n def _convert(query: str) -> str: ...\n\n self.cursor = self.connection.cursor()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_table", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000646.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_get(self):\n channel_id = self.channel_config.get('test')\n self.assertEqual(channel_id, '000000000000000000002')\n", "method_code": " def get(self, option):\n self.config.read(self.file)\n return self.config.get(self.section, option)\n ", "context": "class Config():\n def get(self, option): ...\n def __init__(self, file, section): ...\n def get_as_list(self, option): ...\n def get_all(self): ...\n def save(self, option, value): ...\n def append(self, option, value): ...\n def truncate(self, option, value): ...\n def delete(self, option): ...\n def has(self, option): ...\n def contains(self, option, search): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_get", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000647.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "get_as_list", "tests": "import unittest\n\nclass Test_get_as_list(unittest.TestCase):\n def test_get_as_list(self):\n users = self.ignore_config.get_as_list('list')\n user_list = ['user1', 'user2', 'user3', 'user4', 'user5', 'user6']\n self.assertListEqual(users, user_list)\n", "method_code": " def get_as_list(self, option):\n return self.get(option).split(',')\n ", "context": "class Config():\n def get_as_list(self, option): ...\n def __init__(self, file, section): ...\n def get(self, option): ...\n def get_all(self): ...\n def save(self, option, value): ...\n def append(self, option, value): ...\n def truncate(self, option, value): ...\n def delete(self, option): ...\n def has(self, option): ...\n def contains(self, option, search): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_get_as_list", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000648.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "get_all", "tests": "import unittest\n\nclass Test_get_all(unittest.TestCase):\n def test_get_all(self):\n channels = self.channel_config.get_all()\n channel_list = ['general', 'test', 'awesome', 'asdf', 'cool', 'voice']\n self.assertListEqual(channels, channel_list)\n", "method_code": " def get_all(self):\n self.config.read(self.file)\n return self.config.options(self.section)\n ", "context": "class Config():\n def get_all(self): ...\n def __init__(self, file, section): ...\n def get(self, option): ...\n def get_as_list(self, option): ...\n def save(self, option, value): ...\n def append(self, option, value): ...\n def truncate(self, option, value): ...\n def delete(self, option): ...\n def has(self, option): ...\n def contains(self, option, search): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_get_all", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000649.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "save", "tests": "import unittest\n\nclass Test_save(unittest.TestCase):\n def test_save(self):\n self.channel_config.save('newchannel', '111111111111111111')\n channel_id = self.channel_config.get('newchannel')\n self.assertEqual(channel_id, '111111111111111111')\n", "method_code": " def save(self, option, value):\n self.config.read(self.file)\n self.config.set(self.section, option, value)\n self._write()\n ", "context": "class Config():\n def save(self, option, value): ...\n def __init__(self, file, section): ...\n def get(self, option): ...\n def get_as_list(self, option): ...\n def get_all(self): ...\n def append(self, option, value): ...\n def truncate(self, option, value): ...\n def delete(self, option): ...\n def has(self, option): ...\n def contains(self, option, search): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_save", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000650.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "append", "tests": "import unittest\n\nclass Test_append(unittest.TestCase):\n def test_append(self):\n self.ignore_config.append('list', 'user9001')\n users = self.ignore_config.get('list')\n self.assertIn(',user9001', users)\n self.ignore_config.append('list', 'user9001')\n users = self.ignore_config.get('list')\n self.assertIn(',user9001', users)\n self.ignore_config.append('list2', 'user9001')\n users = self.ignore_config.get('list2')\n self.assertIn('user9001', users)\n self.ignore_config.append('list3', 'user9001')\n users = self.ignore_config.get('list3')\n self.assertIn('user9001', users)\n", "method_code": " def append(self, option, value):\n try:\n current_val = self.get(option)\n except configparser.NoOptionError:\n self.save(option, value)\n return\n if current_val is None or current_val == '':\n self.save(option, value)\n return\n if value in current_val.split(','):\n return\n value = current_val + ',' + value\n self.save(option, value)\n ", "context": "class Config():\n def append(self, option, value): ...\n def __init__(self, file, section): ...\n def get(self, option): ...\n def get_as_list(self, option): ...\n def get_all(self): ...\n def save(self, option, value): ...\n def truncate(self, option, value): ...\n def delete(self, option): ...\n def has(self, option): ...\n def contains(self, option, search): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_append", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000651.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "truncate", "tests": "import unittest\n\nclass Test_truncate(unittest.TestCase):\n def test_truncate(self):\n self.ignore_config.truncate('list2', 'user3')\n does_have = self.ignore_config.has('list2')\n self.assertFalse(does_have)\n for x in range(0, 6):\n user = 'user{}'.format(x)\n self.ignore_config.truncate('list', user)\n users = self.ignore_config.get('list')\n self.assertNotIn(user, users, 'Running ' + user)\n self.ignore_config.truncate('list', 'user6')\n with self.assertRaises(configparser.NoOptionError):\n self.ignore_config.get('list')\n", "method_code": " def truncate(self, option, value):\n try:\n current_val = self.get(option)\n except configparser.NoOptionError:\n return\n if ',' in current_val:\n values = current_val.split(',')\n if value in values:\n values.remove(value)\n self.save(option, ','.join(values))\n else:\n self.delete(option)\n ", "context": "class Config():\n def truncate(self, option, value): ...\n def __init__(self, file, section): ...\n def get(self, option): ...\n def get_as_list(self, option): ...\n def get_all(self): ...\n def save(self, option, value): ...\n def append(self, option, value): ...\n def delete(self, option): ...\n def has(self, option): ...\n def contains(self, option, search): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_truncate", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000652.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "delete", "tests": "import unittest\n\nclass Test_delete(unittest.TestCase):\n def test_delete(self):\n self.channel_config.delete('asdf')\n channels = self.channel_config.get_all()\n self.assertNotIn('asdf', channels)\n", "method_code": " def delete(self, option):\n self.config.read(self.file)\n deleted = self.config.remove_option(self.section, option)\n self._write()\n return deleted\n ", "context": "class Config():\n def delete(self, option): ...\n def __init__(self, file, section): ...\n def get(self, option): ...\n def get_as_list(self, option): ...\n def get_all(self): ...\n def save(self, option, value): ...\n def append(self, option, value): ...\n def truncate(self, option, value): ...\n def has(self, option): ...\n def contains(self, option, search): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_delete", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000653.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "has", "tests": "import unittest\n\nclass Test_has(unittest.TestCase):\n def test_has(self):\n does_contain = self.channel_config.has('awesome')\n self.assertTrue(does_contain)\n", "method_code": " def has(self, option):\n self.config.read(self.file)\n return self.config.has_option(self.section, option)\n ", "context": "class Config():\n def has(self, option): ...\n def __init__(self, file, section): ...\n def get(self, option): ...\n def get_as_list(self, option): ...\n def get_all(self): ...\n def save(self, option, value): ...\n def append(self, option, value): ...\n def truncate(self, option, value): ...\n def delete(self, option): ...\n def contains(self, option, search): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_has", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000654.py"} {"focal_file": "src/utils/config.py", "focal_class": null, "focal_method": "contains", "tests": "import unittest\n\nclass Test_contains(unittest.TestCase):\n def test_contains(self):\n does_contain = self.ignore_config.contains('list', 'user5')\n self.assertTrue(does_contain)\n does_contain = self.ignore_config.contains('list2', 'user5')\n self.assertFalse(does_contain)\n does_contain = self.ignore_config.contains('list3', 'user5')\n self.assertFalse(does_contain)\n does_contain = self.ignore_config.contains('list4', 'user10')\n self.assertTrue(does_contain)\n does_contain = self.ignore_config.contains('list4', 'user5')\n self.assertFalse(does_contain)\n", "method_code": " def contains(self, option, search):\n try:\n val = self.get(option)\n if val is None or val == '':\n return False\n if search in val.split(','):\n return True\n else:\n return False\n except configparser.NoOptionError:\n return False\n ", "context": "class Config():\n def contains(self, option, search): ...\n def __init__(self, file, section): ...\n def get(self, option): ...\n def get_as_list(self, option): ...\n def get_all(self): ...\n def save(self, option, value): ...\n def append(self, option, value): ...\n def truncate(self, option, value): ...\n def delete(self, option): ...\n def has(self, option): ...\n def _write(self): ...\n\n self.file = file\n self.section = section\n self.config = MyConfigParser()\n", "repository": "00firestar00/TnyBot-Discord", "test_name": "test_contains", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000655.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "generate_confirmation_token", "tests": "import unittest\n\nclass Test_User_generate_confirmation_token(unittest.TestCase):\n def test_valid_confirmation_token(self):\n u = User(password='cat')\n db.session.add(u)\n db.session.commit()\n token = u.generate_confirmation_token()\n self.assertTrue(u.confirm(token))\n\n def test_invalid_confirmation_token(self):\n u1 = User(password='cat')\n u2 = User(password='dog')\n db.session.add(u1)\n db.session.add(u2)\n db.session.commit()\n token = u1.generate_confirmation_token()\n self.assertFalse(u2.confirm(token))\n\n def test_expired_confirmation_token(self):\n u = User(password='cat')\n db.session.add(u)\n db.session.commit()\n token = u.generate_confirmation_token(1)\n time.sleep(2)\n self.assertFalse(u.confirm(token))\n", "method_code": " def generate_confirmation_token(self, expiration=3600):\n s = Serializer(current_app.config['SECRET_KEY'], expiration)\n return s.dumps({'confirm': self.id})\n ", "context": "class User(UserMixindb.Model):\n def generate_confirmation_token(self, expiration=3600): ...\n def generate_fake(count=100): ...\n def add_self_follows(): ...\n def __init__(self, **kwargs): ...\n def password(self): ...\n def password(self, password): ...\n def verify_password(self, password): ...\n def confirm(self, token): ...\n def generate_reset_token(self, expiration=3600): ...\n def reset_password(self, token, new_password): ...\n def generate_email_change_token(self, new_email, expiration=3600): ...\n def change_email(self, token): ...\n def can(self, permissions): ...\n def is_administrator(self): ...\n def ping(self): ...\n def gravatar(self, size=100, default='identicon', rating='g'): ...\n def follow(self, user): ...\n def unfollow(self, user): ...\n def is_following(self, user): ...\n def is_followed_by(self, user): ...\n def followed_posts(self): ...\n def to_json(self): ...\n def generate_auth_token(self, expiration): ...\n def verify_auth_token(token): ...\n def __repr__(self): ...\n\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(64), unique=True, index=True)\n username = db.Column(db.String(64), unique=True, index=True)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\n password_hash = db.Column(db.String(128))\n confirmed = db.Column(db.Boolean, default=False)\n name = db.Column(db.String(64))\n location = db.Column(db.String(64))\n about_me = db.Column(db.Text())\n member_since = db.Column(db.DateTime(), default=datetime.utcnow)\n last_seen = db.Column(db.DateTime(), default=datetime.utcnow)\n avatar_hash = db.Column(db.String(32))\n posts = db.relationship('Post', backref='author', lazy='dynamic')\n followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n comments = db.relationship('Comment', backref='author', lazy='dynamic')\n", "repository": "twmw/flask-web-dev", "test_name": "test_valid_confirmation_token", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000656.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "generate_reset_token", "tests": "import unittest\n\nclass Test_User_generate_reset_token(unittest.TestCase):\n def test_valid_reset_token(self):\n u = User(password='cat')\n db.session.add(u)\n db.session.commit()\n token = u.generate_reset_token()\n self.assertTrue(u.reset_password(token, 'dog'))\n self.assertTrue(u.verify_password('dog'))\n\n def test_invalid_reset_token(self):\n u1 = User(password='cat')\n u2 = User(password='dog')\n db.session.add(u1)\n db.session.add(u2)\n db.session.commit()\n token = u1.generate_reset_token()\n self.assertFalse(u2.reset_password(token, 'horse'))\n self.assertTrue(u2.verify_password('dog'))\n", "method_code": " def generate_reset_token(self, expiration=3600):\n s = Serializer(current_app.config['SECRET_KEY'], expiration)\n return s.dumps({'reset': self.id})\n ", "context": "class User(UserMixindb.Model):\n def generate_reset_token(self, expiration=3600): ...\n def generate_fake(count=100): ...\n def add_self_follows(): ...\n def __init__(self, **kwargs): ...\n def password(self): ...\n def password(self, password): ...\n def verify_password(self, password): ...\n def generate_confirmation_token(self, expiration=3600): ...\n def confirm(self, token): ...\n def reset_password(self, token, new_password): ...\n def generate_email_change_token(self, new_email, expiration=3600): ...\n def change_email(self, token): ...\n def can(self, permissions): ...\n def is_administrator(self): ...\n def ping(self): ...\n def gravatar(self, size=100, default='identicon', rating='g'): ...\n def follow(self, user): ...\n def unfollow(self, user): ...\n def is_following(self, user): ...\n def is_followed_by(self, user): ...\n def followed_posts(self): ...\n def to_json(self): ...\n def generate_auth_token(self, expiration): ...\n def verify_auth_token(token): ...\n def __repr__(self): ...\n\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(64), unique=True, index=True)\n username = db.Column(db.String(64), unique=True, index=True)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\n password_hash = db.Column(db.String(128))\n confirmed = db.Column(db.Boolean, default=False)\n name = db.Column(db.String(64))\n location = db.Column(db.String(64))\n about_me = db.Column(db.Text())\n member_since = db.Column(db.DateTime(), default=datetime.utcnow)\n last_seen = db.Column(db.DateTime(), default=datetime.utcnow)\n avatar_hash = db.Column(db.String(32))\n posts = db.relationship('Post', backref='author', lazy='dynamic')\n followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n comments = db.relationship('Comment', backref='author', lazy='dynamic')\n", "repository": "twmw/flask-web-dev", "test_name": "test_valid_reset_token", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000657.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "generate_email_change_token", "tests": "import unittest\n\nclass Test_User_generate_email_change_token(unittest.TestCase):\n def test_valid_email_change_token(self):\n u = User(email='john@example.com', password='cat')\n db.session.add(u)\n db.session.commit()\n token = u.generate_email_change_token('susan@example.org')\n self.assertTrue(u.change_email(token))\n self.assertTrue(u.email == 'susan@example.org')\n\n def test_invalid_email_change_token(self):\n u1 = User(email='john@example.com', password='cat')\n u2 = User(email='susan@example.org', password='dog')\n db.session.add(u1)\n db.session.add(u2)\n db.session.commit()\n token = u1.generate_email_change_token('david@example.net')\n self.assertFalse(u2.change_email(token))\n self.assertTrue(u2.email == 'susan@example.org')\n\n def test_duplicate_email_change_token(self):\n u1 = User(email='john@example.com', password='cat')\n u2 = User(email='susan@example.org', password='dog')\n db.session.add(u1)\n db.session.add(u2)\n db.session.commit()\n token = u2.generate_email_change_token('john@example.com')\n self.assertFalse(u2.change_email(token))\n self.assertTrue(u2.email == 'susan@example.org')\n", "method_code": " def generate_email_change_token(self, new_email, expiration=3600):\n s = Serializer(current_app.config['SECRET_KEY'], expiration)\n return s.dumps({'change_email': self.id, 'new_email': new_email})\n ", "context": "class User(UserMixindb.Model):\n def generate_email_change_token(self, new_email, expiration=3600): ...\n def generate_fake(count=100): ...\n def add_self_follows(): ...\n def __init__(self, **kwargs): ...\n def password(self): ...\n def password(self, password): ...\n def verify_password(self, password): ...\n def generate_confirmation_token(self, expiration=3600): ...\n def confirm(self, token): ...\n def generate_reset_token(self, expiration=3600): ...\n def reset_password(self, token, new_password): ...\n def change_email(self, token): ...\n def can(self, permissions): ...\n def is_administrator(self): ...\n def ping(self): ...\n def gravatar(self, size=100, default='identicon', rating='g'): ...\n def follow(self, user): ...\n def unfollow(self, user): ...\n def is_following(self, user): ...\n def is_followed_by(self, user): ...\n def followed_posts(self): ...\n def to_json(self): ...\n def generate_auth_token(self, expiration): ...\n def verify_auth_token(token): ...\n def __repr__(self): ...\n\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(64), unique=True, index=True)\n username = db.Column(db.String(64), unique=True, index=True)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\n password_hash = db.Column(db.String(128))\n confirmed = db.Column(db.Boolean, default=False)\n name = db.Column(db.String(64))\n location = db.Column(db.String(64))\n about_me = db.Column(db.Text())\n member_since = db.Column(db.DateTime(), default=datetime.utcnow)\n last_seen = db.Column(db.DateTime(), default=datetime.utcnow)\n avatar_hash = db.Column(db.String(32))\n posts = db.relationship('Post', backref='author', lazy='dynamic')\n followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n comments = db.relationship('Comment', backref='author', lazy='dynamic')\n", "repository": "twmw/flask-web-dev", "test_name": "test_valid_email_change_token", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000658.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "ping", "tests": "import unittest\n\nclass Test_User_ping(unittest.TestCase):\n def test_ping(self):\n u = User(password='cat')\n db.session.add(u)\n db.session.commit()\n time.sleep(2)\n last_seen_before = u.last_seen\n u.ping()\n self.assertTrue(u.last_seen > last_seen_before)\n", "method_code": " def ping(self):\n self.last_seen = datetime.utcnow()\n db.session.add(self)\n ", "context": "class User(UserMixindb.Model):\n def ping(self): ...\n def generate_fake(count=100): ...\n def add_self_follows(): ...\n def __init__(self, **kwargs): ...\n def password(self): ...\n def password(self, password): ...\n def verify_password(self, password): ...\n def generate_confirmation_token(self, expiration=3600): ...\n def confirm(self, token): ...\n def generate_reset_token(self, expiration=3600): ...\n def reset_password(self, token, new_password): ...\n def generate_email_change_token(self, new_email, expiration=3600): ...\n def change_email(self, token): ...\n def can(self, permissions): ...\n def is_administrator(self): ...\n def gravatar(self, size=100, default='identicon', rating='g'): ...\n def follow(self, user): ...\n def unfollow(self, user): ...\n def is_following(self, user): ...\n def is_followed_by(self, user): ...\n def followed_posts(self): ...\n def to_json(self): ...\n def generate_auth_token(self, expiration): ...\n def verify_auth_token(token): ...\n def __repr__(self): ...\n\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(64), unique=True, index=True)\n username = db.Column(db.String(64), unique=True, index=True)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\n password_hash = db.Column(db.String(128))\n confirmed = db.Column(db.Boolean, default=False)\n name = db.Column(db.String(64))\n location = db.Column(db.String(64))\n about_me = db.Column(db.Text())\n member_since = db.Column(db.DateTime(), default=datetime.utcnow)\n last_seen = db.Column(db.DateTime(), default=datetime.utcnow)\n avatar_hash = db.Column(db.String(32))\n posts = db.relationship('Post', backref='author', lazy='dynamic')\n followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n comments = db.relationship('Comment', backref='author', lazy='dynamic')\n", "repository": "twmw/flask-web-dev", "test_name": "test_ping", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000659.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "gravatar", "tests": "import unittest\n\nclass Test_User_gravatar(unittest.TestCase):\n def test_gravatar(self):\n u = User(email='john@example.com', password='cat')\n with self.app.test_request_context('/'):\n gravatar = u.gravatar()\n gravatar_256 = u.gravatar(size=256)\n gravatar_pg = u.gravatar(rating='pg')\n gravatar_retro = u.gravatar(default='retro')\n with self.app.test_request_context('/', base_url='https://example.com'):\n gravatar_ssl = u.gravatar()\n self.assertTrue('http://www.gravatar.com/avatar/' + 'd4c74594d841139328695756648b6bd6' in gravatar)\n self.assertTrue('s=256' in gravatar_256)\n self.assertTrue('r=pg' in gravatar_pg)\n self.assertTrue('d=retro' in gravatar_retro)\n self.assertTrue('https://secure.gravatar.com/avatar/' + 'd4c74594d841139328695756648b6bd6' in gravatar_ssl)\n", "method_code": " def gravatar(self, size=100, default='identicon', rating='g'):\n if request.is_secure:\n url = 'https://secure.gravatar.com/avatar'\n else:\n url = 'http://www.gravatar.com/avatar'\n hash = self.avatar_hash or hashlib.md5(self.email.encode('utf-8')).hexdigest()\n return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(url=url, hash=hash, size=size, default=default, rating=rating)\n ", "context": "class User(UserMixindb.Model):\n def gravatar(self, size=100, default='identicon', rating='g'): ...\n def generate_fake(count=100): ...\n def add_self_follows(): ...\n def __init__(self, **kwargs): ...\n def password(self): ...\n def password(self, password): ...\n def verify_password(self, password): ...\n def generate_confirmation_token(self, expiration=3600): ...\n def confirm(self, token): ...\n def generate_reset_token(self, expiration=3600): ...\n def reset_password(self, token, new_password): ...\n def generate_email_change_token(self, new_email, expiration=3600): ...\n def change_email(self, token): ...\n def can(self, permissions): ...\n def is_administrator(self): ...\n def ping(self): ...\n def follow(self, user): ...\n def unfollow(self, user): ...\n def is_following(self, user): ...\n def is_followed_by(self, user): ...\n def followed_posts(self): ...\n def to_json(self): ...\n def generate_auth_token(self, expiration): ...\n def verify_auth_token(token): ...\n def __repr__(self): ...\n\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(64), unique=True, index=True)\n username = db.Column(db.String(64), unique=True, index=True)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\n password_hash = db.Column(db.String(128))\n confirmed = db.Column(db.Boolean, default=False)\n name = db.Column(db.String(64))\n location = db.Column(db.String(64))\n about_me = db.Column(db.Text())\n member_since = db.Column(db.DateTime(), default=datetime.utcnow)\n last_seen = db.Column(db.DateTime(), default=datetime.utcnow)\n avatar_hash = db.Column(db.String(32))\n posts = db.relationship('Post', backref='author', lazy='dynamic')\n followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n comments = db.relationship('Comment', backref='author', lazy='dynamic')\n", "repository": "twmw/flask-web-dev", "test_name": "test_gravatar", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000660.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "is_following", "tests": "import unittest\n\nclass Test_User_is_following(unittest.TestCase):\n def test_follows(self):\n u1 = User(email='john@example.com', password='cat')\n u2 = User(email='susan@example.org', password='dog')\n db.session.add(u1)\n db.session.add(u2)\n db.session.commit()\n self.assertFalse(u1.is_following(u2))\n self.assertFalse(u1.is_followed_by(u2))\n timestamp_before = datetime.utcnow()\n u1.follow(u2)\n db.session.add(u1)\n db.session.commit()\n timestamp_after = datetime.utcnow()\n self.assertTrue(u1.is_following(u2))\n self.assertFalse(u1.is_followed_by(u2))\n self.assertTrue(u2.is_followed_by(u1))\n self.assertTrue(u1.followed.count() == 2)\n self.assertTrue(u2.followers.count() == 2)\n f = u1.followed.all()[-1]\n self.assertTrue(f.followed == u2)\n self.assertTrue(timestamp_before <= f.timestamp <= timestamp_after)\n f = u2.followers.all()[-1]\n self.assertTrue(f.follower == u1)\n u1.unfollow(u2)\n db.session.add(u1)\n db.session.commit()\n self.assertTrue(u1.followed.count() == 1)\n self.assertTrue(u2.followers.count() == 1)\n self.assertTrue(Follow.query.count() == 2)\n u2.follow(u1)\n db.session.add(u1)\n db.session.add(u2)\n db.session.commit()\n db.session.delete(u2)\n db.session.commit()\n self.assertTrue(Follow.query.count() == 1)\n", "method_code": " def is_following(self, user):\n return self.followed.filter_by(followed_id=user.id).first() is not None\n ", "context": "class User(UserMixindb.Model):\n def is_following(self, user): ...\n def generate_fake(count=100): ...\n def add_self_follows(): ...\n def __init__(self, **kwargs): ...\n def password(self): ...\n def password(self, password): ...\n def verify_password(self, password): ...\n def generate_confirmation_token(self, expiration=3600): ...\n def confirm(self, token): ...\n def generate_reset_token(self, expiration=3600): ...\n def reset_password(self, token, new_password): ...\n def generate_email_change_token(self, new_email, expiration=3600): ...\n def change_email(self, token): ...\n def can(self, permissions): ...\n def is_administrator(self): ...\n def ping(self): ...\n def gravatar(self, size=100, default='identicon', rating='g'): ...\n def follow(self, user): ...\n def unfollow(self, user): ...\n def is_followed_by(self, user): ...\n def followed_posts(self): ...\n def to_json(self): ...\n def generate_auth_token(self, expiration): ...\n def verify_auth_token(token): ...\n def __repr__(self): ...\n\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(64), unique=True, index=True)\n username = db.Column(db.String(64), unique=True, index=True)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\n password_hash = db.Column(db.String(128))\n confirmed = db.Column(db.Boolean, default=False)\n name = db.Column(db.String(64))\n location = db.Column(db.String(64))\n about_me = db.Column(db.Text())\n member_since = db.Column(db.DateTime(), default=datetime.utcnow)\n last_seen = db.Column(db.DateTime(), default=datetime.utcnow)\n avatar_hash = db.Column(db.String(32))\n posts = db.relationship('Post', backref='author', lazy='dynamic')\n followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')\n comments = db.relationship('Comment', backref='author', lazy='dynamic')\n", "repository": "twmw/flask-web-dev", "test_name": "test_follows", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000661.py"} {"focal_file": "app/lib/protorpc/webapp/service_handlers_test.py", "focal_class": null, "focal_method": "ResetRequestHandler", "tests": "import unittest\n\nclass Test_ResetRequestHandler(unittest.TestCase):\n def testRequestState(self):\n \"\"\"Make sure request state is passed in to handler that supports it.\"\"\"\n\n class ServiceWithState(object):\n initialize_request_state = self.mox.CreateMockAnything()\n\n @remote.method(Request1, Response1)\n def method1(self, request):\n return Response1()\n self.service_factory = ServiceWithState\n self.ResetRequestHandler()\n self.rpc_mapper1.build_request(self.handler, Request1).AndReturn(Request1())\n\n def build_response(handler, response):\n handler.response.headers['Content-Type'] = 'application/x-www-form-urlencoded'\n handler.response.out.write('whatever')\n self.rpc_mapper1.build_response(self.handler, mox.IsA(Response1)).WithSideEffects(build_response)\n\n def verify_state(state):\n return 'remote.host.com' == state.remote_host and '127.0.0.1' == state.remote_address and ('server.host.com' == state.server_host) and (8080 == state.server_port) and ('POST' == state.http_method) and ('/my_service' == state.service_path) and ('application/x-www-form-urlencoded' == state.headers['content-type']) and ('dev_appserver_login=\"test:test@example.com:True\"' == state.headers['cookie'])\n ServiceWithState.initialize_request_state(mox.Func(verify_state))\n self.mox.ReplayAll()\n self.handler.handle('POST', '/my_service', 'method1')\n self.VerifyResponse('200', 'OK', 'whatever')\n self.mox.VerifyAll()\n", "method_code": " def ResetRequestHandler(self):\n super(ServiceHandlerTest, self).setUp()\n ", "context": "class ServiceHandlerTest(webapp_test_util.RequestHandlerTestBase):\n def ResetRequestHandler(self): ...\n def setUp(self): ...\n def CreateService(self): ...\n def CreateRequestHandler(self): ...\n def GetEnvironment(self): ...\n def VerifyResponse(self, *args, **kwargs): ...\n def ExpectRpcError(self, mapper, state, error_message, error_name=None): ...\n def testRedirect(self): ...\n def testFirstMapper(self): ...\n def testSecondMapper(self): ...\n def testCaseInsensitiveContentType(self): ...\n def testContentTypeWithParameters(self): ...\n def testContentFromHeaderOnly(self): ...\n def testRequestState(self): ...\n def testRequestState_MissingHosts(self): ...\n def testNoMatch_UnknownHTTPMethod(self): ...\n def testNoMatch_GetNotSupported(self): ...\n def testNoMatch_UnknownContentType(self): ...\n def testNoMatch_NoContentType(self): ...\n def testNoSuchMethod(self): ...\n def testNoSuchRemoteMethod(self): ...\n def testRequestError(self): ...\n def testDecodeError(self): ...\n def testResponseException(self): ...\n def testGet(self): ...\n def testPost(self): ...\n def testGetNoMethod(self): ...\n def testGetNotSupported(self): ...\n def testGetUnknownContentType(self): ...\n", "repository": "openfire/openfire_old", "test_name": "testRequestState", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000662.py"} {"focal_file": "app/lib/protorpc/webapp/service_handlers_test.py", "focal_class": null, "focal_method": "ExpectRpcError", "tests": "import unittest\n\nclass Test_ExpectRpcError(unittest.TestCase):\n def testRequestError(self):\n \"\"\"RequestError handling.\"\"\"\n\n def build_request(handler, request):\n raise service_handlers.RequestError('This is a request error')\n self.rpc_mapper1.build_request(self.handler, Request1).WithSideEffects(build_request)\n self.ExpectRpcError(self.rpc_mapper1, remote.RpcState.REQUEST_ERROR, 'Error parsing ProtoRPC request (This is a request error)')\n self.mox.ReplayAll()\n self.handler.handle('POST', '/my_service', 'method1')\n self.VerifyResponse('400', 'Error parsing ProtoRPC request (This is a request error)', '')\n self.mox.VerifyAll()\n", "method_code": " def ExpectRpcError(self, mapper, state, error_message, error_name=None):\n mapper.build_response(self.handler, remote.RpcStatus(state=state, error_message=error_message, error_name=error_name))\n ", "context": "class ServiceHandlerTest(webapp_test_util.RequestHandlerTestBase):\n def ExpectRpcError(self, mapper, state, error_message, error_name=None): ...\n def setUp(self): ...\n def ResetRequestHandler(self): ...\n def CreateService(self): ...\n def CreateRequestHandler(self): ...\n def GetEnvironment(self): ...\n def VerifyResponse(self, *args, **kwargs): ...\n def testRedirect(self): ...\n def testFirstMapper(self): ...\n def testSecondMapper(self): ...\n def testCaseInsensitiveContentType(self): ...\n def testContentTypeWithParameters(self): ...\n def testContentFromHeaderOnly(self): ...\n def testRequestState(self): ...\n def testRequestState_MissingHosts(self): ...\n def testNoMatch_UnknownHTTPMethod(self): ...\n def testNoMatch_GetNotSupported(self): ...\n def testNoMatch_UnknownContentType(self): ...\n def testNoMatch_NoContentType(self): ...\n def testNoSuchMethod(self): ...\n def testNoSuchRemoteMethod(self): ...\n def testRequestError(self): ...\n def testDecodeError(self): ...\n def testResponseException(self): ...\n def testGet(self): ...\n def testPost(self): ...\n def testGetNoMethod(self): ...\n def testGetNotSupported(self): ...\n def testGetUnknownContentType(self): ...\n", "repository": "openfire/openfire_old", "test_name": "testRequestError", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000663.py"} {"focal_file": "app/lib/protorpc/webapp/service_handlers_test.py", "focal_class": null, "focal_method": "DoMappingTest", "tests": "import unittest\n\nclass Test_DoMappingTest(unittest.TestCase):\n def testServiceMapping_ByList(self):\n \"\"\"Test mapping a service by factory.\"\"\"\n self.DoMappingTest([('/my-service1', MyService.new_factory('service1')), ('/my-service2', MyService.new_factory('service2'))])\n\n def testServiceMapping_NoRegistry(self):\n \"\"\"Test mapping a service by class.\"\"\"\n mapping = self.DoMappingTest({'/my-service': MyService}, None)\n", "method_code": " def DoMappingTest(self, services, registry_path='/myreg', expected_paths=None):\n mapped_services = mapping = service_handlers.service_mapping(services, registry_path)\n if registry_path:\n form_mapping = mapping[:2]\n mapped_registry_path, mapped_registry_factory = mapping[-1]\n mapped_services = mapping[2:-1]\n self.CheckFormMappings(form_mapping, registry_path=registry_path)\n self.assertEquals('(%s)%s' % (registry_path, service_handlers._METHOD_PATTERN), mapped_registry_path)\n self.assertEquals(registry.RegistryService, mapped_registry_factory.service_factory.service_class)\n expected_registry = {registry_path: registry.RegistryService}\n for path, factory in dict(services).iteritems():\n if isinstance(factory, type) and issubclass(factory, remote.Service):\n expected_registry[path] = factory\n else:\n expected_registry[path] = factory.service_class\n self.assertEquals(expected_registry, mapped_registry_factory().service.registry)\n self.assertEquals(len(services), len(mapped_services))\n for path, service in dict(services).iteritems():\n mapped_path = '(%s)%s' % (path, service_handlers._METHOD_PATTERN)\n mapped_factory = dict(mapped_services)[mapped_path]\n self.assertEquals(service, mapped_factory.service_factory)\n ", "context": "class ServiceMappingTest(test_util.TestCase):\n def DoMappingTest(self, services, registry_path='/myreg', expected_paths=None): ...\n def CheckFormMappings(self, mapping, registry_path='/protorpc'): ...\n def testServiceMapping_Empty(self): ...\n def testServiceMapping_ByClass(self): ...\n def testServiceMapping_ByFactory(self): ...\n def testServiceMapping_ByList(self): ...\n def testServiceMapping_NoRegistry(self): ...\n def testDefaultMappingWithClass(self): ...\n def testDefaultMappingWithFactory(self): ...\n def testMappingDuplicateExplicitServiceName(self): ...\n def testMappingDuplicateServiceName(self): ...\n", "repository": "openfire/openfire_old", "test_name": "testServiceMapping_ByList", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000664.py"} {"focal_file": "app/lib/protorpc/webapp/service_handlers_test.py", "focal_class": null, "focal_method": "DoRequest", "tests": "import unittest\n\nclass Test_DoRequest(unittest.TestCase):\n def testRequest(self):\n request = Request1(string_field='request value')\n status, response = self.DoRequest('/my_service.my_method', request, Response1)\n self.assertEquals('Status: 200 OK', status)\n self.assertEquals(request, self.request)\n self.assertEquals(Response1(string_field='a response'), response)\n", "method_code": " def DoRequest(self, path, request, response_type, reg_path='/protorpc'):\n stdin = sys.stdin\n stdout = sys.stdout\n environ = os.environ\n try:\n sys.stdin = cStringIO.StringIO(protojson.encode_message(request))\n sys.stdout = cStringIO.StringIO()\n os.environ = webapp_test_util.GetDefaultEnvironment()\n os.environ['PATH_INFO'] = path\n os.environ['REQUEST_METHOD'] = 'POST'\n os.environ['CONTENT_TYPE'] = 'application/json'\n os.environ['wsgi.input'] = sys.stdin\n os.environ['wsgi.output'] = sys.stdout\n os.environ['CONTENT_LENGTH'] = len(sys.stdin.getvalue())\n service_handlers.run_services([('/my_service', GetCalled.new_factory(self))], reg_path)\n header, body = sys.stdout.getvalue().split('\\n\\n', 1)\n return (header.split('\\n')[0], protojson.decode_message(response_type, body))\n finally:\n sys.stdin = stdin\n sys.stdout = stdout\n os.environ = environ\n ", "context": "class TestRunServices(test_util.TestCase):\n def DoRequest(self, path, request, response_type, reg_path='/protorpc'): ...\n def testRequest(self): ...\n def testRegistry(self): ...\n def testRunServicesWithOutRegistry(self): ...\n", "repository": "openfire/openfire_old", "test_name": "testRequest", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000665.py"} {"focal_file": "neckbeard/loader.py", "focal_class": null, "focal_method": "_validate_node_template_agreement", "tests": "import unittest\n\nclass Test_validate_node_template_agreement(unittest.TestCase):\n def test_node_template_name_mismatch(self):\n loader = self._get_loader_for_fixture('minimal')\n loader.validation_errors = {}\n raw_configuration = {'node_templates': {'ec2': {'wrong_name': {'node_template_name': 'mismatch', 'node_aws_type': 'ec2'}, 'both_wrong': {'node_template_name': 'mismatch', 'node_aws_type': 'mismatch'}, 'correct': {'node_template_name': 'correct', 'node_aws_type': 'ec2'}}, 'foo': {'correct': {'node_template_name': 'correct', 'node_aws_type': 'foo'}, 'both_wrong': {'node_template_name': 'mismatch', 'node_aws_type': 'mismatch'}}}}\n loader._validate_node_template_agreement(raw_configuration)\n validation_errors = self._get_validation_errors(loader, 'node_templates/ec2/wrong_name.json', 'file_option_mismatch')\n self.assertEqual(len(validation_errors), 1)\n validation_errors = self._get_validation_errors(loader, 'node_templates/ec2/both_wrong.json', 'file_option_mismatch')\n self.assertEqual(len(validation_errors), 2)\n validation_errors = self._get_validation_errors(loader, 'node_templates/ec2/correct.json')\n self.assertEqual(len(validation_errors), 0)\n validation_errors = self._get_validation_errors(loader, 'node_templates/foo/both_wrong.json', 'file_option_mismatch')\n self.assertEqual(len(validation_errors), 2)\n validation_errors = self._get_validation_errors(loader, 'node_templates/foo/correct.json', 'file_option_mismatch')\n self.assertEqual(len(validation_errors), 0)\n\n def test_node_template_required_options(self):\n loader = self._get_loader_for_fixture('minimal')\n loader.validation_errors = {}\n raw_configuration = {'node_templates': {'ec2': {'missing_type': {'node_template_name': 'missing_type'}, 'missing_name': {'node_aws_type': 'ec2'}, 'missing': {}, 'correct': {'node_template_name': 'correct', 'node_aws_type': 'ec2'}}, 'foo': {'correct': {'node_template_name': 'correct', 'node_aws_type': 'foo'}, 'missing': {}}}}\n loader._validate_node_template_agreement(raw_configuration)\n validation_errors = self._get_validation_errors(loader, 'node_templates/ec2/missing_type.json', 'missing_option')\n self.assertEqual(len(validation_errors), 1)\n validation_errors = self._get_validation_errors(loader, 'node_templates/ec2/missing_name.json', 'missing_option')\n self.assertEqual(len(validation_errors), 1)\n validation_errors = self._get_validation_errors(loader, 'node_templates/ec2/missing.json', 'missing_option')\n self.assertEqual(len(validation_errors), 2)\n validation_errors = self._get_validation_errors(loader, 'node_templates/ec2/correct.json')\n self.assertEqual(len(validation_errors), 0)\n validation_errors = self._get_validation_errors(loader, 'node_templates/foo/missing.json', 'missing_option')\n self.assertEqual(len(validation_errors), 2)\n validation_errors = self._get_validation_errors(loader, 'node_templates/foo/correct.json')\n self.assertEqual(len(validation_errors), 0)\n", "method_code": " def _validate_node_template_agreement(self, raw_configuration):\n \"\"\"\n Ensure that the `node_aws_type` and `node_template_name` for each\n `node_template` configuration actually agrees with the folder structure\n in which it was contained.\n \n A `node_templates/ec2/foo.json` template file should not say it's an\n `rds` node called `bar`.\n \"\"\"\n raw_node_template_config = raw_configuration['node_templates']\n for aws_type, node_templates in raw_node_template_config.items():\n for node_template_name, config in node_templates.items():\n relative_path = 'node_templates/%s/%s.json' % (aws_type, node_template_name)\n self._validate_option_agrees(relative_path, 'node_aws_type', aws_type, config)\n self._validate_option_agrees(relative_path, 'node_template_name', node_template_name, config)\n ", "context": "class NeckbeardLoader(object):\n def _validate_node_template_agreement(self, raw_configuration): ...\n def __init__(self, configuration_directory): ...\n def _all_config_files(self, directory): ...\n def _add_validation_error(self, file_path, error_type, extra_context=None): ...\n def _add_path_relative_validation_error(self, relative_path, error_type, extra_context=None): ...\n def print_validation_errors(self): ...\n def _get_config_from_file(self, file_path): ...\n def _get_data_from_file(self, extensionless_file_path, parser, file_type): ...\n def _get_name_from_conf_file_path(self, file_path): ...\n def _load_root_configuration_files(self, configuration_directory): ...\n def _load_environment_files(self, configuration_directory): ...\n def _load_node_template_files(self, configuration_directory): ...\n def _load_configuration_files(self, configuration_directory): ...\n def _validate_option_agrees(self, relative_path, name, expected_value, config, required=True): ...\n def _validate_environment_name_agreement(self, raw_configuration): ...\n def _validate_neckbeard_conf_version(self, raw_configuration): ...\n def _validate_configuration(self): ...\n def configuration_is_valid(self): ...\n\n self.configuration_directory = configuration_directory\n self.validation_errors = {}\n self.raw_configuration = copy(self.CONFIG_STRUCTURE)\n\n VALIDATION_MESSAGES = {'invalid_configuration_directory': 'The configuration directory does not exist or is not accessible.', 'invalid_json': 'Invalid JSON. Check for trailing commas. Error: %(error)s', 'invalid_yaml': 'Invalid YAML. Error: %(error)s', 'duplicate_config': 'JSON and YAML files with same name should not be present. File: %(filename)s', 'missing_file': 'File is required, but missing.', 'missing_environment': 'You need at least one environment configuration, or what are we really doing here? I recommend starting with <%(file_path)s/staging.json>', 'missing_option': \"The option '%(option_name)s' is required, but missing.\", 'file_option_mismatch': \"The option '%(option_name)s' doesn't match its folder structure. Expected: '%(expected)s' But found: '%(actual)s'\"}\n CONFIG_STRUCTURE = {'constants': None, 'neckbeard_meta': None, 'secrets': None, 'secrets.tpl': None, 'environments': {}, 'node_templates': {'ec2': {}, 'rds': {}, 'elb': {}}}\n ROOT_CONF_FILES = ['constants', 'neckbeard_meta', 'secrets', 'secrets.tpl']\n VERSION_OPTION = 'neckbeard_conf_version'\n", "repository": "winhamwr/neckbeard", "test_name": "test_node_template_name_mismatch", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000666.py"} {"focal_file": "neckbeard/loader.py", "focal_class": null, "focal_method": "_validate_environment_name_agreement", "tests": "import unittest\n\nclass Test_validate_environment_name_agreement(unittest.TestCase):\n def test_environment_name_mismatch(self):\n loader = self._get_loader_for_fixture('minimal')\n loader.validation_errors = {}\n raw_configuration = {'environments': {'correct': {'name': 'correct'}, 'mismatch': {'name': 'wrong'}, 'missing': {}}}\n loader._validate_environment_name_agreement(raw_configuration)\n validation_errors = self._get_validation_errors(loader, 'environments/correct.json')\n self.assertEqual(len(validation_errors), 0)\n validation_errors = self._get_validation_errors(loader, 'environments/mismatch.json', 'file_option_mismatch')\n self.assertEqual(len(validation_errors), 1)\n validation_errors = self._get_validation_errors(loader, 'environments/missing.json', 'missing_option')\n self.assertEqual(len(validation_errors), 1)\n", "method_code": " def _validate_environment_name_agreement(self, raw_configuration):\n environments_config = raw_configuration['environments']\n for environment_name, config in environments_config.items():\n relative_path = 'environments/%s.json' % environment_name\n self._validate_option_agrees(relative_path, 'name', environment_name, config)\n ", "context": "class NeckbeardLoader(object):\n def _validate_environment_name_agreement(self, raw_configuration): ...\n def __init__(self, configuration_directory): ...\n def _all_config_files(self, directory): ...\n def _add_validation_error(self, file_path, error_type, extra_context=None): ...\n def _add_path_relative_validation_error(self, relative_path, error_type, extra_context=None): ...\n def print_validation_errors(self): ...\n def _get_config_from_file(self, file_path): ...\n def _get_data_from_file(self, extensionless_file_path, parser, file_type): ...\n def _get_name_from_conf_file_path(self, file_path): ...\n def _load_root_configuration_files(self, configuration_directory): ...\n def _load_environment_files(self, configuration_directory): ...\n def _load_node_template_files(self, configuration_directory): ...\n def _load_configuration_files(self, configuration_directory): ...\n def _validate_option_agrees(self, relative_path, name, expected_value, config, required=True): ...\n def _validate_node_template_agreement(self, raw_configuration): ...\n def _validate_neckbeard_conf_version(self, raw_configuration): ...\n def _validate_configuration(self): ...\n def configuration_is_valid(self): ...\n\n self.configuration_directory = configuration_directory\n self.validation_errors = {}\n self.raw_configuration = copy(self.CONFIG_STRUCTURE)\n\n VALIDATION_MESSAGES = {'invalid_configuration_directory': 'The configuration directory does not exist or is not accessible.', 'invalid_json': 'Invalid JSON. Check for trailing commas. Error: %(error)s', 'invalid_yaml': 'Invalid YAML. Error: %(error)s', 'duplicate_config': 'JSON and YAML files with same name should not be present. File: %(filename)s', 'missing_file': 'File is required, but missing.', 'missing_environment': 'You need at least one environment configuration, or what are we really doing here? I recommend starting with <%(file_path)s/staging.json>', 'missing_option': \"The option '%(option_name)s' is required, but missing.\", 'file_option_mismatch': \"The option '%(option_name)s' doesn't match its folder structure. Expected: '%(expected)s' But found: '%(actual)s'\"}\n CONFIG_STRUCTURE = {'constants': None, 'neckbeard_meta': None, 'secrets': None, 'secrets.tpl': None, 'environments': {}, 'node_templates': {'ec2': {}, 'rds': {}, 'elb': {}}}\n ROOT_CONF_FILES = ['constants', 'neckbeard_meta', 'secrets', 'secrets.tpl']\n VERSION_OPTION = 'neckbeard_conf_version'\n", "repository": "winhamwr/neckbeard", "test_name": "test_environment_name_mismatch", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000667.py"} {"focal_file": "neckbeard/loader.py", "focal_class": null, "focal_method": "_validate_neckbeard_conf_version", "tests": "import unittest\n\nclass Test_validate_neckbeard_conf_version(unittest.TestCase):\n def test_neckbeard_conf_version_required(self):\n loader = self._get_loader_for_fixture('minimal')\n loader.validation_errors = {}\n raw_configuration = {'constants': {}, 'neckbeard_meta': {}, 'secrets': {}, 'secrets.tpl': {}, 'environments': {'foo': {}, 'bar': {}}, 'node_templates': {'ec2': {'foo': {}, 'bar': {}}, 'baz': {'bang': {}}}}\n loader._validate_neckbeard_conf_version(raw_configuration)\n validation_errors = self._get_validation_errors(loader, 'environments/foo.json', 'missing_option')\n self.assertEqual(len(validation_errors), 1)\n expected_error_count = 4 + 2 + 3\n self.assertEqual(len(loader.validation_errors), expected_error_count)\n correct_configuration = {'constants': {'neckbeard_conf_version': '0.1'}, 'neckbeard_meta': {'neckbeard_conf_version': '0.1'}, 'secrets': {'neckbeard_conf_version': '0.1'}, 'secrets.tpl': {'neckbeard_conf_version': '0.1'}, 'environments': {'foo': {'neckbeard_conf_version': '0.1'}, 'bar': {'neckbeard_conf_version': '0.1'}}, 'node_templates': {'ec2': {'foo': {'neckbeard_conf_version': '0.1'}, 'bar': {'neckbeard_conf_version': '0.1'}}, 'baz': {'bang': {'neckbeard_conf_version': '0.1'}}}}\n loader.validation_errors = {}\n loader._validate_neckbeard_conf_version(correct_configuration)\n self.assertEqual(len(loader.validation_errors), 0)\n", "method_code": " def _validate_neckbeard_conf_version(self, raw_configuration):\n for root_conf in self.ROOT_CONF_FILES:\n if not raw_configuration[root_conf].get(self.VERSION_OPTION):\n relative_path = '%s.json' % root_conf\n self._add_path_relative_validation_error(relative_path, 'missing_option', extra_context={'option_name': self.VERSION_OPTION})\n for name, config in raw_configuration['environments'].items():\n if not config.get(self.VERSION_OPTION):\n relative_path = 'environments/%s.json' % name\n self._add_path_relative_validation_error(relative_path, 'missing_option', extra_context={'option_name': self.VERSION_OPTION})\n all_node_templates = raw_configuration.get('node_templates', {})\n for aws_type, node_templates in all_node_templates.items():\n for node_template_name, config in node_templates.items():\n if not config.get(self.VERSION_OPTION):\n relative_path = 'node_templates/%s/%s.json' % (aws_type, node_template_name)\n self._add_path_relative_validation_error(relative_path, 'missing_option', extra_context={'option_name': self.VERSION_OPTION})\n ", "context": "class NeckbeardLoader(object):\n def _validate_neckbeard_conf_version(self, raw_configuration): ...\n def __init__(self, configuration_directory): ...\n def _all_config_files(self, directory): ...\n def _add_validation_error(self, file_path, error_type, extra_context=None): ...\n def _add_path_relative_validation_error(self, relative_path, error_type, extra_context=None): ...\n def print_validation_errors(self): ...\n def _get_config_from_file(self, file_path): ...\n def _get_data_from_file(self, extensionless_file_path, parser, file_type): ...\n def _get_name_from_conf_file_path(self, file_path): ...\n def _load_root_configuration_files(self, configuration_directory): ...\n def _load_environment_files(self, configuration_directory): ...\n def _load_node_template_files(self, configuration_directory): ...\n def _load_configuration_files(self, configuration_directory): ...\n def _validate_option_agrees(self, relative_path, name, expected_value, config, required=True): ...\n def _validate_node_template_agreement(self, raw_configuration): ...\n def _validate_environment_name_agreement(self, raw_configuration): ...\n def _validate_configuration(self): ...\n def configuration_is_valid(self): ...\n\n self.configuration_directory = configuration_directory\n self.validation_errors = {}\n self.raw_configuration = copy(self.CONFIG_STRUCTURE)\n\n VALIDATION_MESSAGES = {'invalid_configuration_directory': 'The configuration directory does not exist or is not accessible.', 'invalid_json': 'Invalid JSON. Check for trailing commas. Error: %(error)s', 'invalid_yaml': 'Invalid YAML. Error: %(error)s', 'duplicate_config': 'JSON and YAML files with same name should not be present. File: %(filename)s', 'missing_file': 'File is required, but missing.', 'missing_environment': 'You need at least one environment configuration, or what are we really doing here? I recommend starting with <%(file_path)s/staging.json>', 'missing_option': \"The option '%(option_name)s' is required, but missing.\", 'file_option_mismatch': \"The option '%(option_name)s' doesn't match its folder structure. Expected: '%(expected)s' But found: '%(actual)s'\"}\n CONFIG_STRUCTURE = {'constants': None, 'neckbeard_meta': None, 'secrets': None, 'secrets.tpl': None, 'environments': {}, 'node_templates': {'ec2': {}, 'rds': {}, 'elb': {}}}\n ROOT_CONF_FILES = ['constants', 'neckbeard_meta', 'secrets', 'secrets.tpl']\n VERSION_OPTION = 'neckbeard_conf_version'\n", "repository": "winhamwr/neckbeard", "test_name": "test_neckbeard_conf_version_required", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000668.py"} {"focal_file": "scripts/common/annotator.py", "focal_class": "common.annotator.StructuredAnnotationStep", "focal_method": "step_started", "tests": "import unittest\n\nclass Test_common_annotator_StructuredAnnotationStep_step_started(unittest.TestCase):\n def testStructured(self):\n stream = annotator.StructuredAnnotationStream(stream=self.buf, flush_before=None)\n step = annotator.StructuredAnnotationStep(annotation_stream=stream, stream=self.buf, flush_before=None)\n stream.step_cursor('one')\n step.step_started()\n stream.step_cursor('two')\n step.step_started()\n stream.step_cursor('one')\n step.step_closed()\n stream.step_cursor('two')\n step.step_closed()\n result = ['@@@STEP_CURSOR one@@@', '@@@STEP_STARTED@@@', '@@@STEP_CURSOR two@@@', '@@@STEP_STARTED@@@', '@@@STEP_CURSOR one@@@', '@@@STEP_CLOSED@@@', '@@@STEP_CURSOR two@@@', '@@@STEP_CLOSED@@@']\n self.assertEquals(result, self._getLines())\n", "method_code": " def step_started(self):\n self.control.step_started()\n return self\n ", "context": "class StructuredAnnotationStep(StepCommandsStepControlCommands):\n def step_started(self): ...\n def __init__(self, annotation_stream, *args, **kwargs): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_value, tb): ...\n def step_exception_occured(self, exc_type, exc_value, tb): ...\n def step_ended(self): ...\n\n self.annotation_stream = annotation_stream\n self.control = StepControlCommands(self.stream, self.flush_before)\n self.emitted_logs = set()\n", "repository": "yjbanov/chromium_build", "test_name": "testStructured", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000669.py"} {"focal_file": "scripts/common/annotator.py", "focal_class": null, "focal_method": "MatchAnnotation", "tests": "import unittest\n\nclass Test_MatchAnnotation(unittest.TestCase):\n def testBadAnnotation(self):\n with self.assertRaisesRegexp(Exception, 'Unrecognized annotator'):\n annotator.MatchAnnotation('@@@SOME_OTHER_METHOD@@@', self.c)\n", "method_code": "def MatchAnnotation(line, callback_implementor):\n \"\"\"Call back into |callback_implementor| if line contains an annotation.\n\n Args:\n line (str) - The line to analyze\n callback_implementor (object) - An object which contains methods\n corresponding to all of the annotations in the |ALL_ANNOTATIONS|\n dictionary. For example, it should contain a method STEP_SUMMARY_TEXT\n taking a single argument.\n\n Parsing method:\n * if line doesn't match /^@@@.*@@@$/, return without calling back\n * Look for the first '@' or ' '\n \"\"\"\n if not (line.startswith('@@@') and line.endswith('@@@') and (len(line) > 6)):\n return\n line = line[3:-3]\n idx = min((x for x in (line.find('@'), line.find(' '), len(line)) if x > 0))\n cmd_text = line[:idx]\n cmd = DEPRECATED_ALIASES.get(cmd_text, cmd_text)\n field_count = ALL_ANNOTATIONS.get(cmd)\n if field_count is None:\n raise Exception('Unrecognized annotator command \"%s\"' % cmd_text)\n if field_count:\n if idx == len(line):\n raise Exception('Annotator command \"%s\" expects %d args, got 0.' % (cmd_text, field_count))\n line = line[idx + 1:]\n args = line.split('@', field_count - 1)\n if len(args) != field_count:\n raise Exception('Annotator command \"%s\" expects %d args, got %d.' % (cmd_text, field_count, len(args)))\n else:\n line = line[len(cmd_text):]\n if line:\n raise Exception('Annotator command \"%s\" expects no args, got cruft \"%s\".' % (cmd_text, line))\n args = []\n fn = getattr(callback_implementor, cmd, None)\n if fn is None:\n raise Exception('\"%s\" does not implement \"%s\"' % (callback_implementor, cmd))\n fn(*args)", "context": "def MatchAnnotation(line, callback_implementor): ...\ndef emit(line, stream, flush_before=None): ...\ndef MatchAnnotation(line, callback_implementor): ...\ndef print_step(step, env, stream): ...\n", "repository": "yjbanov/chromium_build", "test_name": "testBadAnnotation", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000670.py"} {"focal_file": "scripts/common/configcache.py", "focal_class": null, "focal_method": "FetchAndCache", "tests": "import unittest\n\nclass Test_FetchAndCache(unittest.TestCase):\n def testFetchAndCache(self):\n self.fetcher.return_data = 'bar'\n self.fetcher.return_version = 'v1'\n data, version = self.cache.FetchAndCache('foo', 'v1')\n self.assertEqual(self.fetcher.call_args, ('foo', 'v1'))\n self.assertEqual(data, 'bar')\n self.assertEqual(version, 'v1')\n self.assertWroteFile('bar', 'cache', 'test', 'foo.data')\n self.assertWroteFile('v1', 'cache', 'test', 'foo.version')\n", "method_code": " def FetchAndCache(self, name, version=None):\n \"\"\"Forces a cache artifact to be fetched and cached.\n \n This will operate even if the artifact is currently present in the cache.\n \n Returns: (data, version)\n data: (str) The fetched cache artifact.\n version: (str) The fetched artifact version.\n \n Raises:\n ReadOnlyError: If this cache is read-only.\n ValueError: If the fetcher doesn't return the requested version.\n \"\"\"\n if self.read_only:\n raise ReadOnlyError('Cache is read-only.')\n artifact_dir = os.path.dirname(self._ArtifactPath(name))\n if not os.path.isdir(artifact_dir):\n os.makedirs(artifact_dir)\n data, fetched_version = self.fetcher(name, version)\n if version and version != fetched_version:\n raise ValueError('Fetched artifact version (%s) differs from requested (%s)' % (fetched_version, version))\n version = fetched_version\n logging.debug(\"Fetched artifact '%s' version '%s' (%d bytes)\", name, version, len(data))\n data_path = self._ArtifactDataPath(name)\n version_path = self._ArtifactVersionPath(name)\n self._WriteFile(data_path, data)\n self._WriteFile(version_path, version)\n return (data, version)\n ", "context": "class CacheManager(object):\n def FetchAndCache(self, name, version=None): ...\n def __init__(self, cache_name, cache_dir=None, fetcher=None, base_logger=None): ...\n def _ArtifactPath(self, name): ...\n def _ArtifactVersionPath(self, name): ...\n def _ArtifactDataPath(self, name): ...\n def read_only(self): ...\n def _WriteFile(path, data): ...\n def _ReadFile(path): ...\n def GetArtifactVersion(self, name): ...\n def Get(self, name, version=None): ...\n\n self.logger = (base_logger or logging.getLogger()).getChild('Cache[%s]' % (cache_name,))\n self.cache_dir = cache_dir or self.CACHE_PATH\n self.fetcher = fetcher\n self.cache_name = cache_name\n\n CACHE_PATH = os.path.join(BUILD_PATH, '.config_cache')\n", "repository": "yjbanov/chromium_build", "test_name": "testFetchAndCache", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000671.py"} {"focal_file": "scripts/common/configcache.py", "focal_class": null, "focal_method": "GetArtifactVersion", "tests": "import unittest\n\nclass Test_GetArtifactVersion(unittest.TestCase):\n def testGetArtifactVersion(self):\n self.fetcher.return_data = 'bar'\n self.fetcher.return_version = 'v1'\n self.cache.FetchAndCache('foo', 'v1')\n self.assertEqual(self.cache.GetArtifactVersion('foo'), 'v1')\n\n def testUpdateArtifactVersio(self):\n self.fetcher.return_data = 'bar'\n self.fetcher.return_version = 'v1'\n self.cache.FetchAndCache('foo', 'v1')\n self.assertEqual(self.cache.GetArtifactVersion('foo'), 'v1')\n self.fetcher.return_version = 'v2'\n self.cache.FetchAndCache('foo', 'v2')\n self.assertEqual(self.cache.GetArtifactVersion('foo'), 'v2')\n", "method_code": " def GetArtifactVersion(self, name):\n \"\"\"Returns: (str) The artifact version, or None if it doesn't exist.\n \"\"\"\n try:\n return self._ReadFile(self._ArtifactVersionPath(name))\n except IOError:\n return None\n ", "context": "class CacheManager(object):\n def GetArtifactVersion(self, name): ...\n def __init__(self, cache_name, cache_dir=None, fetcher=None, base_logger=None): ...\n def _ArtifactPath(self, name): ...\n def _ArtifactVersionPath(self, name): ...\n def _ArtifactDataPath(self, name): ...\n def read_only(self): ...\n def _WriteFile(path, data): ...\n def _ReadFile(path): ...\n def FetchAndCache(self, name, version=None): ...\n def Get(self, name, version=None): ...\n\n self.logger = (base_logger or logging.getLogger()).getChild('Cache[%s]' % (cache_name,))\n self.cache_dir = cache_dir or self.CACHE_PATH\n self.fetcher = fetcher\n self.cache_name = cache_name\n\n CACHE_PATH = os.path.join(BUILD_PATH, '.config_cache')\n", "repository": "yjbanov/chromium_build", "test_name": "testGetArtifactVersion", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000672.py"} {"focal_file": "scripts/common/cros_chromite.py", "focal_class": null, "focal_method": "HasVmTests", "tests": "import unittest\n\nclass Test_HasVmTests(unittest.TestCase):\n def testHasTests(self):\n self.assertFalse(self.test.HasVmTests())\n self.assertTrue(self.test.HasHwTests())\n self.assertFalse(self.no_hwtest_pre_cq.HasHwTests())\n self.assertFalse(self.test.HasUnitTests())\n self.assertTrue(self.baremetal.HasVmTests())\n self.assertTrue(self.baremetal.HasHwTests())\n self.assertTrue(self.baremetal.HasUnitTests())\n", "method_code": " def HasVmTests(self):\n \"\"\"Returns: (bool) if this target or any of its children have VM tests.\n \"\"\"\n return self._HasTests('vm_tests')\n ", "context": "class ChromiteTarget(object):\n def HasVmTests(self): ...\n def __init__(self, name, config, default=None, templates=None): ...\n def _setChildren(self, children): ...\n def FromConfigDict(cls, name, config, default=None, templates=None): ...\n def name(self): ...\n def board(self): ...\n def base(self): ...\n def suffix(self): ...\n def category(self): ...\n def is_master(self): ...\n def is_public(self): ...\n def children(self): ...\n def __getitem__(self, key): ...\n def get(self, key, default=None): ...\n def _HasTests(self, test_property): ...\n def HasHwTests(self): ...\n def HasUnitTests(self): ...\n def IsGeneralPreCqBuilder(self): ...\n def IsPreCqBuilder(self): ...\n def Categorize(cls, name, build_type=None): ...\n\n self._name = name\n self._config = config\n self._children = ()\n self._default = default\n self._base, self._suffix, self._category = self.Categorize(name, build_type=self.get('build_type'))\n\n ANDROID_PFQ = 'android_pfq'\n ASAN = 'asan'\n CANARY = 'canary'\n CANARY_TOOLCHAIN = 'canary_toolchain'\n FACTORY = 'factory'\n FIRMWARE = 'firmware'\n FULL = 'full'\n INCREMENTAL = 'incremental'\n LLVM = 'llvm'\n PALADIN = 'paladin'\n PFQ = 'pfq'\n PRE_CQ = 'pre-cq'\n PRE_CQ_LAUNCHER = 'pre-cq-launcher'\n PRE_FLIGHT_BRANCH = 'pre-flight-branch'\n REFRESH_PACKAGES = 'refresh-packages'\n SDK = 'sdk'\n TOOLCHAIN = 'toolchain'\n BUILD_TYPE_CATEGORY_MAP = {'priest': PRE_CQ_LAUNCHER, 'paladin': PALADIN, 'canary': CANARY, 'toolchain': CANARY_TOOLCHAIN, 'chrome': PFQ}\n BUILDER_NAME_CATEGORY_MAP = {'refresh-packages': REFRESH_PACKAGES}\n SUFFIX_MAP = collections.OrderedDict(((ANDROID_PFQ, ('android-pfq',)), (ASAN, ('asan',)), (CANARY_TOOLCHAIN, ('toolchain-release',)), (CANARY, ('release', 'release-group')), (FACTORY, ('factory',)), (FIRMWARE, ('firmware',)), (FULL, ('full',)), (INCREMENTAL, ('incremental',)), (LLVM, ('llvm',)), (PALADIN, ('paladin',)), (PFQ, ('chrome-pfq', 'chromium-pfq')), (PRE_CQ, ('pre-cq',)), (PRE_FLIGHT_BRANCH, ('pre-flight-branch',)), (SDK, ('sdk',)), (TOOLCHAIN, ('toolchain-major', 'toolchain-minor'))))\n _MISSING = object()\n", "repository": "yjbanov/chromium_build", "test_name": "testHasTests", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000673.py"} {"focal_file": "scripts/common/cros_chromite.py", "focal_class": null, "focal_method": "Categorize", "tests": "import unittest\n\nclass Test_Categorize(unittest.TestCase):\n def testCategorize(self):\n expectations = ()\n expectations = (('pre-cq-launcher', 'priest', 'pre-cq-launcher', None, 'PRE_CQ_LAUNCHER'), ('odd-name-paladin', 'canary', 'odd-name-paladin', None, 'CANARY'), ('my-board-asan', None, 'my-board', 'asan', 'ASAN'), ('my-board-pre-cq', None, 'my-board', 'pre-cq', 'PRE_CQ'), ('my-board-chrome-pfq', None, 'my-board', 'chrome-pfq', 'PFQ'), ('my-board-chromium-pfq', None, 'my-board', 'chromium-pfq', 'PFQ'), ('my-board-paladin', None, 'my-board', 'paladin', 'PALADIN'), ('my-board-release', None, 'my-board', 'release', 'CANARY'), ('my-board-release-group', None, 'my-board', 'release-group', 'CANARY'), ('my-board-firmware', None, 'my-board', 'firmware', 'FIRMWARE'), ('my-board-incremental', None, 'my-board', 'incremental', 'INCREMENTAL'), ('my-board-factory', None, 'my-board', 'factory', 'FACTORY'), ('my-board-project-sdk', None, 'my-board-project', 'sdk', 'SDK'), ('my-board-toolchain-major', None, 'my-board', 'toolchain-major', 'TOOLCHAIN'), ('my-board-toolchain-minor', None, 'my-board', 'toolchain-minor', 'TOOLCHAIN'), ('master-toolchain-release', None, 'master', 'toolchain-release', 'CANARY_TOOLCHAIN'))\n for name, build_type, exp_base, exp_suffix, exp_cat_attr in expectations:\n exp_category = getattr(cros_chromite.ChromiteTarget, exp_cat_attr)\n base, suffix, category = cros_chromite.ChromiteTarget.Categorize(name, build_type=build_type)\n self.assertEqual((base, suffix, category), (exp_base, exp_suffix, exp_category))\n", "method_code": " def Categorize(cls, name, build_type=None):\n \"\"\"Returns: (base, suffix, typ)\n base: (str) The base board name\n suffix: (str) The board type suffix, if identifed. Otherwise, None.\n category: (enum) The config typecategory if identified. Otherwise, None.\n \n This method attempts to identify the type of build based on the build name.\n If no type can be inferred, None will be returned.\n \n Args:\n name (str): The configuration name.\n build_type (str): If not None, the configuration build type.\n \"\"\"\n name = name or ''\n category = cls.BUILDER_NAME_CATEGORY_MAP.get(name)\n if not category and build_type:\n category = cls.BUILD_TYPE_CATEGORY_MAP.get(build_type)\n if not category:\n \n def get_category():\n for typ, suffixes in cls.SUFFIX_MAP.iteritems():\n for suffix in suffixes:\n if name.endswith('-' + suffix):\n return typ\n return None\n category = get_category()\n if not category:\n return (None, None, None)\n suffixes = cls.SUFFIX_MAP.get(category, ())\n for suffix in suffixes:\n if name.endswith('-' + suffix):\n return (name[:-(len(suffix) + 1)], suffix, category)\n return (name, None, category)\n ", "context": "class ChromiteTarget(object):\n @classmethod\n def Categorize(cls, name, build_type=None): ...\n def __init__(self, name, config, default=None, templates=None): ...\n def _setChildren(self, children): ...\n def FromConfigDict(cls, name, config, default=None, templates=None): ...\n def name(self): ...\n def board(self): ...\n def base(self): ...\n def suffix(self): ...\n def category(self): ...\n def is_master(self): ...\n def is_public(self): ...\n def children(self): ...\n def __getitem__(self, key): ...\n def get(self, key, default=None): ...\n def _HasTests(self, test_property): ...\n def HasVmTests(self): ...\n def HasHwTests(self): ...\n def HasUnitTests(self): ...\n def IsGeneralPreCqBuilder(self): ...\n def IsPreCqBuilder(self): ...\n\n self._name = name\n self._config = config\n self._children = ()\n self._default = default\n self._base, self._suffix, self._category = self.Categorize(name, build_type=self.get('build_type'))\n\n ANDROID_PFQ = 'android_pfq'\n ASAN = 'asan'\n CANARY = 'canary'\n CANARY_TOOLCHAIN = 'canary_toolchain'\n FACTORY = 'factory'\n FIRMWARE = 'firmware'\n FULL = 'full'\n INCREMENTAL = 'incremental'\n LLVM = 'llvm'\n PALADIN = 'paladin'\n PFQ = 'pfq'\n PRE_CQ = 'pre-cq'\n PRE_CQ_LAUNCHER = 'pre-cq-launcher'\n PRE_FLIGHT_BRANCH = 'pre-flight-branch'\n REFRESH_PACKAGES = 'refresh-packages'\n SDK = 'sdk'\n TOOLCHAIN = 'toolchain'\n BUILD_TYPE_CATEGORY_MAP = {'priest': PRE_CQ_LAUNCHER, 'paladin': PALADIN, 'canary': CANARY, 'toolchain': CANARY_TOOLCHAIN, 'chrome': PFQ}\n BUILDER_NAME_CATEGORY_MAP = {'refresh-packages': REFRESH_PACKAGES}\n SUFFIX_MAP = collections.OrderedDict(((ANDROID_PFQ, ('android-pfq',)), (ASAN, ('asan',)), (CANARY_TOOLCHAIN, ('toolchain-release',)), (CANARY, ('release', 'release-group')), (FACTORY, ('factory',)), (FIRMWARE, ('firmware',)), (FULL, ('full',)), (INCREMENTAL, ('incremental',)), (LLVM, ('llvm',)), (PALADIN, ('paladin',)), (PFQ, ('chrome-pfq', 'chromium-pfq')), (PRE_CQ, ('pre-cq',)), (PRE_FLIGHT_BRANCH, ('pre-flight-branch',)), (SDK, ('sdk',)), (TOOLCHAIN, ('toolchain-major', 'toolchain-minor'))))\n _MISSING = object()\n", "repository": "yjbanov/chromium_build", "test_name": "testCategorize", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000674.py"} {"focal_file": "scripts/common/frozendict.py", "focal_class": "frozendict", "focal_method": "itemtuple", "tests": "import unittest\n\nclass Test_frozendict_itemtuple(unittest.TestCase):\n def testItemTuple(self):\n self.assertEqual(frozendict().itemtuple(), ())\n self.assertEqual(frozendict(a=1, b=2).itemtuple(), (('a', 1), ('b', 2)))\n", "method_code": " def itemtuple(self):\n return tuple(sorted(self.iteritems()))\n ", "context": "class frozendict(collections.Mapping):\n @memo.memo_i()\n def itemtuple(self): ...\n def __init__(self, *args, **kwargs): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __getitem__(self, key): ...\n def __hash__(self): ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __deepcopy__(self, _memo): ...\n def mutableDict(self): ...\n def extend(self, **kwargs): ...\n\n self._data = dict(*args, **kwargs)\n", "repository": "yjbanov/chromium_build", "test_name": "testItemTuple", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000675.py"} {"focal_file": "scripts/common/frozendict.py", "focal_class": "frozendict", "focal_method": "mutableDict", "tests": "import unittest\n\nclass Test_frozendict_mutableDict(unittest.TestCase):\n def testMutableDict(self):\n frozen = frozendict(a=1, b=frozendict(x=1, y=2))\n mutable = frozen.mutableDict()\n self.assertEqual(mutable, frozen)\n try:\n mutable['c'] = 10\n except TypeError:\n self.fail('Failed to assign to mutable copy')\n self.assertEqual(mutable, {'a': 1, 'b': {'x': 1, 'y': 2}, 'c': 10})\n try:\n mutable['b']['z'] = 20\n except TypeError:\n self.fail('Failed to assign to mutable subcopy')\n self.assertEqual(mutable, {'a': 1, 'b': {'x': 1, 'y': 2, 'z': 20}, 'c': 10})\n", "method_code": " def mutableDict(self):\n \"\"\"\n Returns a mutable dictionary copy, replacing 'frozendict' with 'dict's.\n \n This function uses the 'copy.deepcopy' method to create a mutable deep copy\n of the dictionary.\n \n Note that due to the one-size-fits-all behavior of 'deepcopy', the result\n can be anything from heavyhanded to incorrect depending on the contents of\n the dictionary. The caller should make sure they understand the operation\n and its behavior on all of the dictionary's subtypes before using it.\n \n Returns: (dict) A mutable clone of the dictionary and its members.\n \"\"\"\n return copy.deepcopy(self)\n ", "context": "class frozendict(collections.Mapping):\n def mutableDict(self): ...\n def __init__(self, *args, **kwargs): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __getitem__(self, key): ...\n def __hash__(self): ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __deepcopy__(self, _memo): ...\n def itemtuple(self): ...\n def extend(self, **kwargs): ...\n\n self._data = dict(*args, **kwargs)\n", "repository": "yjbanov/chromium_build", "test_name": "testMutableDict", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000676.py"} {"focal_file": "scripts/common/frozendict.py", "focal_class": "frozendict", "focal_method": "extend", "tests": "import unittest\n\nclass Test_frozendict_extend(unittest.TestCase):\n def testExtend(self):\n frozen = frozendict(a=1, b=2)\n ext = frozen.extend(c=3)\n self.assertEqual(type(ext), frozendict)\n self.assertEqual(ext, {'a': 1, 'b': 2, 'c': 3})\n", "method_code": " def extend(self, **kwargs):\n \"\"\"Returns a copy of this object with the 'kwargs' fields updated.\"\"\"\n ndata = self.mutableDict()\n ndata.update(kwargs)\n return type(self)(**ndata)\n ", "context": "class frozendict(collections.Mapping):\n def extend(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __getitem__(self, key): ...\n def __hash__(self): ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __deepcopy__(self, _memo): ...\n def itemtuple(self): ...\n def mutableDict(self): ...\n\n self._data = dict(*args, **kwargs)\n", "repository": "yjbanov/chromium_build", "test_name": "testExtend", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000677.py"} {"focal_file": "scripts/common/gtest_utils.py", "focal_class": "common.gtest_utils.GTestJSONParser", "focal_method": "PassedTests", "tests": "import unittest\n\nclass Test_common_gtest_utils_GTestJSONParser_PassedTests(unittest.TestCase):\n def testPassedTests(self):\n parser = gtest_utils.GTestJSONParser()\n parser.ProcessJSONData({'disabled_tests': [], 'global_tags': [], 'per_iteration_data': [{'Test.One': [{'status': 'SUCCESS', 'output_snippet': ''}], 'Test.Two': [{'status': 'SUCCESS', 'output_snippet': ''}]}]})\n self.assertEqual(['Test.One', 'Test.Two'], parser.PassedTests())\n self.assertEqual([], parser.FailedTests())\n self.assertEqual(0, parser.FlakyTests())\n self.assertEqual(0, parser.DisabledTests())\n self.assertEqual(['SUCCESS'], parser.TriesForTest('Test.One'))\n self.assertEqual(['SUCCESS'], parser.TriesForTest('Test.Two'))\n", "method_code": " def PassedTests(self, include_fails=False, include_flaky=False):\n \"\"\"Returns list of tests that passed.\"\"\"\n return self._TestsByStatus('OK', include_fails, include_flaky)\n ", "context": "class GTestLogParser(object):\n def PassedTests(self, include_fails=False, include_flaky=False): ...\n def __init__(self): ...\n def GetCurrentTest(self): ...\n def _StatusOfTest(self, test): ...\n def _TestsByStatus(self, status, include_fails, include_flaky): ...\n def _RecordError(self, line, reason): ...\n def RunningTests(self): ...\n def ParsingErrors(self): ...\n def ClearParsingErrors(self): ...\n def FailedTests(self, include_fails=False, include_flaky=False): ...\n def TriesForTest(self, test): ...\n def DisabledTests(self): ...\n def FlakyTests(self): ...\n def FailureDescription(self, test): ...\n def MemoryToolReportHashes(self): ...\n def MemoryToolReport(self, report_hash): ...\n def CompletedWithoutFailure(self): ...\n def ProcessLine(self, line): ...\n def _ProcessLine(self, line): ...\n\n self.completed = False\n self._current_test = ''\n self._failure_description = []\n self._current_report_hash = ''\n self._current_report = []\n self._parsing_failures = False\n self._line_number = 0\n self._internal_error_lines = []\n self._test_status = {}\n self._memory_tool_reports = {}\n self._disabled_tests = 0\n self._flaky_tests = 0\n self._master_name_re = re.compile('\\\\[Running for master: \"([^\"]*)\"')\n self.master_name = ''\n self._test_name = re.compile(test_name_regexp)\n self._test_start = re.compile('\\\\[\\\\s+RUN\\\\s+\\\\] ' + test_name_regexp)\n self._test_ok = re.compile('\\\\[\\\\s+OK\\\\s+\\\\] ' + test_name_regexp)\n self._test_fail = re.compile('\\\\[\\\\s+FAILED\\\\s+\\\\] ' + test_name_regexp)\n self._test_passed = re.compile('\\\\[\\\\s+PASSED\\\\s+\\\\] \\\\d+ tests?.')\n self._run_test_cases_line = re.compile('\\\\[\\\\s*\\\\d+\\\\/\\\\d+\\\\]\\\\s+[0-9\\\\.]+s ' + test_name_regexp + ' .+')\n self._test_timeout = re.compile('Test timeout \\\\([0-9]+ ms\\\\) exceeded for ' + test_name_regexp)\n self._disabled = re.compile('\\\\s*YOU HAVE (\\\\d+) DISABLED TEST')\n self._flaky = re.compile('\\\\s*YOU HAVE (\\\\d+) FLAKY TEST')\n self._report_start = re.compile('### BEGIN MEMORY TOOL REPORT \\\\(error hash=#([0-9A-F]+)#\\\\)')\n self._report_end = re.compile('### END MEMORY TOOL REPORT \\\\(error hash=#([0-9A-F]+)#\\\\)')\n self._retry_message = re.compile('RETRYING FAILED TESTS:')\n self.retrying_failed = False\n self.TEST_STATUS_MAP = {'OK': TEST_SUCCESS_LABEL, 'failed': TEST_FAILURE_LABEL, 'timeout': TEST_TIMEOUT_LABEL, 'warning': TEST_WARNING_LABEL}\n", "repository": "yjbanov/chromium_build", "test_name": "testPassedTests", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000678.py"} {"focal_file": "scripts/common/gtest_utils.py", "focal_class": "common.gtest_utils.GTestJSONParser", "focal_method": "FailedTests", "tests": "import unittest\n\nclass Test_common_gtest_utils_GTestJSONParser_FailedTests(unittest.TestCase):\n def testFailedTests(self):\n parser = gtest_utils.GTestJSONParser()\n parser.ProcessJSONData({'disabled_tests': [], 'global_tags': [], 'per_iteration_data': [{'Test.One': [{'status': 'FAILURE', 'output_snippet': ''}], 'Test.Two': [{'status': 'FAILURE', 'output_snippet': ''}]}]})\n self.assertEqual([], parser.PassedTests())\n self.assertEqual(['Test.One', 'Test.Two'], parser.FailedTests())\n self.assertEqual(0, parser.FlakyTests())\n self.assertEqual(0, parser.DisabledTests())\n self.assertEqual(['FAILURE'], parser.TriesForTest('Test.One'))\n self.assertEqual(['FAILURE'], parser.TriesForTest('Test.Two'))\n\n def testRetriedTests(self):\n parser = gtest_utils.GTestJSONParser()\n parser.ProcessJSONData({'disabled_tests': [], 'global_tags': [], 'per_iteration_data': [{'Test.One': [{'status': 'FAILURE', 'output_snippet': ''}, {'status': 'FAILURE', 'output_snippet': ''}], 'Test.Two': [{'status': 'FAILURE', 'output_snippet': ''}, {'status': 'FAILURE_ON_EXIT', 'output_snippet': ''}, {'status': 'CRASH', 'output_snippet': ''}, {'status': 'TIMEOUT', 'output_snippet': ''}, {'status': 'SKIPPED', 'output_snippet': ''}, {'status': 'SUCCESS', 'output_snippet': ''}]}]})\n expected_tries_test_two = ['FAILURE', 'FAILURE_ON_EXIT', 'CRASH', 'TIMEOUT', 'SKIPPED', 'SUCCESS']\n self.assertEqual(['Test.Two'], parser.PassedTests())\n self.assertEqual(['Test.One'], parser.FailedTests())\n self.assertEqual(1, parser.FlakyTests())\n self.assertEqual(0, parser.DisabledTests())\n self.assertEqual(['FAILURE', 'FAILURE'], parser.TriesForTest('Test.One'))\n self.assertEqual(expected_tries_test_two, parser.TriesForTest('Test.Two'))\n\n def testIngoredFailedTests(self):\n TEST_IGNORED_FAILED_TESTS_SPEC = '\\n # A comment.\\n\\n crbug.com/12345 [ OS_WIN , OS_LINUX] Test.One\\n crbug.com/12345 [OS_WIN CPU_64_BITS MODE_RELEASE] Test.Two/2\\n crbug.com/12345 [,OS_MACOSX, OS_WIN CPU_64_BITS, ] Perf/Test.Three\\n crbug.com/12345 [ invalid.platform.spec ] Test.Four\\n crbug.com/12345 [ OS_WIN CPU_32_BITS MODE_RELEASE ] Test.Five\\n invalid line\\n '\n _, spec_filename = tempfile.mkstemp()\n spec_fd = open(spec_filename, 'w')\n spec_fd.write(TEST_IGNORED_FAILED_TESTS_SPEC)\n spec_fd.close()\n self.mock(chromium_utils, 'FindUpward', lambda *_: spec_filename)\n parser = gtest_utils.GTestJSONParser()\n try:\n parser.ProcessJSONData({'disabled_tests': ['Test.Six'], 'per_iteration_data': [{'Test.One': [{'status': 'FAILURE', 'output_snippet': ''}], 'Test.Two/2': [{'status': 'FAILURE', 'output_snippet': ''}], 'Perf/Test.Three': [{'status': 'FAILURE', 'output_snippet': ''}], 'Test.Four': [{'status': 'FAILURE', 'output_snippet': ''}], 'Test.Five': [{'status': 'FAILURE', 'output_snippet': ''}]}], 'global_tags': ['OS_WIN', 'CPU_64_BITS', 'MODE_RELEASE', 'OTHER_FLAG']}, '/fake/path/to/build')\n finally:\n os.remove(spec_filename)\n self.assertEqual(['Test.Five', 'Test.Four'], parser.FailedTests())\n self.assertEqual(['Perf/Test.Three', 'Test.One', 'Test.Two/2'], parser.IgnoredFailedTests())\n self.assertEqual(['FAILURE'], parser.TriesForTest('Test.One'))\n self.assertEqual(['FAILURE'], parser.TriesForTest('Test.Two/2'))\n self.assertEqual(['FAILURE'], parser.TriesForTest('Perf/Test.Three'))\n self.assertEqual(['FAILURE'], parser.TriesForTest('Test.Four'))\n self.assertEqual(['FAILURE'], parser.TriesForTest('Test.Five'))\n", "method_code": " def FailedTests(self, include_fails=False, include_flaky=False):\n \"\"\"Returns list of tests that failed, timed out, or didn't finish\n (crashed).\n \n This list will be incorrect until the complete log has been processed,\n because it will show currently running tests as having failed.\n \n Args:\n include_fails: If true, all failing tests with FAILS_ in their names will\n be included. Otherwise, they will only be included if they crashed or\n timed out.\n include_flaky: If true, all failing tests with FLAKY_ in their names will\n be included. Otherwise, they will only be included if they crashed or\n timed out.\n \n \"\"\"\n return self._TestsByStatus('failed', include_fails, include_flaky) + self._TestsByStatus('timeout', True, True) + self._TestsByStatus('warning', include_fails, include_flaky) + self.RunningTests()\n ", "context": "class GTestLogParser(object):\n def FailedTests(self, include_fails=False, include_flaky=False): ...\n def __init__(self): ...\n def GetCurrentTest(self): ...\n def _StatusOfTest(self, test): ...\n def _TestsByStatus(self, status, include_fails, include_flaky): ...\n def _RecordError(self, line, reason): ...\n def RunningTests(self): ...\n def ParsingErrors(self): ...\n def ClearParsingErrors(self): ...\n def PassedTests(self, include_fails=False, include_flaky=False): ...\n def TriesForTest(self, test): ...\n def DisabledTests(self): ...\n def FlakyTests(self): ...\n def FailureDescription(self, test): ...\n def MemoryToolReportHashes(self): ...\n def MemoryToolReport(self, report_hash): ...\n def CompletedWithoutFailure(self): ...\n def ProcessLine(self, line): ...\n def _ProcessLine(self, line): ...\n\n self.completed = False\n self._current_test = ''\n self._failure_description = []\n self._current_report_hash = ''\n self._current_report = []\n self._parsing_failures = False\n self._line_number = 0\n self._internal_error_lines = []\n self._test_status = {}\n self._memory_tool_reports = {}\n self._disabled_tests = 0\n self._flaky_tests = 0\n self._master_name_re = re.compile('\\\\[Running for master: \"([^\"]*)\"')\n self.master_name = ''\n self._test_name = re.compile(test_name_regexp)\n self._test_start = re.compile('\\\\[\\\\s+RUN\\\\s+\\\\] ' + test_name_regexp)\n self._test_ok = re.compile('\\\\[\\\\s+OK\\\\s+\\\\] ' + test_name_regexp)\n self._test_fail = re.compile('\\\\[\\\\s+FAILED\\\\s+\\\\] ' + test_name_regexp)\n self._test_passed = re.compile('\\\\[\\\\s+PASSED\\\\s+\\\\] \\\\d+ tests?.')\n self._run_test_cases_line = re.compile('\\\\[\\\\s*\\\\d+\\\\/\\\\d+\\\\]\\\\s+[0-9\\\\.]+s ' + test_name_regexp + ' .+')\n self._test_timeout = re.compile('Test timeout \\\\([0-9]+ ms\\\\) exceeded for ' + test_name_regexp)\n self._disabled = re.compile('\\\\s*YOU HAVE (\\\\d+) DISABLED TEST')\n self._flaky = re.compile('\\\\s*YOU HAVE (\\\\d+) FLAKY TEST')\n self._report_start = re.compile('### BEGIN MEMORY TOOL REPORT \\\\(error hash=#([0-9A-F]+)#\\\\)')\n self._report_end = re.compile('### END MEMORY TOOL REPORT \\\\(error hash=#([0-9A-F]+)#\\\\)')\n self._retry_message = re.compile('RETRYING FAILED TESTS:')\n self.retrying_failed = False\n self.TEST_STATUS_MAP = {'OK': TEST_SUCCESS_LABEL, 'failed': TEST_FAILURE_LABEL, 'timeout': TEST_TIMEOUT_LABEL, 'warning': TEST_WARNING_LABEL}\n", "repository": "yjbanov/chromium_build", "test_name": "testFailedTests", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000679.py"} {"focal_file": "scripts/common/gtest_utils.py", "focal_class": "common.gtest_utils.GTestJSONParser", "focal_method": "FlakyTests", "tests": "import unittest\n\nclass Test_common_gtest_utils_GTestJSONParser_FlakyTests(unittest.TestCase):\n def testFlakyTests(self):\n parser = gtest_utils.GTestJSONParser()\n parser.ProcessJSONData({'disabled_tests': [], 'global_tags': [], 'per_iteration_data': [{'Test.One': [{'status': 'FAILURE', 'output_snippet': ''}], 'Test.Two': [{'status': 'FAILURE', 'output_snippet': ''}, {'status': 'SUCCESS', 'output_snippet': ''}]}]})\n self.assertEqual(['Test.Two'], parser.PassedTests())\n self.assertEqual(['Test.One'], parser.FailedTests())\n self.assertEqual(1, parser.FlakyTests())\n self.assertEqual(0, parser.DisabledTests())\n self.assertEqual(['FAILURE'], parser.TriesForTest('Test.One'))\n self.assertEqual(['FAILURE', 'SUCCESS'], parser.TriesForTest('Test.Two'))\n", "method_code": " def FlakyTests(self):\n \"\"\"Returns the name of the flaky test (if there is only 1) or the number\n of flaky tests.\n \"\"\"\n return self._flaky_tests\n ", "context": "class GTestLogParser(object):\n def FlakyTests(self): ...\n def __init__(self): ...\n def GetCurrentTest(self): ...\n def _StatusOfTest(self, test): ...\n def _TestsByStatus(self, status, include_fails, include_flaky): ...\n def _RecordError(self, line, reason): ...\n def RunningTests(self): ...\n def ParsingErrors(self): ...\n def ClearParsingErrors(self): ...\n def PassedTests(self, include_fails=False, include_flaky=False): ...\n def FailedTests(self, include_fails=False, include_flaky=False): ...\n def TriesForTest(self, test): ...\n def DisabledTests(self): ...\n def FailureDescription(self, test): ...\n def MemoryToolReportHashes(self): ...\n def MemoryToolReport(self, report_hash): ...\n def CompletedWithoutFailure(self): ...\n def ProcessLine(self, line): ...\n def _ProcessLine(self, line): ...\n\n self.completed = False\n self._current_test = ''\n self._failure_description = []\n self._current_report_hash = ''\n self._current_report = []\n self._parsing_failures = False\n self._line_number = 0\n self._internal_error_lines = []\n self._test_status = {}\n self._memory_tool_reports = {}\n self._disabled_tests = 0\n self._flaky_tests = 0\n self._master_name_re = re.compile('\\\\[Running for master: \"([^\"]*)\"')\n self.master_name = ''\n self._test_name = re.compile(test_name_regexp)\n self._test_start = re.compile('\\\\[\\\\s+RUN\\\\s+\\\\] ' + test_name_regexp)\n self._test_ok = re.compile('\\\\[\\\\s+OK\\\\s+\\\\] ' + test_name_regexp)\n self._test_fail = re.compile('\\\\[\\\\s+FAILED\\\\s+\\\\] ' + test_name_regexp)\n self._test_passed = re.compile('\\\\[\\\\s+PASSED\\\\s+\\\\] \\\\d+ tests?.')\n self._run_test_cases_line = re.compile('\\\\[\\\\s*\\\\d+\\\\/\\\\d+\\\\]\\\\s+[0-9\\\\.]+s ' + test_name_regexp + ' .+')\n self._test_timeout = re.compile('Test timeout \\\\([0-9]+ ms\\\\) exceeded for ' + test_name_regexp)\n self._disabled = re.compile('\\\\s*YOU HAVE (\\\\d+) DISABLED TEST')\n self._flaky = re.compile('\\\\s*YOU HAVE (\\\\d+) FLAKY TEST')\n self._report_start = re.compile('### BEGIN MEMORY TOOL REPORT \\\\(error hash=#([0-9A-F]+)#\\\\)')\n self._report_end = re.compile('### END MEMORY TOOL REPORT \\\\(error hash=#([0-9A-F]+)#\\\\)')\n self._retry_message = re.compile('RETRYING FAILED TESTS:')\n self.retrying_failed = False\n self.TEST_STATUS_MAP = {'OK': TEST_SUCCESS_LABEL, 'failed': TEST_FAILURE_LABEL, 'timeout': TEST_TIMEOUT_LABEL, 'warning': TEST_WARNING_LABEL}\n", "repository": "yjbanov/chromium_build", "test_name": "testFlakyTests", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000680.py"} {"focal_file": "scripts/common/gtest_utils.py", "focal_class": "common.gtest_utils.GTestJSONParser", "focal_method": "DisabledTests", "tests": "import unittest\n\nclass Test_common_gtest_utils_GTestJSONParser_DisabledTests(unittest.TestCase):\n def testDisabledTests(self):\n parser = gtest_utils.GTestJSONParser()\n parser.ProcessJSONData({'disabled_tests': ['Test.Two'], 'global_tags': [], 'per_iteration_data': [{'Test.One': [{'status': 'SUCCESS', 'output_snippet': ''}]}]})\n self.assertEqual(['Test.One'], parser.PassedTests())\n self.assertEqual([], parser.FailedTests())\n self.assertEqual(0, parser.FlakyTests())\n self.assertEqual(1, parser.DisabledTests())\n self.assertEqual(['SUCCESS'], parser.TriesForTest('Test.One'))\n self.assertEqual(['UNKNOWN'], parser.TriesForTest('Test.Two'))\n", "method_code": " def DisabledTests(self):\n \"\"\"Returns the name of the disabled test (if there is only 1) or the number\n of disabled tests.\n \"\"\"\n return self._disabled_tests\n ", "context": "class GTestLogParser(object):\n def DisabledTests(self): ...\n def __init__(self): ...\n def GetCurrentTest(self): ...\n def _StatusOfTest(self, test): ...\n def _TestsByStatus(self, status, include_fails, include_flaky): ...\n def _RecordError(self, line, reason): ...\n def RunningTests(self): ...\n def ParsingErrors(self): ...\n def ClearParsingErrors(self): ...\n def PassedTests(self, include_fails=False, include_flaky=False): ...\n def FailedTests(self, include_fails=False, include_flaky=False): ...\n def TriesForTest(self, test): ...\n def FlakyTests(self): ...\n def FailureDescription(self, test): ...\n def MemoryToolReportHashes(self): ...\n def MemoryToolReport(self, report_hash): ...\n def CompletedWithoutFailure(self): ...\n def ProcessLine(self, line): ...\n def _ProcessLine(self, line): ...\n\n self.completed = False\n self._current_test = ''\n self._failure_description = []\n self._current_report_hash = ''\n self._current_report = []\n self._parsing_failures = False\n self._line_number = 0\n self._internal_error_lines = []\n self._test_status = {}\n self._memory_tool_reports = {}\n self._disabled_tests = 0\n self._flaky_tests = 0\n self._master_name_re = re.compile('\\\\[Running for master: \"([^\"]*)\"')\n self.master_name = ''\n self._test_name = re.compile(test_name_regexp)\n self._test_start = re.compile('\\\\[\\\\s+RUN\\\\s+\\\\] ' + test_name_regexp)\n self._test_ok = re.compile('\\\\[\\\\s+OK\\\\s+\\\\] ' + test_name_regexp)\n self._test_fail = re.compile('\\\\[\\\\s+FAILED\\\\s+\\\\] ' + test_name_regexp)\n self._test_passed = re.compile('\\\\[\\\\s+PASSED\\\\s+\\\\] \\\\d+ tests?.')\n self._run_test_cases_line = re.compile('\\\\[\\\\s*\\\\d+\\\\/\\\\d+\\\\]\\\\s+[0-9\\\\.]+s ' + test_name_regexp + ' .+')\n self._test_timeout = re.compile('Test timeout \\\\([0-9]+ ms\\\\) exceeded for ' + test_name_regexp)\n self._disabled = re.compile('\\\\s*YOU HAVE (\\\\d+) DISABLED TEST')\n self._flaky = re.compile('\\\\s*YOU HAVE (\\\\d+) FLAKY TEST')\n self._report_start = re.compile('### BEGIN MEMORY TOOL REPORT \\\\(error hash=#([0-9A-F]+)#\\\\)')\n self._report_end = re.compile('### END MEMORY TOOL REPORT \\\\(error hash=#([0-9A-F]+)#\\\\)')\n self._retry_message = re.compile('RETRYING FAILED TESTS:')\n self.retrying_failed = False\n self.TEST_STATUS_MAP = {'OK': TEST_SUCCESS_LABEL, 'failed': TEST_FAILURE_LABEL, 'timeout': TEST_TIMEOUT_LABEL, 'warning': TEST_WARNING_LABEL}\n", "repository": "yjbanov/chromium_build", "test_name": "testDisabledTests", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000681.py"} {"focal_file": "scripts/common/gtest_utils.py", "focal_class": null, "focal_method": "CompressList", "tests": "import unittest\n\nclass Test_CompressList(unittest.TestCase):\n def testCompressList(self):\n CompressList = gtest_utils.CompressList\n self.assertEqual(['foo'], CompressList([1, 2, 3, 4], 0, 'foo'))\n self.assertEqual(['foo', 4], CompressList([1, 2, 3, 4], 1, 'foo'))\n self.assertEqual([1, 'foo', 4], CompressList([1, 2, 3, 4], 2, 'foo'))\n self.assertEqual([1, 'foo', 3, 4], CompressList([1, 2, 3, 4], 3, 'foo'))\n self.assertEqual([1, 2, 3, 4], CompressList([1, 2, 3, 4], 4, 'foo'))\n self.assertEqual([1, 2, 3, 4], CompressList([1, 2, 3, 4], 5, 'foo'))\n self.assertEqual([1, 2, 3, 4], CompressList([1, 2, 3, 4], 6, 'foo'))\n", "method_code": "def CompressList(lines, max_length, middle_replacement):\n \"\"\"Ensures that |lines| is no longer than |max_length|. If |lines| need to\n be compressed then the middle items are replaced by |middle_replacement|.\n \"\"\"\n if len(lines) <= max_length:\n return lines\n remove_from_start = max_length / 2\n return lines[:remove_from_start] + [middle_replacement] + lines[len(lines) - (max_length - remove_from_start):]", "context": "def CompressList(lines, max_length, middle_replacement): ...\ndef CompressList(lines, max_length, middle_replacement): ...\n", "repository": "yjbanov/chromium_build", "test_name": "testCompressList", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000682.py"} {"focal_file": "scripts/common/gerrit/object.py", "focal_class": null, "focal_method": "revisionInfoForNumber", "tests": "import unittest\n\nclass Test_revisionInfoForNumber(unittest.TestCase):\n def testRevisionInfoForNumber(self):\n self.assertEqual(self.ci.revisionInfoForNumber(3), self._buildRevisionInfo(self.ci, 'THIRD'))\n self.assertEqual(self.ci.revisionInfoForNumber(2), self._buildRevisionInfo(self.ci, 'SECOND'))\n self.assertEqual(self.ci.revisionInfoForNumber(1), self._buildRevisionInfo(self.ci, 'FIRST'))\n", "method_code": " def revisionInfoForNumber(self, value):\n \"\"\"Gets the revision hash that corresponds to a patch set number.\n \n Args:\n value: (int) the revision number value\n Returns: (RevisionInfo/None) The RevisionInfo for 'value', or None if one\n is not defined.\n \"\"\"\n return self._revision_number_map.get(value)\n ", "context": "class ChangeInfo(GerritObject):\n def revisionInfoForNumber(self, value): ...\n def _revisions(self): ...\n def _revision_number_map(self): ...\n def parse_id(value): ...\n def id_tuple(self): ...\n def messages(self): ...\n def unique_id(self): ...\n def update_time(self): ...\n def created_time(self): ...\n def revisions(self): ...\n def latest_revision(self): ...\n def owner(self): ...\n def label(self, name): ...\n def labels(self): ...\n def __repr__(self): ...\n\n __gerrit_object_name__ = 'ChangeInfo'\n", "repository": "yjbanov/chromium_build", "test_name": "testRevisionInfoForNumber", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000683.py"} {"focal_file": "scripts/common/gerrit/object.py", "focal_class": null, "focal_method": "addLabel", "tests": "import unittest\n\nclass Test_addLabel(unittest.TestCase):\n def testAddLabel(self):\n ri = self.ri.addLabel('Code-Review', 1)\n ri = ri.addLabel('Other-Label', -1)\n self.assertEqual(ri.data, {'message': 'Test', 'strict_labels': True, 'drafts': ReviewInput.DRAFTS_DELETE, 'notify': ReviewInput.NOTIFY_NONE, 'on_behalf_of': 12345, 'labels': {'Code-Review': 1, 'Other-Label': -1}})\n", "method_code": " def addLabel(self, label, value):\n \"\"\"Adds a label/value pair\n \n Args:\n label: (str) the name of the label (e.g., 'Code-Review')\n value: (int) the label value (e.g., -1)\n Returns: (ReviewInput) A new ReviewInput with the specified labels set.\n \"\"\"\n nlabels = self.get('labels')\n if nlabels is None:\n nlabels = {}\n else:\n nlabels = nlabels.mutableDict()\n nlabels[label] = value\n return self.extend(labels=nlabels)\n ", "context": "class ReviewInput(GerritObject):\n def addLabel(self, label, value): ...\n def New(cls, message=None, strict_labels=None, drafts=None, notify=None, on_behalf_of=None): ...\n\n __gerrit_object_name__ = 'ReviewInput'\n DRAFTS_DELETE = 'DELETE'\n DRAFTS_PUBLISH = 'PUBLISH'\n DRAFTS_KEEP = 'KEEP'\n NOTIFY_NONE = 'NONE'\n NOTIFY_OWNER = 'OWNER'\n NOTIFY_OWNER_REVIEWERS = 'OWNER_REVIEWERS'\n NOTIFY_ALL = 'ALL'\n", "repository": "yjbanov/chromium_build", "test_name": "testAddLabel", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000684.py"} {"focal_file": "scripts/common/gerrit/query.py", "focal_class": null, "focal_method": "New", "tests": "import unittest\n\nclass Test_New(unittest.TestCase):\n def testNestedQueryBuilders(self):\n self.assertEqual(str(QueryBuilder.New('status:open', QueryBuilder.NewOR('label:Code-Review=+0', 'status:open'), 'test1', 'test2')), 'status:open+(label:Code-Review%3D%2B0+OR+status:open)+test1+test2')\n self.assertEqual(str(QueryBuilder.New('status:open', QueryBuilder.NewOR('label:Code-Review=+0', 'status:open', QueryBuilder.NewAND('status:new', 'label:Code-Review=-0')), 'test1', 'test2')), 'status:open+(label:Code-Review%3D%2B0+OR+status:open+OR+(status:new+AND+label:Code-Review%3D-0))+test1+test2')\n self.assertEqual(str(QueryBuilder.New('status:open', QueryBuilder.New(), 'test1', 'test2')), 'status:open+test1+test2')\n self.assertEqual(str(QueryBuilder.New(QueryBuilder.New(), QueryBuilder.New(), QueryBuilder.New(), QueryBuilder.New())), '')\n", "method_code": " def New(cls, *terms):\n return cls._New(terms)\n ", "context": "class QueryBuilder(object):\n @classmethod\n def New(cls, *terms): ...\n def __init__(self, terms, operator): ...\n def _New(cls, terms, operator=None): ...\n def NewOR(cls, *terms): ...\n def NewAND(cls, *terms): ...\n def _prepareTerm(cls, value): ...\n def _prepareString(cls, value, quoted=False): ...\n def _prepareSelector(cls, key, value): ...\n def _cloneWithTerms(self, *terms): ...\n def add(self, *values): ...\n def addSelector(self, key, value): ...\n def addQuoted(self, value): ...\n def addUnquoted(self, value): ...\n def _formatQuery(cls, terms): ...\n def termiter(self): ...\n def __len__(self): ...\n def __str__(self): ...\n\n self._terms = tuple(terms)\n self._operator = operator\n", "repository": "yjbanov/chromium_build", "test_name": "testNestedQueryBuilders", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000685.py"} {"focal_file": "scripts/common/gerrit/time.py", "focal_class": null, "focal_method": "ParseGerritTime", "tests": "import unittest\n\nclass Test_ParseGerritTime(unittest.TestCase):\n def testParseGerritTime(self):\n self.assertEquals(ParseGerritTime('2014-03-11 00:20:08.946000000'), datetime(year=2014, month=3, day=11, hour=0, minute=20, second=8, microsecond=946000))\n", "method_code": "def ParseGerritTime(value):\n \"\"\"Parses a Gerrit-formatted timestamp into a Python 'datetime'.\n From Gerrit API documentation:\n `Timestamps are given in UTC and have the format\n \"yyyy-mm-dd hh:mm:ss.fffffffff\" where \"ffffffffff\" indicates the\n nanoseconds.`\n\n Args:\n value: (str) the value to parse\n\n Return: A Python 'datetime' object parsed from 'value'\n \"\"\"\n parts = value.split('.')\n dt = datetime.datetime.strptime(parts[0], GERRIT_TIMESTAMP_FMT)\n if len(parts) > 1:\n dt += datetime.timedelta(microseconds=int(float('0.%s' % parts[1]) * 1000000.0))\n return dt", "context": "def ParseGerritTime(value): ...\ndef ParseGerritTime(value): ...\ndef ToGerritTime(value): ...\n", "repository": "yjbanov/chromium_build", "test_name": "testParseGerritTime", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000686.py"} {"focal_file": "scripts/common/gerrit/time.py", "focal_class": null, "focal_method": "ToGerritTime", "tests": "import unittest\n\nclass Test_ToGerritTime(unittest.TestCase):\n def testToGerritTime(self):\n self.assertEquals(ToGerritTime(datetime(year=2014, month=3, day=11, hour=0, minute=20, second=8, microsecond=946000)), '2014-03-11 00:20:08.946000000')\n", "method_code": "def ToGerritTime(value):\n \"\"\"Converts a Python 'datetime' to a Gerrit-formatted timestamp. See\n 'ParseGerritTime' for details.\n\n Args:\n value: (datetime.datetime) the value to convert\n Return: A Gerrit timestamp string\n \"\"\"\n ns_str = str(value.microsecond * 1000)\n return '%s.%s' % (value.strftime(GERRIT_TIMESTAMP_FMT), ns_str)", "context": "def ToGerritTime(value): ...\ndef ParseGerritTime(value): ...\ndef ToGerritTime(value): ...\n", "repository": "yjbanov/chromium_build", "test_name": "testToGerritTime", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000687.py"} {"focal_file": "scripts/master/buildbucket/changestore.py", "focal_class": null, "focal_method": "_find_change_in_db", "tests": "import unittest\n\nclass Test_find_change_in_db(unittest.TestCase):\n def test_find_change_in_db(self):\n change = Mock()\n rev = 123\n change_id = 'abc'\n change.properties.getProperty.return_value = {'change_id': change_id}\n self.buildbot.get_change_by_id.return_value = change\n self.buildbot.find_changes_by_revision.return_value = [change.changeid]\n result = run_deferred(self.store._find_change_in_db((rev, change_id)))\n self.assertEqual(result, change)\n change.properties.getProperty.assert_any_call(common.INFO_PROPERTY)\n self.buildbot.find_changes_by_revision.assert_called_once_with(rev)\n self.buildbot.get_change_by_id.assert_called_once_with(change.changeid)\n", "method_code": " def _find_change_in_db(self, revision_and_id):\n \"\"\"Searches for an existing Change object in the database.\n \n Args:\n revision_and_id: a tuple of change revision and buildbucket-level change\n id.\n \n Every Change object has a revision attribute. The buildbucket-level change\n id is stored as common.INFO_PROPERTY/common.BUILDBUCKET_CHANGE_ID_PROPERTY\n property.\n \n This function runs a db query to find Changes by revision and then filters\n them by buildbucket-level change id. Presumably, there won't be many changes\n with the same revision, which is a git sha or svn revision number,\n so filtering by id in memory is OK.\n \n Returns:\n buildbot.changes.change.Change object as Deferred.\n \"\"\"\n revision, buildbucket_change_id = revision_and_id\n buildbot_change_ids = (yield self.buildbot.find_changes_by_revision(revision))\n for buildbot_change_id in buildbot_change_ids:\n change = (yield self.buildbot.get_change_by_id(buildbot_change_id))\n info = change.properties.getProperty(common.INFO_PROPERTY)\n if info is None:\n continue\n prop_value = info.get(common.BUILDBUCKET_CHANGE_ID_PROPERTY)\n if str(prop_value) == str(buildbucket_change_id):\n defer.returnValue(change)\n return\n ", "context": "class ChangeStore(object):\n @defer.inlineCallbacks\n def _find_change_in_db(self, revision_and_id): ...\n def __init__(self, buildbot_gateway): ...\n def _insert_change(self, buildbucket_change): ...\n def _find_change(self, revision, buildbucket_change_id): ...\n def get_change(self, buildbucket_change): ...\n def _insert_source_stamp(self, buildbucket_changes): ...\n def get_source_stamp(self, buildbucket_changes, cache=None): ...\n\n self.buildbot = buildbot_gateway\n self._find_change_cache = self.buildbot.get_cache(CHANGE_CACHE_NAME, self._find_change_in_db)\n", "repository": "yjbanov/chromium_build", "test_name": "test_find_change_in_db", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000688.py"} {"focal_file": "scripts/master/buildbucket/changestore.py", "focal_class": null, "focal_method": "_find_change", "tests": "import unittest\n\nclass Test_find_change(unittest.TestCase):\n def test_find_change(self):\n m = Mock()\n change = self.store._find_change(m.revision, m.change_id)\n cache = self.buildbot.change_cache\n cache.get.assert_called_once_with((m.revision, m.change_id))\n self.assertEqual(change, cache.get.return_value)\n", "method_code": " def _find_change(self, revision, buildbucket_change_id):\n \"\"\"Searches for a Change by revision and change_key. Uses cache.\"\"\"\n assert revision\n assert buildbucket_change_id\n return self._find_change_cache.get((revision, buildbucket_change_id))\n ", "context": "class ChangeStore(object):\n def _find_change(self, revision, buildbucket_change_id): ...\n def __init__(self, buildbot_gateway): ...\n def _insert_change(self, buildbucket_change): ...\n def _find_change_in_db(self, revision_and_id): ...\n def get_change(self, buildbucket_change): ...\n def _insert_source_stamp(self, buildbucket_changes): ...\n def get_source_stamp(self, buildbucket_changes, cache=None): ...\n\n self.buildbot = buildbot_gateway\n self._find_change_cache = self.buildbot.get_cache(CHANGE_CACHE_NAME, self._find_change_in_db)\n", "repository": "yjbanov/chromium_build", "test_name": "test_find_change", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000689.py"} {"focal_file": "scripts/master/buildbucket/changestore.py", "focal_class": null, "focal_method": "get_change", "tests": "import unittest\n\nclass Test_get_change(unittest.TestCase):\n def test_get_change(self):\n cache = self.buildbot.change_cache\n cache.get.return_value = None\n result = run_deferred(self.store.get_change(self.buildbucket_change))\n info = json.dumps({common.BUILDBUCKET_CHANGE_ID_PROPERTY: '1'}, sort_keys=True)\n self.buildbot.add_change_to_db.assert_called_once_with(author=self.buildbucket_change['author']['email'], files=[], comments=self.buildbucket_change['message'], revision=self.buildbucket_change['revision'], when_timestamp=datetime.datetime(2014, 12, 22), branch=self.buildbucket_change['branch'], category=common.CHANGE_CATEGORY, revlink=self.buildbucket_change['url'], properties={common.INFO_PROPERTY: (info, 'Change')}, repository=self.buildbucket_change.get('repo_url'), project=self.buildbucket_change.get('project'))\n self.assertEqual(result, self.buildbot.get_change_by_id.return_value)\n\n def test_get_change_without_id(self):\n cache = self.buildbot.change_cache\n cache.get.return_value = None\n result = run_deferred(self.store.get_change({'author': {'email': 'johndoe@chromium.org'}, 'message': 'Hello world'}))\n expected_info = json.dumps({'change_id': None})\n self.buildbot.add_change_to_db.assert_called_once_with(author='johndoe@chromium.org', files=[], comments='Hello world', revision='', when_timestamp=None, branch=None, category=common.CHANGE_CATEGORY, revlink='', properties={common.INFO_PROPERTY: (expected_info, 'Change')}, repository='', project='')\n self.assertEqual(result, self.buildbot.get_change_by_id.return_value)\n", "method_code": " def get_change(self, buildbucket_change):\n \"\"\"Returns an existing or new Buildbot Change for a buildbucket change.\n \n Args:\n buildbucket_change (dict): a change found in build parameters.\n \n Returns:\n buildbot.changes.change.Change object as Deferred.\n \"\"\"\n buildbot_change = None\n if buildbucket_change.get('revision') and buildbucket_change.get('id'):\n buildbot_change = (yield self._find_change(buildbucket_change['revision'], buildbucket_change['id']))\n if buildbot_change is None:\n change_id = (yield self._insert_change(buildbucket_change))\n buildbot_change = (yield self.buildbot.get_change_by_id(change_id))\n defer.returnValue(buildbot_change)\n ", "context": "class ChangeStore(object):\n @defer.inlineCallbacks\n def get_change(self, buildbucket_change): ...\n def __init__(self, buildbot_gateway): ...\n def _insert_change(self, buildbucket_change): ...\n def _find_change_in_db(self, revision_and_id): ...\n def _find_change(self, revision, buildbucket_change_id): ...\n def _insert_source_stamp(self, buildbucket_changes): ...\n def get_source_stamp(self, buildbucket_changes, cache=None): ...\n\n self.buildbot = buildbot_gateway\n self._find_change_cache = self.buildbot.get_cache(CHANGE_CACHE_NAME, self._find_change_in_db)\n", "repository": "yjbanov/chromium_build", "test_name": "test_get_change", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000690.py"} {"focal_file": "scripts/master/buildbucket/changestore.py", "focal_class": null, "focal_method": "get_source_stamp", "tests": "import unittest\n\nclass Test_get_source_stamp(unittest.TestCase):\n def test_get_source_stamp(self):\n result = run_deferred(self.store.get_source_stamp([self.buildbucket_change]))\n cache = self.buildbot.change_cache\n cache.get.assert_called_once_with((self.buildbucket_change['revision'], self.buildbucket_change['id']))\n bb_change = cache.get.return_value\n self.buildbot.insert_source_stamp_to_db.assert_called_once_with(branch=bb_change.branch, revision=bb_change.revision, repository=bb_change.repository, project=bb_change.project, changeids=[bb_change.number])\n self.assertEqual(result, self.buildbot.insert_source_stamp_to_db.return_value)\n\n def test_get_source_stamp_with_cache(self):\n ssid = Mock()\n ss_cache = {(self.buildbucket_change['id'],): ssid}\n result = run_deferred(self.store.get_source_stamp([self.buildbucket_change], cache=ss_cache))\n self.assertFalse(self.buildbot.change_cache.get.called)\n self.assertFalse(self.buildbot.insert_source_stamp_to_db.called)\n self.assertEqual(result, ssid)\n", "method_code": " def get_source_stamp(self, buildbucket_changes, cache=None):\n \"\"\"Returns a new or existing SourceStamp for the list of changes.\n \n Returns:\n SourceStamp ID as Deferred.\n \"\"\"\n assert isinstance(buildbucket_changes, list)\n if cache is not None and all(('id' in c for c in buildbucket_changes)):\n cache_key = tuple(sorted([c['id'] for c in buildbucket_changes]))\n ssid = cache.get(cache_key)\n if ssid:\n defer.returnValue(ssid)\n return\n ssid = (yield self._insert_source_stamp(buildbucket_changes))\n if cache is not None:\n cache[cache_key] = ssid\n defer.returnValue(ssid)\n ", "context": "class ChangeStore(object):\n @defer.inlineCallbacks\n def get_source_stamp(self, buildbucket_changes, cache=None): ...\n def __init__(self, buildbot_gateway): ...\n def _insert_change(self, buildbucket_change): ...\n def _find_change_in_db(self, revision_and_id): ...\n def _find_change(self, revision, buildbucket_change_id): ...\n def get_change(self, buildbucket_change): ...\n def _insert_source_stamp(self, buildbucket_changes): ...\n\n self.buildbot = buildbot_gateway\n self._find_change_cache = self.buildbot.get_cache(CHANGE_CACHE_NAME, self._find_change_in_db)\n", "repository": "yjbanov/chromium_build", "test_name": "test_get_source_stamp", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000691.py"} {"focal_file": "scripts/master/buildbucket/common.py", "focal_class": null, "focal_method": "parse_info_property", "tests": "import unittest\n\nclass Test_parse_info_property(unittest.TestCase):\n def test_parse_info_property_succeed(self):\n value, expected = ({'build': {'foo': 'bar'}}, {'build': {'foo': 'bar'}})\n self.assertDictEqual(common.parse_info_property(value), expected)\n value, expected = ({'build': '{\"foo\": \"bar\"}'}, {'build': {'foo': 'bar'}})\n self.assertDictEqual(common.parse_info_property(value), expected)\n value, expected = ('{\"build\": {\"foo\": \"bar\"}}', {'build': {'foo': 'bar'}})\n self.assertDictEqual(common.parse_info_property(value), expected)\n\n def test_parse_info_property_fail(self):\n value = 'invalid json'\n self.assertRaises(ValueError, lambda: common.parse_info_property(value))\n value = {'build': 'invalid json'}\n self.assertRaises(ValueError, lambda: common.parse_info_property(value))\n value = '42'\n self.assertRaises(ValueError, lambda: common.parse_info_property(value))\n", "method_code": "def parse_info_property(value):\n \"\"\"Parses the buildbot build property containing buildbucket INFO.\"\"\"\n try:\n if isinstance(value, dict):\n if isinstance(value.get('build'), basestring):\n value['build'] = json.loads(value['build'])\n return value\n parsed = json.loads(value)\n if not isinstance(parsed, dict):\n raise ValueError('must be a JSON dict')\n return parsed\n except ValueError as e:\n msg = 'failed to parse %s property \"%s\": %s' % (INFO_PROPERTY, value, e)\n log(msg, logging.ERROR)\n raise ValueError(msg)", "context": "def parse_info_property(value): ...\ndef log(message, level=None): ...\ndef log_on_error(deferred, msg_prefix=None): ...\ndef datetime_to_timestamp(value): ...\ndef timestamp_to_datetime(value): ...\ndef parse_info_property(value): ...\n", "repository": "yjbanov/chromium_build", "test_name": "test_parse_info_property_succeed", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000692.py"} {"focal_file": "scripts/master/buildbucket/integration.py", "focal_class": null, "focal_method": "poll_builds", "tests": "import unittest\n\nclass Test_poll_builds(unittest.TestCase):\n def test_no_builds(self):\n with self.create_integrator():\n self.buildbucket.api.peek.return_value = {'builds': []}\n run_deferred(self.integrator.poll_builds())\n self.assertFalse(self.buildbot.add_build_request.called)\n self.assertTrue(self.buildbucket.api.peek.called)\n self.assertFalse(self.buildbucket.api.lease.called)\n", "method_code": " def poll_builds(self):\n \"\"\"Polls buildbucket and schedules builds.\"\"\"\n assert self.started\n start_cursor = None\n ssid_cache = {}\n yield self._ensure_leases_loaded()\n max_lease_count = self.get_max_lease_count()\n if len(self._leases) >= max_lease_count:\n self.log('Not polling because reached lease count limit: %d/%d' % (len(self._leases), max_lease_count), level=logging.DEBUG)\n return\n max_builds = min(MAX_MAX_BUILDS, (max_lease_count - len(self._leases)) * 3)\n self.log('polling builds...')\n while len(self._leases) < self.get_max_lease_count():\n peek_resp = (yield self.buildbucket_service.api.peek(bucket=self.buckets, max_builds=max_builds, start_cursor=start_cursor))\n if self._check_error(peek_resp):\n break\n start_cursor = peek_resp.get('next_cursor')\n builds = peek_resp.get('builds', [])\n builds = filter(None, builds)\n self.log('got %d builds' % len(builds))\n while builds:\n max_schedule = self.get_max_lease_count() - len(self._leases)\n if max_schedule <= 0:\n self.log('Reached the maximum number of leases', level=logging.DEBUG)\n return\n to_schedule, builds = (builds[:max_schedule], builds[max_schedule:])\n yield [self._try_schedule_build(b, ssid_cache) for b in to_schedule]\n if not start_cursor:\n break\n ", "context": "class BuildBucketIntegrator(object):\n @deferredLocked('poll_lock')\n @inlineCallbacks\n def poll_builds(self): ...\n def __init__(self, buckets, build_params_hook=None, max_lease_count=None, heartbeat_interval=None): ...\n def get_max_lease_count(self): ...\n def log(self, message, level=None): ...\n def start(self, buildbot, buildbucket_service, change_store_factory=None): ...\n def _get_leases_from_db(self): ...\n def _ensure_leases_loaded(self): ...\n def stop(self): ...\n def _validate_change(change): ...\n def _validate_build(self, build): ...\n def _check_error(self, res): ...\n def _try_lease_build(self, build): ...\n def _strip_build_def(build): ...\n def _schedule(self, builder_name, properties, build, ssid): ...\n def _try_schedule_build(self, build, ssid_cache): ...\n def is_buildbucket_build(build): ...\n def _get_build_def(build): ...\n def send_heartbeats(self): ...\n def clean_completed_build_requests(self): ...\n def _do_until_stopped(self, interval, fn): ...\n def _stop_build(self, build, reason): ...\n def _leased_build_call(self, method_name, build, body): ...\n def on_build_started(self, build): ...\n def on_build_finished(self, build, status): ...\n\n self.buckets = buckets[:]\n self.build_params_hook = build_params_hook\n self.buildbot = None\n self.buildbucket_service = None\n self._find_change_cache = None\n self.started = False\n self.changes = None\n self.poll_lock = defer.DeferredLock()\n self._max_lease_count = max_lease_count\n self._leases = None\n self.heartbeat_interval = heartbeat_interval or DEFAULT_HEARTBEAT_INTERVAL\n", "repository": "yjbanov/chromium_build", "test_name": "test_no_builds", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000693.py"} {"focal_file": "scripts/master/buildbucket/integration.py", "focal_class": null, "focal_method": "clean_completed_build_requests", "tests": "import unittest\n\nclass Test_clean_completed_build_requests(unittest.TestCase):\n def test_clean_completed_build_requests(self):\n with self.create_integrator():\n\n def make_build_request(complete, has_builds):\n result = Mock()\n result.is_failed.return_value = complete\n result.has_builds.return_value = has_builds\n return result\n self.integrator._leases = {'1': {'lease_key': LEASE_KEY, 'build_request': make_build_request(True, False)}, '2': {'lease_key': LEASE_KEY, 'build_request': make_build_request(False, False)}, '3': {'lease_key': LEASE_KEY, 'build_request': make_build_request(True, True)}}\n run_deferred(self.integrator.clean_completed_build_requests())\n self.assertEqual(1, self.buildbucket.api.cancel.call_count)\n self.buildbucket.api.cancel.assert_called_once_with(id='1')\n", "method_code": " def clean_completed_build_requests(self):\n \"\"\"Deletes leases that point to cancelled build requests.\n \n Since Buildbot's requestCancelled notifcation does not work,\n we have to periodically check for canceled build requests.\n \"\"\"\n if not self._leases:\n return\n for build_id, lease in self._leases.items():\n request = lease['build_request']\n is_cancelled = (yield request.is_failed()) and (not (yield request.has_builds()))\n if not is_cancelled:\n continue\n if build_id not in self._leases:\n continue\n self.log('Build request %r is complete. Deleting lease for build %s' % (request, build_id), level=logging.DEBUG)\n del self._leases[build_id]\n yield self.buildbucket_service.api.cancel(id=build_id)\n ", "context": "class BuildBucketIntegrator(object):\n @inlineCallbacks\n def clean_completed_build_requests(self): ...\n def __init__(self, buckets, build_params_hook=None, max_lease_count=None, heartbeat_interval=None): ...\n def get_max_lease_count(self): ...\n def log(self, message, level=None): ...\n def start(self, buildbot, buildbucket_service, change_store_factory=None): ...\n def _get_leases_from_db(self): ...\n def _ensure_leases_loaded(self): ...\n def stop(self): ...\n def _validate_change(change): ...\n def _validate_build(self, build): ...\n def _check_error(self, res): ...\n def _try_lease_build(self, build): ...\n def _strip_build_def(build): ...\n def _schedule(self, builder_name, properties, build, ssid): ...\n def _try_schedule_build(self, build, ssid_cache): ...\n def poll_builds(self): ...\n def is_buildbucket_build(build): ...\n def _get_build_def(build): ...\n def send_heartbeats(self): ...\n def _do_until_stopped(self, interval, fn): ...\n def _stop_build(self, build, reason): ...\n def _leased_build_call(self, method_name, build, body): ...\n def on_build_started(self, build): ...\n def on_build_finished(self, build, status): ...\n\n self.buckets = buckets[:]\n self.build_params_hook = build_params_hook\n self.buildbot = None\n self.buildbucket_service = None\n self._find_change_cache = None\n self.started = False\n self.changes = None\n self.poll_lock = defer.DeferredLock()\n self._max_lease_count = max_lease_count\n self._leases = None\n self.heartbeat_interval = heartbeat_interval or DEFAULT_HEARTBEAT_INTERVAL\n", "repository": "yjbanov/chromium_build", "test_name": "test_clean_completed_build_requests", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000694.py"} {"focal_file": "scripts/master/buildbucket/integration.py", "focal_class": null, "focal_method": "on_build_started", "tests": "import unittest\n\nclass Test_on_build_started(unittest.TestCase):\n def test_build_started(self):\n with self.create_integrator():\n build = self.mock_existing_build(put_build_to_lease=False)\n self.buildbucket.api.start.return_value = {}\n self.integrator.on_build_started(build)\n self.buildbucket.api.start.assert_called_once_with(id=build.id, body={'lease_key': LEASE_KEY, 'url': self.buildbot.get_build_url.return_value})\n\n def test_build_started_error_response(self):\n with self.create_integrator():\n build = self.mock_existing_build(put_build_to_lease=False)\n self.buildbucket.api.start.return_value = {'error': {'reason': 'BAD', 'message': 'Something is bad'}}\n self.integrator.on_build_started(build)\n self.assertTrue(self.buildbot.stop_build.called)\n", "method_code": " def on_build_started(self, build):\n assert self.started\n build_def = self._get_build_def(build)\n if not build_def:\n return\n build_id = build_def['id']\n builder = build.getBuilder()\n self.log('Build %s started as %s/%d' % (build_id, builder.getName(), build.getNumber()))\n yield self._ensure_leases_loaded()\n if build_id not in self._leases:\n self._stop_build(build, 'Build started, but it is not among leases.')\n lease = self._leases.get(build_id)\n if not lease or lease['key'] != build_def['lease_key']:\n self._stop_build(build, 'Build started, but it is lease key is not current.')\n return\n assert not lease.get('build')\n lease['build'] = build\n resp = (yield self._leased_build_call('start', build, {'url': self.buildbot.get_build_url(build)}))\n if 'error' in resp:\n stop_reason = 'Build has started, but an attempt to notify buildbucket about it has failed with error \"%s\" (reason: %s).' % (resp['error'].get('message'), resp['error'].get('reason'))\n self._stop_build(build, stop_reason)\n ", "context": "class BuildBucketIntegrator(object):\n @inlineCallbacks\n def on_build_started(self, build): ...\n def __init__(self, buckets, build_params_hook=None, max_lease_count=None, heartbeat_interval=None): ...\n def get_max_lease_count(self): ...\n def log(self, message, level=None): ...\n def start(self, buildbot, buildbucket_service, change_store_factory=None): ...\n def _get_leases_from_db(self): ...\n def _ensure_leases_loaded(self): ...\n def stop(self): ...\n def _validate_change(change): ...\n def _validate_build(self, build): ...\n def _check_error(self, res): ...\n def _try_lease_build(self, build): ...\n def _strip_build_def(build): ...\n def _schedule(self, builder_name, properties, build, ssid): ...\n def _try_schedule_build(self, build, ssid_cache): ...\n def poll_builds(self): ...\n def is_buildbucket_build(build): ...\n def _get_build_def(build): ...\n def send_heartbeats(self): ...\n def clean_completed_build_requests(self): ...\n def _do_until_stopped(self, interval, fn): ...\n def _stop_build(self, build, reason): ...\n def _leased_build_call(self, method_name, build, body): ...\n def on_build_finished(self, build, status): ...\n\n self.buckets = buckets[:]\n self.build_params_hook = build_params_hook\n self.buildbot = None\n self.buildbucket_service = None\n self._find_change_cache = None\n self.started = False\n self.changes = None\n self.poll_lock = defer.DeferredLock()\n self._max_lease_count = max_lease_count\n self._leases = None\n self.heartbeat_interval = heartbeat_interval or DEFAULT_HEARTBEAT_INTERVAL\n", "repository": "yjbanov/chromium_build", "test_name": "test_build_started", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000695.py"} {"focal_file": "scripts/master/buildbucket/integration.py", "focal_class": null, "focal_method": "on_build_finished", "tests": "import unittest\n\nclass Test_on_build_finished(unittest.TestCase):\n def test_build_failed(self):\n with self.create_integrator():\n build = self.mock_existing_build()\n self.buildbucket.api.fail.return_value = {}\n run_deferred(self.integrator.on_build_finished(build, 'FAILURE'))\n self.assertFalse(build.id in self.integrator._leases)\n self.buildbucket.api.fail.assert_called_once_with(id=build.id, body={'lease_key': LEASE_KEY, 'failure_reason': 'BUILD_FAILURE', 'result_details_json': build.expected_result_details_json})\n\n def test_build_retried(self):\n with self.create_integrator():\n build = self.mock_existing_build()\n self.integrator.stop()\n run_deferred(self.integrator.on_build_finished(build, 'RETRY'))\n self.assertTrue(build.id in self.integrator._leases)\n self.assertFalse(self.buildbucket.api.fail.called)\n\n def test_build_skipped(self):\n with self.create_integrator():\n build = self.mock_existing_build()\n run_deferred(self.integrator.on_build_finished(build, 'SKIPPED'))\n self.assertFalse(build.id in self.integrator._leases)\n self.assertFalse(self.buildbucket.api.fail.called)\n", "method_code": " def on_build_finished(self, build, status):\n assert status in ('SUCCESS', 'FAILURE', 'EXCEPTION', 'RETRY', 'SKIPPED')\n build_def = self._get_build_def(build)\n if not build_def:\n return\n build_id = build_def['id']\n assert self.is_buildbucket_build(build)\n self.log('Build %s finished with status \"%s\"' % (build_id, status), level=logging.DEBUG)\n yield self._ensure_leases_loaded()\n if build_id not in self._leases:\n self.log('build %s is not among current leases' % build_id, level=logging.WARNING)\n elif status != 'RETRY':\n del self._leases[build_id]\n if status == 'RETRY':\n return\n if status == 'SKIPPED':\n return\n if not self.started:\n self.log('BuildBucketIntegrator.on_build_finished: cannot proceed because the integrator is stopped', level=logging.WARNING)\n return\n properties_to_send = build.getProperties().asDict()\n properties_to_send = {k: v for k, (v, s) in properties_to_send.iteritems()}\n del properties_to_send[common.INFO_PROPERTY]\n body = {'result_details_json': json.dumps({'properties': properties_to_send}, sort_keys=True)}\n if status == 'SUCCESS':\n yield self._leased_build_call('succeed', build, body)\n else:\n body['failure_reason'] = 'BUILD_FAILURE' if status == 'FAILURE' else 'INFRA_FAILURE'\n yield self._leased_build_call('fail', build, body)\n ", "context": "class BuildBucketIntegrator(object):\n @inlineCallbacks\n def on_build_finished(self, build, status): ...\n def __init__(self, buckets, build_params_hook=None, max_lease_count=None, heartbeat_interval=None): ...\n def get_max_lease_count(self): ...\n def log(self, message, level=None): ...\n def start(self, buildbot, buildbucket_service, change_store_factory=None): ...\n def _get_leases_from_db(self): ...\n def _ensure_leases_loaded(self): ...\n def stop(self): ...\n def _validate_change(change): ...\n def _validate_build(self, build): ...\n def _check_error(self, res): ...\n def _try_lease_build(self, build): ...\n def _strip_build_def(build): ...\n def _schedule(self, builder_name, properties, build, ssid): ...\n def _try_schedule_build(self, build, ssid_cache): ...\n def poll_builds(self): ...\n def is_buildbucket_build(build): ...\n def _get_build_def(build): ...\n def send_heartbeats(self): ...\n def clean_completed_build_requests(self): ...\n def _do_until_stopped(self, interval, fn): ...\n def _stop_build(self, build, reason): ...\n def _leased_build_call(self, method_name, build, body): ...\n def on_build_started(self, build): ...\n\n self.buckets = buckets[:]\n self.build_params_hook = build_params_hook\n self.buildbot = None\n self.buildbucket_service = None\n self._find_change_cache = None\n self.started = False\n self.changes = None\n self.poll_lock = defer.DeferredLock()\n self._max_lease_count = max_lease_count\n self._leases = None\n self.heartbeat_interval = heartbeat_interval or DEFAULT_HEARTBEAT_INTERVAL\n", "repository": "yjbanov/chromium_build", "test_name": "test_build_failed", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000696.py"} {"focal_file": "scripts/slave/chromium_commands.py", "focal_class": null, "focal_method": "parseGotRevision", "tests": "import unittest\n\nclass Test_parseGotRevision(unittest.TestCase):\n def testParseGotRevision_NoRevisions(self):\n gclient = TestableGClient('hello world!')\n actual = gclient.parseGotRevision()\n expected = {}\n self.assertEqual(expected, actual)\n\n def testParseGotRevision_Checkout(self):\n gclient = TestableGClient(SVN_CHECKOUT_STDOUT)\n actual = gclient.parseGotRevision()\n expected = {'got_chromium_revision': '12345', 'got_nacl_revision': '98765', 'got_revision': '12345', 'got_webkit_revision': '67890', 'got_webrtc_revision': '4297'}\n self.assertEqual(expected, actual)\n\n def testParseGotRevision_Update(self):\n gclient = TestableGClient(SVN_UPDATE_STDOUT)\n actual = gclient.parseGotRevision()\n expected = {'got_chromium_revision': '12345', 'got_nacl_revision': '98765', 'got_revision': '12345', 'got_webkit_revision': '67890', 'got_webrtc_revision': '4297'}\n self.assertEqual(expected, actual)\n\n def testParseGotRevision_UpdateNoChange(self):\n gclient = TestableGClient(SVN_UPDATE_NO_CHANGE_STDOUT)\n actual = gclient.parseGotRevision()\n expected = {'got_chromium_revision': '12345', 'got_nacl_revision': '98765', 'got_revision': '12345', 'got_webkit_revision': '67890', 'got_webrtc_revision': '4297'}\n self.assertEqual(expected, actual)\n\n def testParseGotRevision_GClientSyncNoChange(self):\n gclient = TestableGClient(GCLIENT_SYNC_NO_CHANGE_STDOUT)\n actual = gclient.parseGotRevision()\n expected = {'got_chromium_revision': '12345', 'got_nacl_revision': '98765', 'got_revision': '12345', 'got_webkit_revision': '67890', 'got_webrtc_revision': '4297'}\n self.assertEqual(expected, actual)\n\n def testParseGotRevision_MulitJob(self):\n gclient = TestableGClient(stdout=GCLIENT_SYNC_MULTI_JOB_STDOUT)\n actual = gclient.parseGotRevision()\n expected = {'got_chromium_revision': '59820', 'got_revision': '59820'}\n self.assertEqual(expected, actual)\n\n def testParseGotRevision_MultiJobDepsTry(self):\n gclient = TestableGClient(stdout=GCLIENT_SYNC_MULTI_JOB_DEPS_TRY_STDOUT)\n actual = gclient.parseGotRevision()\n expected = {'got_chromium_revision': '61624', 'got_revision': '61624', 'got_webkit_revision': '69168'}\n self.assertEqual(expected, actual)\n\n def testParseGotRevision_Nacl(self):\n gclient = TestableGClient(stdout=NACL_CHECKOUT)\n actual = gclient.parseGotRevision()\n expected = {'got_revision': '11'}\n self.assertEqual(expected, actual)\n", "method_code": " def parseGotRevision(self):\n if not hasattr(self.command, 'stdout'):\n return {}\n return extract_revisions(self.command.stdout)\n ", "context": "class GClient(SourceBaseCommand):\n def parseGotRevision(self): ...\n def __init__(self, *args, **kwargs): ...\n def setup(self, args): ...\n def start(self): ...\n def sourcedirIsPatched(self): ...\n def sourcedirIsUpdateable(self): ...\n def _RemoveDirectoryCommand(self, rm_dir): ...\n def doGclientUpdate(self): ...\n def getGclientConfigCommand(self): ...\n def doVCUpdate(self): ...\n def doVCFull(self): ...\n def doClobber(self, dummy, dirname, _=False): ...\n def doRevert(self, dummy): ...\n def _doRevertRemoveSignalFile(self): ...\n def doPatch(self, res): ...\n def doVCUpdateOnPatch(self, res): ...\n def doRunHooks(self, dummy): ...\n def writeSourcedata(self, res): ...\n def _handleGotRevision(self, res): ...\n def maybeDoVCFallback(self, rc): ...\n def maybeDoVCRetry(self, res): ...\n\n self.branch = None\n self.srcdir = None\n self.revision = None\n self.env = None\n self.sourcedatafile = None\n self.patch = None\n self.command = None\n self.vcexe = None\n self.svnurl = None\n self.sudo_for_remove = None\n self.gclient_spec = None\n self.gclient_deps = None\n self.rm_timeout = None\n self.gclient_nohooks = False\n self.was_patched = False\n self.no_gclient_branch = False\n self.no_gclient_revision = False\n self.gclient_transitive = False\n self.delete_unversioned_trees_when_updating = True\n self.gclient_jobs = None\n self.project = None\n self.sourcedata = None\n self.do_nothing = None\n\n header = 'gclient'\n", "repository": "yjbanov/chromium_build", "test_name": "testParseGotRevision_NoRevisions", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000697.py"} {"focal_file": "scripts/master/master_utils.py", "focal_class": null, "focal_method": "Partition", "tests": "import unittest\n\nclass Test_Partition(unittest.TestCase):\n def testPartition(self):\n partitions = master_utils.Partition([(1, 'a'), (2, 'b'), (3, 'c')], 2)\n self.assertEquals([['a', 'b'], ['c']], partitions)\n", "method_code": "def Partition(item_tuples, num_partitions):\n \"\"\"Divides |item_tuples| into |num_partitions| separate lists.\n\n Perfect partitioning is NP hard, this is a \"good enough\" estimate.\n\n Args:\n item_tuples: tuple in the format (weight, item_name).\n num_partitions: int number of partitions to generate.\n\n Returns:\n A list of lists of item_names with as close to equal weight as possible.\n \"\"\"\n assert num_partitions > 0, 'Must pass a positive number of partitions'\n assert len(item_tuples) >= num_partitions, 'Need more items than partitions'\n partitions = [[] for _ in xrange(num_partitions)]\n\n def GetLowestSumPartition():\n return sorted(partitions, key=lambda x: sum([i[0] for i in x]))[0]\n for item in sorted(item_tuples, reverse=True):\n GetLowestSumPartition().append(item)\n return sorted([sorted([name for _, name in p]) for p in partitions])", "context": "def Partition(item_tuples, num_partitions): ...\ndef HackMaxTime(maxTime=8 * 60 * 60): ...\ndef HackBuildStatus(): ...\ndef AutoSetupSlaves(builders, bot_password, max_builds=1, missing_recipients=None, preferred_builder_dict=None, missing_timeout=300): ...\ndef VerifySetup(c, slaves, enforce_sane_slave_pools=True): ...\ndef CreateWebStatus(port, templates=None, tagComparator=None, customEndpoints=None, console_repo_filter=None, console_builder_filter=None, web_template_globals=None, **kwargs): ...\ndef GetMastername(): ...\ndef AutoSetupMaster(c, active_master, mail_notifier=False, mail_notifier_mode=None, public_html=None, templates=None, order_console_by_time=False, tagComparator=None, customEndpoints=None, enable_http_status_push=False, console_repo_filter=None, console_builder_filter=None, web_template_globals=None): ...\ndef SetupBuildbucket(c, active_master): ...\ndef DumpSetup(c, important=None, filename='config.current.txt'): ...\ndef Partition(item_tuples, num_partitions): ...\n", "repository": "yjbanov/chromium_build", "test_name": "testPartition", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000698.py"} {"focal_file": "scripts/master/perf_count_notifier.py", "focal_class": null, "focal_method": "isInterestingStep", "tests": "import unittest\n\nclass Test_isInterestingStep(unittest.TestCase):\n def testSuccessIsNotInteresting(self):\n \"\"\"Test success step is not interesting.\"\"\"\n build_status = GetBuildStatusMock('test_build')\n step_status = BuildStepStatusMock(TEST_STATUS_TEXT)\n results = [SUCCESS]\n for _ in range(self.notifier.minimum_count):\n self.assertFalse(self.notifier.isInterestingStep(build_status, step_status, results))\n\n def testIsInterestingResetBySuccess(self):\n \"\"\"Test step count reset after a successful pass.\"\"\"\n build_status = GetBuildStatusMock('test_build')\n step_status = BuildStepStatusMock(TEST_STATUS_TEXT)\n results = [FAILURE]\n for _ in range(self.notifier.minimum_count - 1):\n self.assertFalse(self.notifier.isInterestingStep(build_status, step_status, results))\n results = [SUCCESS]\n self.assertFalse(self.notifier.isInterestingStep(build_status, step_status, results))\n results = [1]\n for _ in range(self.notifier.minimum_count - 1):\n self.assertFalse(self.notifier.isInterestingStep(build_status, step_status, results))\n self.assertTrue(self.notifier.isInterestingStep(build_status, step_status, results))\n\n def testIsInterestingException(self):\n \"\"\"Test step is interesting when step has exception.\"\"\"\n build_status = GetBuildStatusMock('test_build')\n step_status = BuildStepStatusMock(TEST_STATUS_TEXT_EXCEPTION)\n results = [FAILURE]\n self.assertTrue(self.notifier.isInterestingStep(build_status, step_status, results))\n", "method_code": " def isInterestingStep(self, build_status, step_status, results):\n \"\"\"Ignore the step if it is not one of the perf results steps.\n \n Returns:\n True: - if a REGRESS|IMPROVE happens consecutive minimum number of times.\n - if it is not a SUCCESS step and neither REGRESS|IMPROVE.\n False: - if it is a SUCCESS step.\n - if it is a notification which has already been notified.\n \"\"\"\n self.error_email = False\n step_text = ' '.join(step_status.getText())\n PerfLog('Analyzing failure text: %s.' % step_text)\n if not self._IsPerfStep(step_status) or not self.isInterestingBuilder(build_status.getBuilder()):\n return False\n if not results:\n results = [FAILURE]\n builder_name = build_status.getBuilder().getName()\n self.SetBuilderGraphURL(self.getName(step_status), build_status)\n if results[0] == SUCCESS:\n self._DeleteAllForBuild(builder_name)\n return False\n step_text = ' '.join(step_status.getText())\n PerfLog('Analyzing failure text: %s.' % step_text)\n perf_regress = perf_improve = ''\n perf_results = []\n if PERF_REGRESS in step_text:\n perf_regress = step_text[step_text.find(PERF_REGRESS) + len(PERF_REGRESS) + 1:step_text.find(PERF_IMPROVE)]\n perf_results.extend([(REGRESS, test_name, builder_name) for test_name in re.findall('(\\\\S+) (?=\\\\(.+\\\\))', perf_regress)])\n if PERF_IMPROVE in step_text:\n perf_improve = step_text[step_text.find(PERF_IMPROVE) + len(PERF_IMPROVE) + 1:]\n perf_results.extend([(IMPROVE, test_name, builder_name) for test_name in re.findall('(\\\\S+) (?=\\\\(.+\\\\))', perf_improve)])\n if not perf_results:\n if not self.recent_results.GetCount(step_text):\n PerfLog('Unrecognized step status. Reporting status as interesting.')\n self.error_email = True\n self.recent_results.Put(step_text)\n return True\n else:\n PerfLog('This problem has already been notified.')\n return False\n update_list = []\n for result in perf_results:\n if len(result) != 3:\n continue\n result_id = ' '.join(result)\n update_list.append(result)\n PerfLog('Result: %s happened %d times in a row.' % (result_id, self.recent_results.GetCount(result_id) + 1))\n if self.recent_results.GetCount(result_id) >= self.minimum_count - 1:\n PerfLog('Result: %s happened enough consecutive times to be reported.' % result_id)\n self.AddNewEmailResult(result)\n self._UpdateResults(builder_name, update_list)\n return self.ShouldSendEmail(builder_name)\n ", "context": "class PerfCountNotifier(ChromiumNotifier):\n def isInterestingStep(self, build_status, step_status, results): ...\n def __init__(self, step_names, minimum_count=5, combine_results=True, **kwargs): ...\n def AddNewEmailResult(self, result): ...\n def GetEmailResults(self, builder_name): ...\n def _UpdateResults(self, builder_name, results): ...\n def _StoreResult(self, result): ...\n def _DeleteResult(self, result_id): ...\n def _DeleteAllForBuild(self, builder_name): ...\n def _ResetResults(self, builder_name): ...\n def _IsPerfStep(self, step_status): ...\n def buildMessage(self, builder_name, build_status, results, step_name): ...\n def ShouldSendEmail(self, builder_name): ...\n def _ShouldSendEmail(self, builder_name): ...\n def GetEmailSubject(self, builder_name, build_status, results, step_name): ...\n def GetEmailHeader(self, builder_name, build_status, results, step_name): ...\n def GetEmailBody(self, builder_name, build_status, results, step_name): ...\n def GetPerfEmailBody(self, builder_name): ...\n def BuildEmailObject(self, email_subject, html_content, builder_name, build_status, step_name): ...\n def GenStepBox(self, builder_name, build_status, step_name): ...\n def SetBuilderGraphURL(self, step_name, build_status): ...\n\n self.minimum_count = minimum_count\n self.combine_results = combine_results\n self.step_names = step_names\n self.recent_results = None\n self.error_email = False\n self.new_email_results = {}\n self.recent_results = FailuresHistory(expiration_time=_EXPIRATION_TIME, size_limit=1000)\n", "repository": "yjbanov/chromium_build", "test_name": "testSuccessIsNotInteresting", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000699.py"} {"focal_file": "scripts/master/status_logger.py", "focal_class": null, "focal_method": "stepStarted", "tests": "import unittest\n\nclass Test_stepStarted(unittest.TestCase):\n def testStartStep(self):\n config_dict = {'file_logging': True, 'event_logging': True}\n with _make_logger(config_dict) as logger:\n logger.stepStarted(Build(), Step())\n self.assertTrue(os.path.exists(logger.logfile))\n self.assertTrue(os.path.isdir(logger._event_logging_dir))\n self.assertTrue(os.path.exists(logger._event_logfile))\n with open(logger._event_logfile, 'r') as f:\n content = f.read()\n self.assertTrue(content)\n json.loads(content)\n", "method_code": " def stepStarted(self, build, step):\n bot = build.getSlavename()\n builder_name = build.getBuilder().name\n build_number = build.getNumber()\n step_name = step.getName()\n self.log('stepStarted', '%s, %d, %s', builder_name, build_number, step_name)\n started, _ = step.getTimes()\n self.send_build_event('BEGIN', started * 1000, 'STEP', bot, builder_name, build_number, self._get_requested_at_millis(build), step_name=step_name, step_number=step.step_number)\n return self\n ", "context": "class StatusEventLogger(StatusReceiverMultiService):\n def stepStarted(self, build, step): ...\n def __init__(self, logfile='status.log', configfile='.logstatus', basedir=None, event_logging_dir=None): ...\n def as_dict(self): ...\n def _configure(self, config_data): ...\n def _get_requested_at_millis(build): ...\n def basedir(self): ...\n def _canonical_file(self, filename, ignore_basedir=False): ...\n def configfile(self): ...\n def logfile(self): ...\n def active(self): ...\n def send_build_result(self, scheduled, started, finished, builder_name, bot_name, result, project_id=None, subproject_tag=None, steps=None, pre_test_time_s=None): ...\n def send_build_event(self, timestamp_kind, timestamp, build_event_type, bot_name, builder_name, build_number, build_scheduled_ts, step_name=None, step_number=None, result=None, extra_result_code=None): ...\n def _create_logging_dir(self): ...\n def _create_ts_mon_logger(self): ...\n def _create_event_logger(self): ...\n def _create_logger(self): ...\n def startService(self): ...\n def log(self, event, message, *args): ...\n def requestSubmitted(self, request): ...\n def requestCancelled(self, builder, request): ...\n def buildsetSubmitted(self, buildset): ...\n def builderAdded(self, builderName, builder): ...\n def builderChangedState(self, builderName, state): ...\n def buildStarted(self, builderName, build): ...\n def buildETAUpdate(self, build, ETA): ...\n def changeAdded(self, change): ...\n def stepTextChanged(self, build, step, text): ...\n def stepText2Changed(self, build, step, text2): ...\n def stepETAUpdate(self, build, step, ETA, expectations): ...\n def logStarted(self, build, step, log): ...\n def logChunk(self, _build, _step, log, _channel, _text): ...\n def logFinished(self, build, step, log): ...\n def stepFinished(self, build, step, results): ...\n def buildFinished(self, builderName, build, results): ...\n def builderRemoved(self, builderName): ...\n def slaveConnected(self, slaveName): ...\n def slaveDisconnected(self, slaveName): ...\n\n self._logfile = self._original_logfile = logfile\n self._configfile = configfile\n self._basedir = basedir\n self.master_dir = os.path.basename(os.path.abspath(os.curdir))\n self._event_logging_dir = os.path.join(event_logging_dir or '/var/log/chrome-infra', 'status_logger-' + self.master_dir)\n self._event_logfile = os.path.join(self._event_logging_dir, 'events.log')\n self._ts_mon_logfile = os.path.join(self._event_logging_dir, 'ts_mon.log')\n self.logging_ignore_basedir = self.DEFAULT_LOGGING_IGNORE_BASEDIR\n self.logger = None\n self.event_logger = None\n self.ts_mon_logger = None\n self.status = None\n self._active = False\n self._last_checked_active = 0\n self._logging = False\n self._event_logging = False\n self._ts_mon_logging = False\n\n DEFAULT_LOGGING_IGNORE_BASEDIR = False\n", "repository": "yjbanov/chromium_build", "test_name": "testStartStep", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000700.py"} {"focal_file": "scripts/slave/recipe_modules/auto_bisect/bisector.py", "focal_class": "Bisector", "focal_method": "check_improvement_direction", "tests": "import unittest\n\nclass Test_Bisector_check_improvement_direction(unittest.TestCase):\n def test_improvement_direction_greater_is_better_fail(self):\n self.bisect_config['improvement_direction'] = 1\n bisector = Bisector(self.dummy_api, self.bisect_config, MockRevisionClass)\n bisector.good_rev.mean_value = 10\n bisector.bad_rev.mean_value = 100\n self.assertFalse(bisector.check_improvement_direction())\n self.assertIn('direction of improvement', ''.join(bisector.warnings))\n\n def test_improvement_direction_greater_is_better_pass(self):\n self.bisect_config['improvement_direction'] = 1\n bisector = Bisector(self.dummy_api, self.bisect_config, MockRevisionClass)\n bisector.good_rev.mean_value = 100\n bisector.bad_rev.mean_value = 10\n self.assertTrue(bisector.check_improvement_direction())\n self.assertNotIn('direction of improvement', ''.join(bisector.warnings))\n\n def test_improvement_direction_lower_is_better_fail(self):\n self.bisect_config['improvement_direction'] = -1\n bisector = Bisector(self.dummy_api, self.bisect_config, MockRevisionClass)\n bisector.good_rev.mean_value = 100\n bisector.bad_rev.mean_value = 10\n self.assertFalse(bisector.check_improvement_direction())\n self.assertIn('direction of improvement', ''.join(bisector.warnings))\n\n def test_improvement_direction_lower_is_better_pass(self):\n self.bisect_config['improvement_direction'] = -1\n bisector = Bisector(self.dummy_api, self.bisect_config, MockRevisionClass)\n bisector.good_rev.mean_value = 10\n bisector.bad_rev.mean_value = 100\n self.assertTrue(bisector.check_improvement_direction())\n self.assertNotIn('direction of improvement', ''.join(bisector.warnings))\n\n def test_improvement_direction_return_code(self):\n bisect_config = copy.deepcopy(self.bisect_config)\n bisect_config['test_type'] = 'return_code'\n bisector = Bisector(self.dummy_api, bisect_config, MockRevisionClass)\n bisector.good_rev.mean_value = 1\n bisector.bad_rev.mean_value = 0\n self.assertTrue(bisector.is_return_code_mode())\n self.assertFalse(bisector.check_improvement_direction())\n self.assertIn('return code', ''.join(bisector.warnings))\n", "method_code": " def check_improvement_direction(self):\n \"\"\"Verifies that the change from 'good' to 'bad' is in the right direction.\n \n The change between the test results obtained for the given 'good' and\n 'bad' revisions is expected to be considered a regression. The\n `improvement_direction` attribute is positive if a larger number is\n considered better, and negative if a smaller number is considered better.\n \"\"\"\n good = self.good_rev.mean_value\n bad = self.bad_rev.mean_value\n if self.is_return_code_mode():\n if good == 1 or bad == 0:\n self._set_failed_return_code_direction_results()\n return False\n return True\n direction = self.improvement_direction\n if direction is None:\n return True\n if bad > good and direction > 0 or (bad < good and direction < 0):\n self._set_failed_direction_results()\n return False\n return True\n ", "context": "class Bisector(object):\n def check_improvement_direction(self): ...\n def __init__(self, api, bisect_config, revision_class, init_revisions=True): ...\n def significantly_different(self, list_a, list_b, significance_level=SIGNIFICANCE_LEVEL): ...\n def config_step(self): ...\n def api(self): ...\n def compute_relative_change(self): ...\n def make_deps_sha_file(self, deps_sha): ...\n def _git_intern_file(self, file_contents, cwd, commit_hash): ...\n def _gen_diff_patch(self, git_object_a, git_object_b, src_alias, dst_alias, cwd, deps_rev): ...\n def make_deps_patch(self, base_revision, base_file_contents, depot, new_commit_hash): ...\n def _expand_chromium_revision_range(self): ...\n def _get_chromium_rev_range(self, min_rev, max_rev): ...\n def _expand_deps_revisions(self, revision_to_expand): ...\n def _get_rev_range_for_depot(self, depot_name, min_rev, max_rev, base_revision): ...\n def _update_revision_list_indexes(self): ...\n def _set_failed_return_code_direction_results(self): ...\n def _set_failed_direction_results(self): ...\n def check_initial_confidence(self): ...\n def get_exception(self): ...\n def _set_insufficient_confidence_warning(self): ...\n def _results_debug_message(self): ...\n def _revision_value_table(self): ...\n def _pretty_table(self, data): ...\n def _t_test_results(self): ...\n def print_result_debug_info(self): ...\n def post_result(self, halt_on_failure=False): ...\n def get_revision_to_eval(self): ...\n def check_reach_adjacent_revision(self, revision): ...\n def check_bisect_finished(self, revision): ...\n def wait_for_all(self, revision_list): ...\n def sleep_until_next_revision_ready(self, revision_list): ...\n def wait_for_any(self, revision_list): ...\n def abort_unnecessary_jobs(self): ...\n def _update_candidate_range(self): ...\n def get_perf_tester_name(self): ...\n def get_builder_bot_for_this_platform(self): ...\n def get_platform_gs_prefix(self): ...\n def ensure_sync_master_branch(self): ...\n def is_return_code_mode(self): ...\n def surface_result(self, result_string): ...\n def get_result(self): ...\n def _culprit_data(self): ...\n def _revision_data(self): ...\n def _get_build_url(self): ...\n\n self._api = api\n self.bisect_config = bisect_config\n self.revision_class = revision_class\n self.result_codes = set()\n self.last_tested_revision = None\n self.dummy_initial_confidence = bisect_config.get('dummy_initial_confidence')\n self.dummy_builds = bisect_config.get('dummy_builds', False)\n self.test_type = bisect_config.get('test_type', 'perf')\n self.improvement_direction = int(bisect_config.get('improvement_direction', 0)) or None\n self.warnings = []\n self.initial_confidence = None\n self.failed_initial_confidence = False\n self.failed = False\n self.failed_direction = False\n self.lkgr = None\n self.fkbr = None\n self.culprit = None\n self.bisect_over = False\n self.relative_change = None\n self.internal_bisect = api.internal_bisect\n self.base_depot = 'chromium'\n", "repository": "yjbanov/chromium_build", "test_name": "test_improvement_direction_greater_is_better_fail", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000701.py"} {"focal_file": "scripts/slave/recipe_modules/auto_bisect/bisector.py", "focal_class": "Bisector", "focal_method": "check_initial_confidence", "tests": "import unittest\n\nclass Test_Bisector_check_initial_confidence(unittest.TestCase):\n def test_check_initial_confidence_zero(self):\n mock_score = self.dummy_api.m.math_utils.confidence_score\n mock_score.return_value = 0\n bisector = Bisector(self.dummy_api, self.bisect_config, MockRevisionClass)\n bisector.good_rev.values = [3, 3, 3, 3, 3, 3]\n bisector.bad_rev.values = [3, 3, 3, 3, 3, 3]\n self.assertFalse(bisector.check_initial_confidence())\n self.assertTrue(bisector.failed_initial_confidence)\n\n def test_check_initial_confidence_one_hundred(self):\n bisector = Bisector(self.dummy_api, self.bisect_config, MockRevisionClass)\n bisector.good_rev.values = [3, 3, 3, 3, 3, 3]\n bisector.bad_rev.values = [9, 9, 9, 9, 9, 9]\n self.assertTrue(bisector.check_initial_confidence())\n self.assertFalse(bisector.failed_initial_confidence)\n\n def test_check_initial_confidence_not_required(self):\n mock_score = self.dummy_api.m.math_utils.confidence_score\n self.bisect_config['required_initial_confidence'] = None\n bisector = Bisector(self.dummy_api, self.bisect_config, MockRevisionClass)\n self.assertTrue(bisector.check_initial_confidence())\n self.assertFalse(mock_score.called)\n\n def test_check_initial_confidence_fail(self):\n mock_score = self.dummy_api.m.math_utils.confidence_score\n self.bisect_config['required_initial_confidence'] = 99\n mock_score.return_value = 98.5\n bisector = Bisector(self.dummy_api, self.bisect_config, MockRevisionClass)\n bisector.good_rev.values = [3, 3, 3, 3, 3, 3]\n bisector.bad_rev.values = [3, 3, 3, 3, 3, 3]\n self.assertFalse(bisector.check_initial_confidence())\n self.assertTrue(bisector.failed_initial_confidence)\n", "method_code": " def check_initial_confidence(self):\n \"\"\"Checks that the initial range presents a clear enough regression.\n \n We calculate the confidence of the results of the given 'good'\n and 'bad' revisions and compare it against the required confidence\n set for the bisector.\n \n Note that when a dummy regression confidence value has been set, that\n is used instead.\n \"\"\"\n if self.test_type != 'perf':\n return True\n if self.required_initial_confidence is None:\n return True\n if self.dummy_initial_confidence is not None:\n self.initial_confidence = float(self.dummy_initial_confidence)\n if float(self.initial_confidence) < float(self.required_initial_confidence):\n self._set_insufficient_confidence_warning()\n return False\n return True\n if self.dummy_builds:\n dummy_result = self.good_rev.values != self.bad_rev.values\n if not dummy_result:\n self._set_insufficient_confidence_warning()\n return dummy_result\n with self.api.m.step.nest('Re-testing reference range'):\n expiration_time = time.time() + REGRESSION_CHECK_TIMEOUT\n while time.time() < expiration_time:\n if len(self.good_rev.values) >= 5 and len(self.bad_rev.values) >= 5:\n if self.significantly_different(self.good_rev.values, self.bad_rev.values):\n return True\n if len(self.good_rev.values) == len(self.bad_rev.values):\n revision_to_retest = self.last_tested_revision\n else:\n revision_to_retest = min(self.good_rev, self.bad_rev, key=lambda x: len(x.values))\n if len(revision_to_retest.values) < MAX_REQUIRED_SAMPLES:\n revision_to_retest.retest()\n else:\n break\n self._set_insufficient_confidence_warning()\n return False\n ", "context": "class Bisector(object):\n def check_initial_confidence(self): ...\n def __init__(self, api, bisect_config, revision_class, init_revisions=True): ...\n def significantly_different(self, list_a, list_b, significance_level=SIGNIFICANCE_LEVEL): ...\n def config_step(self): ...\n def api(self): ...\n def compute_relative_change(self): ...\n def make_deps_sha_file(self, deps_sha): ...\n def _git_intern_file(self, file_contents, cwd, commit_hash): ...\n def _gen_diff_patch(self, git_object_a, git_object_b, src_alias, dst_alias, cwd, deps_rev): ...\n def make_deps_patch(self, base_revision, base_file_contents, depot, new_commit_hash): ...\n def _expand_chromium_revision_range(self): ...\n def _get_chromium_rev_range(self, min_rev, max_rev): ...\n def _expand_deps_revisions(self, revision_to_expand): ...\n def _get_rev_range_for_depot(self, depot_name, min_rev, max_rev, base_revision): ...\n def _update_revision_list_indexes(self): ...\n def check_improvement_direction(self): ...\n def _set_failed_return_code_direction_results(self): ...\n def _set_failed_direction_results(self): ...\n def get_exception(self): ...\n def _set_insufficient_confidence_warning(self): ...\n def _results_debug_message(self): ...\n def _revision_value_table(self): ...\n def _pretty_table(self, data): ...\n def _t_test_results(self): ...\n def print_result_debug_info(self): ...\n def post_result(self, halt_on_failure=False): ...\n def get_revision_to_eval(self): ...\n def check_reach_adjacent_revision(self, revision): ...\n def check_bisect_finished(self, revision): ...\n def wait_for_all(self, revision_list): ...\n def sleep_until_next_revision_ready(self, revision_list): ...\n def wait_for_any(self, revision_list): ...\n def abort_unnecessary_jobs(self): ...\n def _update_candidate_range(self): ...\n def get_perf_tester_name(self): ...\n def get_builder_bot_for_this_platform(self): ...\n def get_platform_gs_prefix(self): ...\n def ensure_sync_master_branch(self): ...\n def is_return_code_mode(self): ...\n def surface_result(self, result_string): ...\n def get_result(self): ...\n def _culprit_data(self): ...\n def _revision_data(self): ...\n def _get_build_url(self): ...\n\n self._api = api\n self.bisect_config = bisect_config\n self.revision_class = revision_class\n self.result_codes = set()\n self.last_tested_revision = None\n self.dummy_initial_confidence = bisect_config.get('dummy_initial_confidence')\n self.dummy_builds = bisect_config.get('dummy_builds', False)\n self.test_type = bisect_config.get('test_type', 'perf')\n self.improvement_direction = int(bisect_config.get('improvement_direction', 0)) or None\n self.warnings = []\n self.initial_confidence = None\n self.failed_initial_confidence = False\n self.failed = False\n self.failed_direction = False\n self.lkgr = None\n self.fkbr = None\n self.culprit = None\n self.bisect_over = False\n self.relative_change = None\n self.internal_bisect = api.internal_bisect\n self.base_depot = 'chromium'\n", "repository": "yjbanov/chromium_build", "test_name": "test_check_initial_confidence_zero", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000702.py"} {"focal_file": "scripts/slave/recipe_modules/test_results/resources/json_results_generator_unittest.py", "focal_class": null, "focal_method": "_generate_and_test_full_results_json", "tests": "import unittest\n\nclass Test_generate_and_test_full_results_json(unittest.TestCase):\n def test_get_full_results_json(self):\n self._generate_and_test_full_results_json(['testPassed', 'FLAKY_testPassedAndFlaky', 'DISABLED_testDisabled02'], ['testFailed', 'DISABLED_testDisabled01', 'FLAKY_testFlakyAndFailed'])\n self._generate_and_test_full_results_json([], [])\n self._generate_and_test_full_results_json(['testPassed01', 'testPassed02'], [])\n self._generate_and_test_full_results_json(['DISABLED_testDisabled01'], ['FAILS_testFailed'])\n", "method_code": " def _generate_and_test_full_results_json(self, passed_tests_list, failed_tests_list):\n tests_set = set(passed_tests_list) | set(failed_tests_list)\n get_test_set = lambda ts, label: set([t for t in ts if t.startswith(label)])\n DISABLED_tests = get_test_set(tests_set, 'DISABLED_')\n FLAKY_tests = get_test_set(tests_set, 'FLAKY_')\n MAYBE_tests = get_test_set(tests_set, 'MAYBE_')\n FAILS_tests = get_test_set(tests_set, 'FAILS_')\n PASS_tests = tests_set - (DISABLED_tests | FLAKY_tests | FAILS_tests | MAYBE_tests) - set(failed_tests_list)\n failed_tests = set(failed_tests_list) - DISABLED_tests\n test_timings = {}\n test_results_map = {}\n for i, test in enumerate(tests_set):\n test_name = canonical_name(test)\n test_timings[test_name] = i\n test_results_map[test_name] = [TestResult(test, status='FAILURE' if test in failed_tests else 'SUCCESS', elapsed_time=test_timings[test_name])]\n mock_writer = lambda path, data: True\n generator = JSONResultsGenerator(self.builder_name, self.build_number, '', test_results_map, svn_revisions=[('blink', '12345')], file_writer=mock_writer)\n results_json = generator.get_full_results_json()\n self._verify_full_json_results(results_json, tests_set, PASS_tests, failed_tests, test_timings)\n self.assertEqual(results_json.get('blink_revision'), '12345')\n ", "context": "class JSONGeneratorTest(unittest.TestCase):\n def _generate_and_test_full_results_json(self, passed_tests_list, failed_tests_list): ...\n def setUp(self): ...\n def test_get_full_results_json(self): ...\n def _verify_full_json_results(self, results, all_tests, passed_tests, failed_tests, test_timings): ...\n def test_test_timings_trie(self): ...\n", "repository": "yjbanov/chromium_build", "test_name": "test_get_full_results_json", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000703.py"} {"focal_file": "scripts/slave/annotated_run.py", "focal_class": null, "focal_method": "_should_run_logdog", "tests": "import unittest\n\nclass Test_should_run_logdog(unittest.TestCase):\n def test_should_run_logdog(self):\n self.assertFalse(annotated_run._should_run_logdog({'mastername': 'master.undefined', 'buildername': 'any'}))\n self.assertFalse(annotated_run._should_run_logdog({'mastername': 'master.some', 'buildername': 'nobuilder'}))\n self.assertTrue(annotated_run._should_run_logdog({'mastername': 'master.some', 'buildername': 'yesbuilder'}))\n self.assertTrue(annotated_run._should_run_logdog({'mastername': 'master.all', 'buildername': 'anybuilder'}))\n", "method_code": "def _should_run_logdog(properties):\n \"\"\"Returns (bool): True if LogDog should be used for this run.\n\n Args:\n properties (dict): The factory properties for this recipe run.\n \"\"\"\n mastername = properties.get('mastername')\n buildername = properties.get('buildername')\n if not all((mastername, buildername)):\n LOGGER.warning('Required mastername/buildername is not set.')\n return False\n bdict = LOGDOG_WHITELIST_MASTER_BUILDERS.get(mastername)\n if bdict is not None:\n if WHITELIST_ALL in bdict or buildername in bdict:\n LOGGER.info('Whitelisted master %s, builder %s.', mastername, buildername)\n return True\n LOGGER.info('Master %s, builder %s is not whitelisted for LogDog.', mastername, buildername)\n return False", "context": "def _should_run_logdog(properties): ...\ndef get_config(): ...\ndef ensure_directory(*path): ...\ndef _logdog_get_streamserver_uri(rt, typ): ...\ndef _run_command(cmd, **kwargs): ...\ndef _check_command(cmd, **kwargs): ...\ndef ensure_directory(*path): ...\ndef _get_service_account_json(opts, credential_path): ...\ndef _logdog_install_cipd(path, *packages): ...\ndef _build_logdog_prefix(properties): ...\ndef _logdog_bootstrap(rt, opts, basedir, tempdir, config, properties, cmd): ...\ndef _should_run_logdog(properties): ...\ndef get_recipe_properties(workdir, build_properties, use_factory_properties_from_disk): ...\ndef get_factory_properties_from_disk(workdir, mastername, buildername): ...\ndef get_args(argv): ...\ndef update_scripts(): ...\ndef clean_old_recipe_engine(): ...\ndef write_monitoring_event(config, datadir, build_properties): ...\ndef _exec_recipe(rt, opts, basedir, tdir, config, properties): ...\ndef main(argv): ...\ndef shell_main(argv): ...\n", "repository": "yjbanov/chromium_build", "test_name": "test_should_run_logdog", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000704.py"} {"focal_file": "scripts/slave/chromium_commands.py", "focal_class": null, "focal_method": "extract_revisions", "tests": "import unittest\n\nclass Test_extract_revisions(unittest.TestCase):\n def test_extract_revisions_empty(self):\n data = ''\n expected = {}\n actual = chromium_commands.extract_revisions(data)\n self.assertEqual(expected, actual)\n\n def test_extract_revisions_short(self):\n data = \"124>_____ src/tools/swarming_client at c60aabe2367cea6a9cdecd895a9da5a0a381201d\\n124>________ running 'git ...' in '/build'\\n124>Cloning into '/build/src/tools/_gclient_swarming_client_LfrCWh'...\\n124>POST git-upload-pack (174 bytes)\\n124>remote: Total 2041 (delta 1534), reused 2041 (delta 1534)\\n124>Receiving objects: 100% (2041/2041)\\n124>Receiving objects: 100% (2041/2041), 619.13 KiB | 0 bytes/s, done.\\n124>Resolving deltas: 100% (1534/1534)\\n124>Resolving deltas: 100% (1534/1534), done.\\n124>Checking connectivity... done\\n124>________ running 'git checkout --quiet c60aabe2367cea6a9cdecd895a9da5a0a381201d' in '/build/src/tools/swarming_client'\\n124>Checked out c60aabe2367cea6a9cdecd895a9da5a0a381201d to a detached HEAD. Before making any commits\\n124>in this repo, you should use 'git checkout ' to switch to\\n124>an existing branch or use 'git checkout origin -b ' to\\n124>create a new branch for your work.\\n\"\n expected = {'got_revision': 'c60aabe2367cea6a9cdecd895a9da5a0a381201d', 'got_swarming_client_revision': 'c60aabe2367cea6a9cdecd895a9da5a0a381201d'}\n actual = chromium_commands.extract_revisions(data)\n self.assertEqual(expected, actual)\n", "method_code": "def extract_revisions(output):\n \"\"\"Extracts revision numbers for all the dependencies checked out.\n\n svn checkout operations finish with 'Checked out revision 16657.'\n svn update operations finish the line 'At revision 16654.' when there is no\n change. They finish with 'Updated to revision 16655.' otherwise.\n\n The first project checked out gets to be set to got_revision property. This is\n important since this class is not only used for chromium, it's also used for\n other projects.\n \"\"\"\n SCM_RE = {'git': '^Checked out revision ([0-9a-fA-F]{40})$', 'svn': '^(?:Checked out|At|Updated to) revision ([0-9]+)\\\\.'}\n GCLIENT_CMD = re.compile(\"^________ running \\\\'(.+?)\\\\' in \\\\'(.+?)\\\\'$\")\n GCLIENT_AT_REV = re.compile('_____ (.+?) at (\\\\d+|[0-9a-fA-F]{40})$')\n untangled_stdout = untangle(output.splitlines(False))\n for i, line in enumerate(reversed(untangled_stdout)):\n if line.startswith('solutions=['):\n untangled_stdout = untangled_stdout[-i - 1:]\n break\n revisions_found = {}\n current_scm = None\n current_project = None\n reldir = None\n for line in untangled_stdout:\n match = GCLIENT_AT_REV.match(line)\n if match:\n current_project = None\n current_scm = None\n log.msg('gclient: %s == %s' % match.groups())\n project = PROJECTS_LOOKING_FOR.get(match.group(1))\n if not revisions_found:\n revisions_found['got_revision'] = match.group(2)\n if project:\n revisions_found[project] = match.group(2)\n continue\n if current_scm:\n match = re.match(SCM_RE[current_scm], line)\n if match:\n log.msg('scm: %s (%s) == %s' % (reldir, current_project, match.group(1)))\n if not revisions_found:\n revisions_found['got_revision'] = match.group(1)\n if current_project:\n revisions_found[current_project] = match.group(1)\n current_project = None\n current_scm = None\n continue\n match = GCLIENT_CMD.match(line)\n if match:\n command, directory = match.groups()\n parts = command.split(' ')\n directory = directory.rstrip(os.path.sep) + os.path.sep\n if parts[0] in SCM_RE:\n current_scm = parts[0]\n for part in parts:\n if part.startswith(directory):\n reldir = part[len(directory):]\n if reldir:\n current_project = PROJECTS_LOOKING_FOR.get(reldir)\n break\n return revisions_found", "context": "def extract_revisions(output): ...\ndef FixDiffLineEnding(diff): ...\ndef untangle(stdout_lines): ...\ndef extract_revisions(output): ...\ndef _RenameDirectoryCommand(src_dir, dest_dir): ...\ndef _RemoveFileCommand(filename): ...\ndef RegisterCommands(): ...\n", "repository": "yjbanov/chromium_build", "test_name": "test_extract_revisions_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000705.py"} {"focal_file": "third_party/pytz/tzinfo.py", "focal_class": null, "focal_method": "localize", "tests": "import unittest\n\nclass Test_localize(unittest.TestCase):\n def testLocalize(self):\n loc_tz = pytz.timezone('Europe/Amsterdam')\n loc_time = loc_tz.localize(datetime(1930, 5, 10, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'AMT+0020')\n loc_time = loc_tz.localize(datetime(1930, 5, 20, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'NST+0120')\n loc_time = loc_tz.localize(datetime(1940, 5, 10, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'NET+0020')\n loc_time = loc_tz.localize(datetime(1940, 5, 20, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CEST+0200')\n loc_time = loc_tz.localize(datetime(2004, 2, 1, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CET+0100')\n loc_time = loc_tz.localize(datetime(2004, 4, 1, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CEST+0200')\n tz = pytz.timezone('Europe/Amsterdam')\n loc_time = loc_tz.localize(datetime(1943, 3, 29, 1, 59, 59))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CET+0100')\n loc_tz = pytz.timezone('US/Eastern')\n loc_time = loc_tz.localize(datetime(1918, 10, 27, 1, 59, 59), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EDT-0400')\n loc_time = loc_tz.localize(datetime(1918, 10, 27, 1, 59, 59), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n self.assertRaises(pytz.AmbiguousTimeError, loc_tz.localize, datetime(1918, 10, 27, 1, 59, 59), is_dst=None)\n loc_time = loc_tz.localize(datetime(1918, 3, 31, 2, 0, 0), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n loc_time = loc_tz.localize(datetime(1918, 3, 31, 2, 0, 0), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EDT-0400')\n self.assertRaises(pytz.NonExistentTimeError, loc_tz.localize, datetime(1918, 3, 31, 2, 0, 0), is_dst=None)\n loc_time = loc_tz.localize(datetime(1942, 2, 9, 3, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'EWT-0400')\n loc_time = loc_tz.localize(datetime(1945, 8, 14, 19, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'EPT-0400')\n loc_time = loc_tz.localize(datetime(1945, 9, 30, 1, 0, 0), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EPT-0400')\n loc_time = loc_tz.localize(datetime(1945, 9, 30, 1, 0, 0), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n", "method_code": " def localize(self, dt, is_dst=False):\n \"\"\"Convert naive time to local time\"\"\"\n if dt.tzinfo is not None:\n raise ValueError('Not naive datetime (tzinfo is already set)')\n return dt.replace(tzinfo=self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def localize(self, dt, is_dst=False): ...\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "yjbanov/chromium_build", "test_name": "testLocalize", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000706.py"} {"focal_file": "third_party/pytz/tzinfo.py", "focal_class": null, "focal_method": "normalize", "tests": "import unittest\n\nclass Test_normalize(unittest.TestCase):\n def testNormalize(self):\n tz = pytz.timezone('US/Eastern')\n dt = datetime(2004, 4, 4, 7, 0, 0, tzinfo=UTC).astimezone(tz)\n dt2 = dt - timedelta(minutes=10)\n self.assertEqual(dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'), '2004-04-04 02:50:00 EDT-0400')\n dt2 = tz.normalize(dt2)\n self.assertEqual(dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'), '2004-04-04 01:50:00 EST-0500')\n\n def test_normalize(self):\n other_tz = pytz.timezone('Europe/Paris')\n self.assertTrue(self.tz is not other_tz)\n dt = datetime(2012, 3, 26, 12, 0)\n other_dt = other_tz.localize(dt)\n local_dt = self.tz.normalize(other_dt)\n self.assertTrue(local_dt.tzinfo is not other_dt.tzinfo)\n self.assertNotEqual(local_dt.replace(tzinfo=None), other_dt.replace(tzinfo=None))\n", "method_code": " def normalize(self, dt, is_dst=False):\n \"\"\"Correct the timezone information on the given datetime.\n \n This is normally a no-op, as StaticTzInfo timezones never have\n ambiguous cases to correct:\n \n >>> from pytz import timezone\n >>> gmt = timezone('GMT')\n >>> isinstance(gmt, StaticTzInfo)\n True\n >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt)\n >>> gmt.normalize(dt) is dt\n True\n \n The supported method of converting between timezones is to use\n datetime.astimezone(). Currently normalize() also works:\n \n >>> la = timezone('America/Los_Angeles')\n >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3))\n >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'\n >>> gmt.normalize(dt).strftime(fmt)\n '2011-05-07 08:02:03 GMT (+0000)'\n \"\"\"\n if dt.tzinfo is self:\n return dt\n if dt.tzinfo is None:\n raise ValueError('Naive time - no tzinfo set')\n return dt.astimezone(self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def normalize(self, dt, is_dst=False): ...\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def localize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "yjbanov/chromium_build", "test_name": "testNormalize", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000707.py"} {"focal_file": "third_party/pytz/tzinfo.py", "focal_class": null, "focal_method": "fromutc", "tests": "import unittest\n\nclass Test_fromutc(unittest.TestCase):\n def test_fromutc(self):\n dt1 = datetime(2011, 10, 31)\n dt2 = self.tz.localize(dt1)\n for dt in [dt1, dt2]:\n loc_dt = self.tz.fromutc(dt)\n loc_dt2 = pytz.utc.localize(dt1).astimezone(self.tz)\n self.assertEqual(loc_dt, loc_dt2)\n new_tz = pytz.timezone('Europe/Paris')\n self.assertTrue(self.tz is not new_tz)\n dt3 = new_tz.localize(dt1)\n self.assertRaises(ValueError, self.tz.fromutc, dt3)\n", "method_code": " def fromutc(self, dt):\n \"\"\"See datetime.tzinfo.fromutc\"\"\"\n if dt.tzinfo is not None and dt.tzinfo is not self:\n raise ValueError('fromutc: dt.tzinfo is not self')\n return (dt + self._utcoffset).replace(tzinfo=self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def localize(self, dt, is_dst=False): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "yjbanov/chromium_build", "test_name": "test_fromutc", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000708.py"} {"focal_file": "third_party/requests_1_2_3/requests/structures.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_request_ok_set(self):\n r = requests.get(httpbin('status', '404'))\n self.assertEqual(r.ok, False)\n\n def test_unicode_get(self):\n url = httpbin('/get')\n requests.get(url, params={'foo': 'føø'})\n requests.get(url, params={'føø': 'føø'})\n requests.get(url, params={'føø': 'føø'})\n requests.get(url, params={'foo': 'foo'})\n requests.get(httpbin('ø'), params={'foo': 'foo'})\n", "method_code": " def get(self, key, default=None):\n return self.__dict__.get(key, default)\n ", "context": "class LookupDict(dict):\n def get(self, key, default=None): ...\n def __init__(self, name=None): ...\n def __repr__(self): ...\n def __getitem__(self, key): ...\n\n self.name = name\n", "repository": "yjbanov/chromium_build", "test_name": "test_request_ok_set", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1], "pynose_source_file": "test_000709.py"} {"focal_file": "third_party/requests_1_2_3/requests/structures.py", "focal_class": "CaseInsensitiveDict", "focal_method": "get", "tests": "import unittest\n\nclass Test_CaseInsensitiveDict_get(unittest.TestCase):\n def test_get(self):\n cid = CaseInsensitiveDict()\n cid['spam'] = 'oneval'\n cid['SPAM'] = 'blueval'\n self.assertEqual(cid.get('spam'), 'blueval')\n self.assertEqual(cid.get('SPAM'), 'blueval')\n self.assertEqual(cid.get('sPam'), 'blueval')\n self.assertEqual(cid.get('notspam', 'default'), 'default')\n", "method_code": " def get(self, key, default=None):\n return self.__dict__.get(key, default)\n ", "context": "class LookupDict(dict):\n def get(self, key, default=None): ...\n def __init__(self, name=None): ...\n def __repr__(self): ...\n def __getitem__(self, key): ...\n\n self.name = name\n", "repository": "yjbanov/chromium_build", "test_name": "test_get", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000710.py"} {"focal_file": "third_party/requests_1_2_3/requests/structures.py", "focal_class": "CaseInsensitiveDict", "focal_method": "lower_items", "tests": "import unittest\n\nclass Test_CaseInsensitiveDict_lower_items(unittest.TestCase):\n def test_lower_items(self):\n cid = CaseInsensitiveDict({'Accept': 'application/json', 'user-Agent': 'requests'})\n keyset = frozenset((lowerkey for lowerkey, v in cid.lower_items()))\n lowerkeyset = frozenset(['accept', 'user-agent'])\n self.assertEqual(keyset, lowerkeyset)\n", "method_code": " def lower_items(self):\n \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n return ((lowerkey, keyval[1]) for lowerkey, keyval in self._store.items())\n ", "context": "class CaseInsensitiveDict(collections.MutableMapping):\n def lower_items(self): ...\n def __init__(self, data=None, **kwargs): ...\n def __setitem__(self, key, value): ...\n def __getitem__(self, key): ...\n def __delitem__(self, key): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __eq__(self, other): ...\n def copy(self): ...\n def __repr__(self): ...\n\n self._store = dict()\n", "repository": "yjbanov/chromium_build", "test_name": "test_lower_items", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000711.py"} {"focal_file": "graphcanvas/graph_node_hover_tool.py", "focal_class": null, "focal_method": "_is_in", "tests": "import unittest\n\nclass Test_is_in(unittest.TestCase):\n def test__is_in(self):\n self.assertTrue(self.tool._is_in(0, 0))\n self.assertFalse(self.tool._is_in(-100, -100))\n", "method_code": " def _is_in(self, x, y):\n return self.component.is_in(x, y)\n ", "context": "class GraphNodeHoverTool(HoverTool):\n def _is_in(self, x, y): ...\n def normal_mouse_move(self, event): ...\n def on_hover(self): ...\n\n _last_xy = Tuple()\n", "repository": "enthought/graphcanvas", "test_name": "test__is_in", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000712.py"} {"focal_file": "graphcanvas/graph_node_hover_tool.py", "focal_class": null, "focal_method": "normal_mouse_move", "tests": "import unittest\n\nclass Test_normal_mouse_move(unittest.TestCase):\n def test_normal_mouse_move(self):\n event = BasicEvent(x=10, y=10, handled=False)\n self.tool.normal_mouse_move(event)\n self.assertEqual(self.tool._last_xy, (10, 10))\n", "method_code": " def normal_mouse_move(self, event):\n self._last_xy = (event.x, event.y)\n super(GraphNodeHoverTool, self).normal_mouse_move(event)\n ", "context": "class GraphNodeHoverTool(HoverTool):\n def normal_mouse_move(self, event): ...\n def _is_in(self, x, y): ...\n def on_hover(self): ...\n\n _last_xy = Tuple()\n", "repository": "enthought/graphcanvas", "test_name": "test_normal_mouse_move", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000713.py"} {"focal_file": "graphcanvas/graph_node_hover_tool.py", "focal_class": null, "focal_method": "on_hover", "tests": "import unittest\n\nclass Test_on_hover(unittest.TestCase):\n def test_on_hover(self):\n self.tool._last_xy = (0, 0)\n self.tool.callback = mock.Mock()\n self.tool.on_hover()\n self.tool.callback.assert_called_once_with('test')\n self.tool._last_xy = (-100, -100)\n self.tool.callback = mock.Mock()\n self.tool.on_hover()\n self.tool.callback.assert_not_called()\n", "method_code": " def on_hover(self):\n \"\"\" This gets called when all the conditions of the hover action have\n been met, and the tool determines that the mouse is, in fact, hovering\n over a target region on the component.\n \n By default, this method call self.callback (if one is configured).\n \"\"\"\n for component in self.component.components:\n if component.is_in(*self._last_xy):\n if self.callback is not None:\n self.callback(component.label)\n ", "context": "class GraphNodeHoverTool(HoverTool):\n def on_hover(self): ...\n def _is_in(self, x, y): ...\n def normal_mouse_move(self, event): ...\n\n _last_xy = Tuple()\n", "repository": "enthought/graphcanvas", "test_name": "test_on_hover", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000714.py"} {"focal_file": "graphcanvas/graph_node_selection_tool.py", "focal_class": null, "focal_method": "normal_left_dclick", "tests": "import unittest\n\nclass Test_normal_left_dclick(unittest.TestCase):\n def test_normal_left_dclick_in(self):\n event = BasicEvent(x=0, y=0, handled=False)\n node = self.container.components[0]\n node.edit_traits = mock.Mock()\n self.tool.normal_left_dclick(event)\n node.edit_traits.assert_called_once_with(kind='livemodal')\n\n def test_normal_left_dclick_not_in(self):\n event = BasicEvent(x=50, y=50, handled=False)\n node = self.container.components[0]\n node.edit_traits = mock.Mock()\n self.tool.normal_left_dclick(event)\n node.edit_traits.assert_not_called()\n self.assertFalse(event.handled)\n", "method_code": " def normal_left_dclick(self, event):\n for node in self.component.components:\n if node.is_in(event.x, event.y):\n if isinstance(node.value, HasTraits):\n node.value.edit_traits()\n else:\n node.edit_traits(kind='livemodal')\n break\n ", "context": "class GraphNodeSelectionTool(BaseTool):\n def normal_left_dclick(self, event): ...", "repository": "enthought/graphcanvas", "test_name": "test_normal_left_dclick_in", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000715.py"} {"focal_file": "graphcanvas/graph_container.py", "focal_class": "GraphContainer", "focal_method": "do_layout", "tests": "import unittest\n\nclass Test_GraphContainer_do_layout(unittest.TestCase):\n def test_do_layout(self):\n container = self.create_graph_container()\n container.style = 'spring'\n self.assertTrue(container._graph_layout_needed)\n container.do_layout()\n self.assert_in_bounds(container)\n self.assertFalse(container._graph_layout_needed)\n container = self.create_graph_container()\n container.style = 'tree'\n self.assertTrue(container._graph_layout_needed)\n container.do_layout()\n self.assert_in_bounds(container)\n self.assertFalse(container._graph_layout_needed)\n container = self.create_graph_container()\n container.style = 'shell'\n self.assertTrue(container._graph_layout_needed)\n container.do_layout()\n self.assert_in_bounds(container)\n self.assertFalse(container._graph_layout_needed)\n container = self.create_graph_container()\n container.style = 'spectral'\n self.assertTrue(container._graph_layout_needed)\n container.do_layout()\n self.assert_in_bounds(container)\n self.assertFalse(container._graph_layout_needed)\n g = networkx.balanced_tree(3, 5)\n container = GraphContainer(graph=g)\n for node in g.nodes():\n GraphNodeComponent(container=container, value=node)\n container.style = 'circular'\n self.assertTrue(container._graph_layout_needed)\n container.do_layout()\n self.assert_in_bounds(container)\n self.assertFalse(container._graph_layout_needed)\n", "method_code": " def do_layout(self, size=None, force=False):\n \"\"\" Nodes of the graph will be layed out based on the the style\n attribute\n \"\"\"\n if not self._graph_layout_needed or len(self.components) == 0:\n return\n \n def _apply_graphviz_layout(layout):\n x_values = [pos[0] for pos in layout.values()]\n y_values = [pos[1] for pos in layout.values()]\n min_x = min(x_values)\n max_x = max(x_values)\n min_y = min(y_values)\n max_y = max(y_values)\n x_range = max_x - min_x\n y_range = max_y - min_y\n for component in self.components:\n component.x = self.width * (layout[component._key][0] - min_x) / x_range\n component.y = self.height * (layout[component._key][1] - min_y) / y_range\n initial_positions = {node.value: node.position for node in self.components}\n if all((point == [0.0, 0.0] for point in initial_positions.values())):\n initial_positions = None\n scale = min(self.bounds)\n if self.style == 'tree':\n try:\n layout = networkx.drawing.nx_agraph.pygraphviz_layout(self.graph, prog='dot')\n _apply_graphviz_layout(layout)\n except ImportError:\n layout = tree_layout(self.graph)\n depths = [v[1] for v in layout.values()]\n widths = [depths.count(d) for d in numpy.unique(depths)]\n max_width = max(widths)\n max_depth = len(widths)\n self.bounds = [max(75, self.components[0].width) * max_width, max(50, self.components[0].height) * max_depth]\n elif self.style == 'shell':\n layout = networkx.shell_layout(self.graph)\n radius = numpy.log2(len(layout))\n self.bounds = [max(75, self.components[0].width) * 2 * radius, max(50, self.components[0].height) * 2 * radius]\n for component in self.components:\n component.y = self.height * (1 + layout[component._key][0]) / 2\n component.x = self.width * (1 + layout[component._key][1]) / 2\n elif self.style == 'spectral':\n layout = networkx.spectral_layout(self.graph)\n radius = numpy.log2(len(layout))\n self.bounds = [max(75, self.components[0].width) * 2 * radius, max(50, self.components[0].height) * 2 * radius]\n for component in self.components:\n component.y = self.height * (1 + layout[component._key][0]) / 2\n component.x = self.width * (1 + layout[component._key][1]) / 2\n elif self.style == 'circular':\n try:\n layout = networkx.drawing.nx_agraph.pygraphviz_layout(self.graph, prog='twopi')\n _apply_graphviz_layout(layout)\n except ImportError:\n layout = networkx.circular_layout(self.graph, scale=min(self.bounds) // 2, center=[bound // 2 for bound in self.bounds])\n else:\n layout = networkx.spring_layout(self.graph, pos=initial_positions, scale=scale / 2.0, center=[bound / 2.0 for bound in self.bounds])\n radius = len(layout)\n self.bounds = [max(75, self.components[0].width) * 2 * radius, max(50, self.components[0].height) * 2 * radius]\n for component in self.components:\n component.x = layout[component._key][0]\n component.y = layout[component._key][1]\n self._graph_layout_needed = False\n ", "context": "class GraphContainer(Container):\n def do_layout(self, size=None, force=False): ...\n def draw(self, gc, view_bounds=None, mode='default'): ...\n def _graph_changed(self, new): ...\n\n bounds = [350, 350]\n graph = Instance(networkx.Graph)\n style = Enum(SUPPORTED_LAYOUTS)\n _graph_layout_needed = Bool(True)\n", "repository": "enthought/graphcanvas", "test_name": "test_do_layout", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000716.py"} {"focal_file": "graphcanvas/layout.py", "focal_class": null, "focal_method": "tree_layout", "tests": "import unittest\n\nclass Test_tree_layout(unittest.TestCase):\n def test_layout(self):\n g = networkx.DiGraph()\n g.add_edge('root', 'child 1')\n g.add_edge('child 1', 'grandchild 1')\n g.add_edge('child 1', 'grandchild 2')\n g.add_edge('root', 'child 2')\n g.add_edge('child 2', 'grandchild 3')\n g.add_edge('child 2', 'grandchild 4')\n g.add_edge('child 2', 'grandchild 5')\n layout = tree_layout(g)\n expected_root_x, expected_root_y = (0.5, 1.0)\n self.assertAlmostEqual(layout['root'][0], expected_root_x)\n self.assertAlmostEqual(layout['root'][1], expected_root_y)\n gc_xs = [value[0] for key, value in layout.items() if key.startswith('child')]\n expected_gc_xs = [x / 3.0 for x in range(1, 3)]\n nptest.assert_almost_equal(sorted(gc_xs), expected_gc_xs)\n gc_ys = [value[1] for key, value in layout.items() if key.startswith('child')]\n expected_gc_ys = [0.5] * 2\n nptest.assert_almost_equal(sorted(gc_ys), expected_gc_ys)\n gc_xs = [value[0] for key, value in layout.items() if 'grandchild' in key]\n expected_gc_xs = [x / 6.0 for x in range(1, 6)]\n nptest.assert_almost_equal(sorted(gc_xs), expected_gc_xs)\n gc_ys = [value[1] for key, value in layout.items() if 'grandchild' in key]\n expected_gc_ys = [0.0] * 5\n nptest.assert_almost_equal(sorted(gc_ys), expected_gc_ys)\n", "method_code": "def tree_layout(graph, dim=2, scale=1):\n if dim != 2:\n raise ValueError('currently only 2D graphs are supported')\n if not graph.is_directed():\n raise ValueError('graph must be directed')\n if not networkx.is_directed_acyclic_graph(graph):\n raise ValueError('graph must not contain cycles')\n roots = numpy.array([node for node, degree in dict(graph.in_degree()).items() if degree < 1])\n depths = []\n for node in graph.nodes():\n depth = 0\n parents = [parent for parent in graph.predecessors(node)]\n while len(parents) > 0:\n node = parents[0]\n parents = [parent for parent in graph.predecessors(node)]\n depth += 1\n depths.append(depth)\n max_depth = max(depths)\n widths = [depths.count(i) for i in range(max_depth + 1)]\n nodes_positioned_at_depth = [0] * len(widths)\n positions = {}\n for root in roots:\n node_stack = [(0, root)]\n while len(node_stack) > 0:\n curr_depth, curr_node = node_stack.pop()\n for child in graph.successors(curr_node):\n node_stack.append((curr_depth + 1, child))\n draw_depth = 1.0 - float(curr_depth) / max_depth\n depth_width = widths[curr_depth]\n nodes_positioned_at_depth[curr_depth] += 1\n width_positions = numpy.linspace(0, 1, depth_width + 2)\n draw_width = width_positions[nodes_positioned_at_depth[curr_depth]]\n positions[curr_node] = (draw_width, draw_depth)\n return positions", "context": "def tree_layout(graph, dim=2, scale=1): ...\ndef tree_layout(graph, dim=2, scale=1): ...\n", "repository": "enthought/graphcanvas", "test_name": "test_layout", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000717.py"} {"focal_file": "graphcanvas/graph_node_drag_tool.py", "focal_class": null, "focal_method": "get_value", "tests": "import unittest\n\nclass Test_get_value(unittest.TestCase):\n def test_get_value(self):\n self.tool.original_screen_point = (0, 0)\n result = self.tool.get_value()\n self.assertIsInstance(result, GraphNodeComponent)\n self.tool.original_screen_point = (50, 50)\n result = self.tool.get_value()\n self.assertIsNone(result)\n", "method_code": " def get_value(self):\n for node in self.component.components:\n if node.is_in(*self.original_screen_point):\n return node\n ", "context": "class GraphNodeDragTool(ValueDragTool):\n def get_value(self): ...\n def set_delta(self, value, delta_x, delta_y): ...\n def dragging(self, event): ...\n\n drag_button = 'right'\n x_name = 'x'\n y_name = 'y'\n", "repository": "enthought/graphcanvas", "test_name": "test_get_value", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000718.py"} {"focal_file": "graphcanvas/graph_node_drag_tool.py", "focal_class": null, "focal_method": "set_delta", "tests": "import unittest\n\nclass Test_set_delta(unittest.TestCase):\n def test_set_delta(self):\n delta_x = 10\n delta_y = 10\n self.tool.original_screen_point = (0, 0)\n value = self.tool.get_value()\n self.tool.set_delta(value, delta_x, delta_y)\n self.assertEqual(value.x, delta_x)\n self.assertEqual(value.y, delta_y)\n", "method_code": " def set_delta(self, value, delta_x, delta_y):\n if value is not None:\n value.x = self.original_screen_point[0] + delta_x\n value.y = self.original_screen_point[1] + delta_y\n value.request_redraw()\n ", "context": "class GraphNodeDragTool(ValueDragTool):\n def set_delta(self, value, delta_x, delta_y): ...\n def get_value(self): ...\n def dragging(self, event): ...\n\n drag_button = 'right'\n x_name = 'x'\n y_name = 'y'\n", "repository": "enthought/graphcanvas", "test_name": "test_set_delta", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000719.py"} {"focal_file": "graphcanvas/graph_node_drag_tool.py", "focal_class": null, "focal_method": "dragging", "tests": "import unittest\n\nclass Test_dragging(unittest.TestCase):\n def test_dragging(self):\n mock_window = self.create_mock_window()\n mock_window.get_pointer_position = mock.Mock(return_value=(0, 0))\n self.tool.original_screen_point = (0, 0)\n self.tool.original_data_point = (0, 0)\n event = self.create_drag_event(window=mock_window)\n self.tool.dragging(event)\n mock_window.set_pointer.assert_called_once_with('hand')\n", "method_code": " def dragging(self, event):\n event.window.set_pointer('hand')\n super(GraphNodeDragTool, self).dragging(event)\n ", "context": "class GraphNodeDragTool(ValueDragTool):\n def dragging(self, event): ...\n def get_value(self): ...\n def set_delta(self, value, delta_x, delta_y): ...\n\n drag_button = 'right'\n x_name = 'x'\n y_name = 'y'\n", "repository": "enthought/graphcanvas", "test_name": "test_dragging", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000720.py"} {"focal_file": "graphcanvas/graph_view.py", "focal_class": null, "focal_method": "graph_from_dict", "tests": "import unittest\n\nclass Test_graph_from_dict(unittest.TestCase):\n def test_graph_from_dict(self):\n d = {'a': ['b'], 'b': ['c', 'd'], 'c': [], 'd': [], 'e': ['d']}\n g = graph_from_dict(d)\n for key, value in d.items():\n children = g.successors(key)\n expected_children = value\n self.assertListEqual(sorted(children), sorted(expected_children))\n", "method_code": "def graph_from_dict(d):\n \"\"\" Creates a NetworkX Graph from a dictionary\n\n Parameters\n ----------\n d : dict\n\n Returns\n -------\n Graph: NetworkX Graph\n\n Examples\n --------\n >>> g = graph_from_dict({'a':['b'], 'b':['c', 'd'], 'c':[], 'd':[], 'e':['d']})\n \"\"\"\n g = networkx.DiGraph()\n for key, children in d.items():\n for child in children:\n g.add_edge(key, child)\n return g", "context": "def graph_from_dict(d): ...\ndef graph_from_dict(d): ...\n", "repository": "enthought/graphcanvas", "test_name": "test_graph_from_dict", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000721.py"} {"focal_file": "mysqlTools/mysql_utilities/bs4/element.py", "focal_class": null, "focal_method": "decode", "tests": "import unittest\n\nclass Test_decode(unittest.TestCase):\n def test_real_shift_jis_document(self):\n shift_jis_html = b'
\\x82\\xb1\\x82\\xea\\x82\\xcdShift-JIS\\x82\\xc5\\x83R\\x81[\\x83f\\x83B\\x83\\x93\\x83O\\x82\\xb3\\x82\\xea\\x82\\xbd\\x93\\xfa\\x96{\\x8c\\xea\\x82\\xcc\\x83t\\x83@\\x83C\\x83\\x8b\\x82\\xc5\\x82\\xb7\\x81B
'\n unicode_html = shift_jis_html.decode('shift-jis')\n soup = self.soup(unicode_html)\n self.assertEqual(soup.encode('utf-8'), unicode_html.encode('utf-8'))\n self.assertEqual(soup.encode('euc_jp'), unicode_html.encode('euc_jp'))\n\n def test_real_hebrew_document(self):\n hebrew_document = b'Hebrew (ISO 8859-8) in Visual Directionality

Hebrew (ISO 8859-8) in Visual Directionality

\\xed\\xe5\\xec\\xf9'\n soup = self.soup(hebrew_document, from_encoding='iso8859-8')\n self.assertEqual(soup.original_encoding, 'iso8859-8')\n self.assertEqual(soup.encode('utf-8'), hebrew_document.decode('iso8859-8').encode('utf-8'))\n", "method_code": " def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):\n \"\"\"Returns a Unicode representation of this tag and its contents.\n \n :param eventual_encoding: The tag is destined to be\n encoded into this encoding. This method is _not_\n responsible for performing that encoding. This information\n is passed in so that it can be substituted in if the\n document contains a tag that mentions the document's\n encoding.\n \"\"\"\n attrs = []\n if self.attrs:\n for key, val in sorted(self.attrs.items()):\n if val is None:\n decoded = key\n else:\n if isinstance(val, list) or isinstance(val, tuple):\n val = ' '.join(val)\n elif not isinstance(val, basestring):\n val = str(val)\n elif isinstance(val, AttributeValueWithCharsetSubstitution) and eventual_encoding is not None:\n val = val.encode(eventual_encoding)\n text = self.format_string(val, formatter)\n decoded = str(key) + '=' + EntitySubstitution.quoted_attribute_value(text)\n attrs.append(decoded)\n close = ''\n closeTag = ''\n if self.is_empty_element:\n close = '/'\n else:\n closeTag = '' % self.name\n prefix = ''\n if self.prefix:\n prefix = self.prefix + ':'\n pretty_print = indent_level is not None\n if pretty_print:\n space = ' ' * (indent_level - 1)\n indent_contents = indent_level + 1\n else:\n space = ''\n indent_contents = None\n contents = self.decode_contents(indent_contents, eventual_encoding, formatter)\n if self.hidden:\n s = contents\n else:\n s = []\n attribute_string = ''\n if attrs:\n attribute_string = ' ' + ' '.join(attrs)\n if pretty_print:\n s.append(space)\n s.append('<%s%s%s%s>' % (prefix, self.name, attribute_string, close))\n if pretty_print:\n s.append('\\n')\n s.append(contents)\n if pretty_print and contents and (contents[-1] != '\\n'):\n s.append('\\n')\n if pretty_print and closeTag:\n s.append(space)\n s.append(closeTag)\n if pretty_print and closeTag and self.next_sibling:\n s.append('\\n')\n s = ''.join(s)\n return s\n ", "context": "class Tag(PageElement):\n def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None): ...\n def is_empty_element(self): ...\n def string(self): ...\n def string(self, string): ...\n def _all_strings(self, strip=False): ...\n def stripped_strings(self): ...\n def get_text(self, separator='', strip=False): ...\n def decompose(self): ...\n def clear(self, decompose=False): ...\n def index(self, element): ...\n def get(self, key, default=None): ...\n def has_attr(self, key): ...\n def __hash__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __contains__(self, x): ...\n def __nonzero__(self): ...\n def __setitem__(self, key, value): ...\n def __delitem__(self, key): ...\n def __call__(self, *args, **kwargs): ...\n def __getattr__(self, tag): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): ...\n def __unicode__(self): ...\n def __str__(self): ...\n def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, indent_level=None, formatter='minimal', errors='xmlcharrefreplace'): ...\n def prettify(self, encoding=None, formatter='minimal'): ...\n def decode_contents(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def encode_contents(self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): ...\n def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): ...\n def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): ...\n def children(self): ...\n def descendants(self): ...\n def childGenerator(self): ...\n def recursiveChildGenerator(self): ...\n\n self.name = name\n self.namespace = namespace\n self.prefix = prefix\n self.attrs = attrs\n self.contents = []\n self.hidden = False\n\n parserClass = _alias('parser_class')\n isSelfClosing = is_empty_element\n strings = property(_all_strings)\n getText = get_text\n text = property(get_text)\n findChild = find\n findAll = find_all\n findChildren = find_all\n has_key = has_attr\n", "repository": "xiepaup/dbatools", "test_name": "test_real_shift_jis_document", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000722.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/my_print_defaults.py", "focal_class": null, "focal_method": "my_login_config_path", "tests": "import unittest\n\nclass Test_my_login_config_path(unittest.TestCase):\n def test_my_login_config_path(self):\n path = my_login_config_path()\n self.assertTrue(os.path.isdir(path))\n", "method_code": "def my_login_config_path():\n \"\"\"Return the default path of the mylogin file (.mylogin.cnf).\n \"\"\"\n if os.name == 'posix':\n return os.path.expanduser('~')\n else:\n return os.environ['APPDATA'] + '\\\\MySQL'", "context": "def my_login_config_path(): ...\ndef my_login_config_path(): ...\ndef my_login_config_exists(): ...\n", "repository": "xiepaup/dbatools", "test_name": "test_my_login_config_path", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000723.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/my_print_defaults.py", "focal_class": null, "focal_method": "my_login_config_exists", "tests": "import unittest\n\nclass Test_my_login_config_exists(unittest.TestCase):\n def test_my_login_config_exists(self):\n self.assertTrue(my_login_config_exists())\n", "method_code": "def my_login_config_exists():\n \"\"\"Check if the mylogin file (.mylogin.cnf) exists.\n \"\"\"\n my_login_fullpath = os.path.normpath(my_login_config_path() + '/' + _MYLOGIN_FILE)\n return os.path.isfile(my_login_fullpath)", "context": "def my_login_config_exists(): ...\ndef my_login_config_path(): ...\ndef my_login_config_exists(): ...\n", "repository": "xiepaup/dbatools", "test_name": "test_my_login_config_exists", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000724.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/my_print_defaults.py", "focal_class": "MyDefaultsReader", "focal_method": "search_my_print_defaults_tool", "tests": "import unittest\n\nclass Test_MyDefaultsReader_search_my_print_defaults_tool(unittest.TestCase):\n def test_search_my_print_defaults_tool(self):\n cfg_reader = MyDefaultsReader(find_my_print_defaults_tool=False)\n self.assertIsNone(cfg_reader.tool_path)\n cfg_reader.search_my_print_defaults_tool()\n self.assertTrue(os.path.isfile(cfg_reader.tool_path))\n tool_dir = os.path.dirname(cfg_reader.tool_path)\n os.environ['PATH'] = ''\n cfg_reader = MyDefaultsReader(find_my_print_defaults_tool=False)\n self.assertIsNone(cfg_reader.tool_path)\n self.assertRaises(UtilError, cfg_reader.search_my_print_defaults_tool)\n self.assertRaises(UtilError, cfg_reader.search_my_print_defaults_tool, ['not-a-valid-path'])\n cfg_reader.search_my_print_defaults_tool(['not-a-valid-path', tool_dir])\n self.assertTrue(os.path.isfile(cfg_reader.tool_path))\n", "method_code": " def search_my_print_defaults_tool(self, search_paths=[]):\n \"\"\"Search for the tool my_print_defaults.\n \"\"\"\n default_paths = [my_login_config_path()]\n if search_paths:\n default_paths.extend(search_paths)\n try:\n self._tool_path = get_tool_path(self._basedir, _MY_PRINT_DEFAULTS_TOOL, defaults_paths=default_paths, search_PATH=True)\n except UtilError as err:\n raise UtilError('Unable to locate MySQL Client tools. Please confirm that the path to the MySQL client tools are included in the PATH. Error: %s' % err.errmsg)\n ", "context": "class MyDefaultsReader(object):\n def search_my_print_defaults_tool(self, search_paths=[]): ...\n def __init__(self, options={}, find_my_print_defaults_tool=True): ...\n def tool_path(self): ...\n def check_tool_version(self, major_version, minor_version): ...\n def check_login_path_support(self): ...\n def _read_group_data(self, group): ...\n def get_group_data(self, group): ...\n def get_option_value(self, group, opt_name): ...\n\n self._config_data = {}\n", "repository": "xiepaup/dbatools", "test_name": "test_search_my_print_defaults_tool", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000725.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/my_print_defaults.py", "focal_class": "MyDefaultsReader", "focal_method": "check_tool_version", "tests": "import unittest\n\nclass Test_MyDefaultsReader_check_tool_version(unittest.TestCase):\n def test_check_tool_version(self):\n cfg_reader = MyDefaultsReader()\n self.assertTrue(cfg_reader.check_tool_version(1, 6), 'Only version 1.6 or above of my_prints_defaults tool is supported. Please add the location of a supported tool version to your PATH (at the beginning).')\n self.assertTrue(cfg_reader.check_tool_version(1, 0))\n self.assertFalse(cfg_reader.check_tool_version(1, 99))\n self.assertFalse(cfg_reader.check_tool_version(99, 0))\n self.assertTrue(cfg_reader.check_tool_version(0, 0))\n self.assertTrue(cfg_reader.check_tool_version(0, 99))\n", "method_code": " def check_tool_version(self, major_version, minor_version):\n \"\"\"Check the version of the my_print_defaults tool.\n \n Returns True if the version of the tool is equal or above the one that\n is specified, otherwise False.\n \"\"\"\n assert self._tool_path, 'First, the required MySQL tool must be found. E.g., use method search_my_print_defaults_tool.'\n out_file = tempfile.TemporaryFile()\n if self._verbosity > 0:\n subprocess.call([self._tool_path, '--version'], stdout=out_file)\n else:\n null_file = open(os.devnull, 'w+b')\n subprocess.call([self._tool_path, '--version'], stdout=out_file, stderr=null_file)\n out_file.seek(0)\n line = out_file.readline()\n out_file.close()\n match = re.search('(?:Ver )(\\\\d)\\\\.(\\\\d)', line)\n if match:\n major, minor = match.groups()\n if major_version < int(major) or (major_version == int(major) and minor_version <= int(minor)):\n return True\n else:\n return False\n else:\n raise UtilError('Unable to determine tool version - %s' % self._tool_path)\n ", "context": "class MyDefaultsReader(object):\n def check_tool_version(self, major_version, minor_version): ...\n def __init__(self, options={}, find_my_print_defaults_tool=True): ...\n def tool_path(self): ...\n def search_my_print_defaults_tool(self, search_paths=[]): ...\n def check_login_path_support(self): ...\n def _read_group_data(self, group): ...\n def get_group_data(self, group): ...\n def get_option_value(self, group, opt_name): ...\n\n self._config_data = {}\n", "repository": "xiepaup/dbatools", "test_name": "test_check_tool_version", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000726.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/my_print_defaults.py", "focal_class": "MyDefaultsReader", "focal_method": "check_login_path_support", "tests": "import unittest\n\nclass Test_MyDefaultsReader_check_login_path_support(unittest.TestCase):\n def test_check_login_path_support(self):\n cfg_reader = MyDefaultsReader()\n self.assertTrue(cfg_reader.check_login_path_support(), 'The used my_prints_defaults tool does not support login-path options: %s. Please add the location of atool that support login-path to your PATH (at the beginning).' % cfg_reader.tool_path)\n", "method_code": " def check_login_path_support(self):\n \"\"\"Checks if the used my_print_defaults tool supports login-paths.\n \"\"\"\n assert self._tool_path, 'First, the required MySQL tool must be found. E.g., use method search_my_print_defaults_tool.'\n out_file = tempfile.TemporaryFile()\n if self._verbosity > 0:\n subprocess.call([self._tool_path, '--help'], stdout=out_file)\n else:\n null_file = open(os.devnull, 'w+b')\n subprocess.call([self._tool_path, '--help'], stdout=out_file, stderr=null_file)\n out_file.seek(0)\n help_output = out_file.read()\n out_file.close()\n if 'login-path' in help_output:\n return True\n else:\n return False\n ", "context": "class MyDefaultsReader(object):\n def check_login_path_support(self): ...\n def __init__(self, options={}, find_my_print_defaults_tool=True): ...\n def tool_path(self): ...\n def search_my_print_defaults_tool(self, search_paths=[]): ...\n def check_tool_version(self, major_version, minor_version): ...\n def _read_group_data(self, group): ...\n def get_group_data(self, group): ...\n def get_option_value(self, group, opt_name): ...\n\n self._config_data = {}\n", "repository": "xiepaup/dbatools", "test_name": "test_check_login_path_support", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000727.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/my_print_defaults.py", "focal_class": "MyDefaultsReader", "focal_method": "get_group_data", "tests": "import unittest\n\nclass Test_MyDefaultsReader_get_group_data(unittest.TestCase):\n def test_get_group_data(self):\n cfg_reader = MyDefaultsReader(find_my_print_defaults_tool=False)\n self.assertRaises(AssertionError, cfg_reader.get_group_data, _TEST_LOGIN_PATH)\n cfg_reader.search_my_print_defaults_tool()\n expected_res = {'host': _TEST_HOST, 'user': _TEST_USER}\n start_time1 = time.time()\n grp_data = cfg_reader.get_group_data(_TEST_LOGIN_PATH)\n end_time1 = time.time()\n self.assertEqual(expected_res, grp_data)\n start_time2 = time.time()\n grp_data = cfg_reader.get_group_data(_TEST_LOGIN_PATH)\n end_time2 = time.time()\n self.assertEqual(expected_res, grp_data)\n self.assertLess(end_time2 - start_time2, end_time1 - start_time1)\n grp_data = cfg_reader.get_group_data(_TEST_UNKNOWN_LOGIN_PATH)\n self.assertIsNone(grp_data)\n", "method_code": " def get_group_data(self, group):\n \"\"\"Retrieve the data associated to the given group.\n \"\"\"\n try:\n return self._config_data[group]\n except KeyError:\n return self._read_group_data(group)\n ", "context": "class MyDefaultsReader(object):\n def get_group_data(self, group): ...\n def __init__(self, options={}, find_my_print_defaults_tool=True): ...\n def tool_path(self): ...\n def search_my_print_defaults_tool(self, search_paths=[]): ...\n def check_tool_version(self, major_version, minor_version): ...\n def check_login_path_support(self): ...\n def _read_group_data(self, group): ...\n def get_option_value(self, group, opt_name): ...\n\n self._config_data = {}\n", "repository": "xiepaup/dbatools", "test_name": "test_get_group_data", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000728.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/my_print_defaults.py", "focal_class": "MyDefaultsReader", "focal_method": "get_option_value", "tests": "import unittest\n\nclass Test_MyDefaultsReader_get_option_value(unittest.TestCase):\n def test_get_option_value(self):\n cfg_reader = MyDefaultsReader(find_my_print_defaults_tool=False)\n self.assertRaises(AssertionError, cfg_reader.get_option_value, _TEST_LOGIN_PATH, _TEST_HOST)\n self.assertRaises(AssertionError, cfg_reader.get_option_value, _TEST_LOGIN_PATH, _TEST_USER)\n cfg_reader.search_my_print_defaults_tool()\n expected_res = {'host': _TEST_HOST, 'user': _TEST_USER}\n opt_value = cfg_reader.get_option_value(_TEST_LOGIN_PATH, 'user')\n self.assertEqual(expected_res['user'], opt_value)\n opt_value = cfg_reader.get_option_value(_TEST_LOGIN_PATH, 'host')\n self.assertEqual(expected_res['host'], opt_value)\n opt_value = cfg_reader.get_option_value(_TEST_LOGIN_PATH, 'unknown')\n self.assertIsNone(opt_value)\n opt_value = cfg_reader.get_option_value(_TEST_UNKNOWN_LOGIN_PATH, 'user')\n self.assertIsNone(opt_value)\n opt_value = cfg_reader.get_option_value(_TEST_UNKNOWN_LOGIN_PATH, 'host')\n self.assertIsNone(opt_value)\n", "method_code": " def get_option_value(self, group, opt_name):\n \"\"\"Retrieve the value associated to the given opt_name in the group.\n \"\"\"\n grp_options = self.get_group_data(group)\n if grp_options:\n return grp_options.get(opt_name, None)\n else:\n return None\n ", "context": "class MyDefaultsReader(object):\n def get_option_value(self, group, opt_name): ...\n def __init__(self, options={}, find_my_print_defaults_tool=True): ...\n def tool_path(self): ...\n def search_my_print_defaults_tool(self, search_paths=[]): ...\n def check_tool_version(self, major_version, minor_version): ...\n def check_login_path_support(self): ...\n def _read_group_data(self, group): ...\n def get_group_data(self, group): ...\n\n self._config_data = {}\n", "repository": "xiepaup/dbatools", "test_name": "test_get_option_value", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000729.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_get_next_line", "tests": "import unittest\n\nclass Test_get_next_line(unittest.TestCase):\n def test_get_next_line(self):\n \"\"\"Get the next line from the log file\"\"\"\n data = ('# Line 1', '# Line 2')\n self._fakelog_writelines(data, empty=True)\n self.assertEqual(data[0], self.log._get_next_line())\n self.assertEqual(data[1], self.log._get_next_line())\n self.log._stream.seek(0, os.SEEK_END)\n self.assertEqual(None, self.log._get_next_line())\n", "method_code": " def _get_next_line(self):\n \"\"\"Get next line from the log file\n \n This method reads the next line from the stream. Trailing\n newline (\n ) and carraige return (\\r) are removed.\n \n Returns next line as string or None\n \"\"\"\n line = self._stream.readline()\n if not line:\n return None\n return line.rstrip('\\r\\n')\n ", "context": "class LogParserBase(object):\n def _get_next_line(self): ...\n def __init__(self, stream): ...\n def _parse_header(self, line): ...\n def version(self): ...\n def program(self): ...\n def port(self): ...\n def socket(self): ...\n def start_datetime(self): ...\n def last_seen_datetime(self): ...\n def __iter__(self): ...\n def next(self): ...\n def __str__(self): ...\n\n self._stream = None\n self._version = None\n self._program = None\n self._port = None\n self._socket = None\n self._start_datetime = None\n self._last_seen_datetime = None\n", "repository": "xiepaup/dbatools", "test_name": "test_get_next_line", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000730.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_parse_header", "tests": "import unittest\n\nclass Test_parse_header(unittest.TestCase):\n def test_parse_header(self):\n \"\"\"Parse the header of a MySQL log file\"\"\"\n self.assertRaises(LogParserError, self.log._parse_header, 'Ham Spam')\n self.assertEqual(None, self.log._parse_header(None))\n", "method_code": " def _parse_header(self, line):\n \"\"\"Parse the header of a MySQL log file\n \n line[in] A string, usually result of self._get_next_line()\n \n This method parses the header of a MySQL log file, that is the header\n found in the General and Slow Query log files. It sets attributes\n _version, _program, _port and _socket.\n Note that headers can repeat in a log file, for example, after a restart\n of the MySQL server.\n \n Example header:\n /usr/sbin/mysqld, Version: 5.5.17-log (Source distribution). started with:\n Tcp port: 0 Unix socket: /tmp/mysql.sock\n Time Id Command Argument\n \n Raises LogParserError on errors.\n \"\"\"\n if line is None:\n return\n info = _HEADER_VERSION_CRE.match(line)\n if not info:\n raise LogParserError('Could not read executable and version from header')\n program, major, minor, patch, extra = info.groups()\n line = self._get_next_line()\n info = _HEADER_SERVER_CRE.match(line)\n if not info:\n raise LogParserError('Malformed server header line: %s' % line)\n tcp_port, unix_socket = info.groups()\n self._get_next_line()\n self._version = (int(major), int(minor), int(patch), extra)\n self._program = program\n self._port = int(tcp_port)\n self._socket = unix_socket\n ", "context": "class LogParserBase(object):\n def _parse_header(self, line): ...\n def __init__(self, stream): ...\n def _get_next_line(self): ...\n def version(self): ...\n def program(self): ...\n def port(self): ...\n def socket(self): ...\n def start_datetime(self): ...\n def last_seen_datetime(self): ...\n def __iter__(self): ...\n def next(self): ...\n def __str__(self): ...\n\n self._stream = None\n self._version = None\n self._program = None\n self._port = None\n self._socket = None\n self._start_datetime = None\n self._last_seen_datetime = None\n", "repository": "xiepaup/dbatools", "test_name": "test_parse_header", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000731.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_new_session", "tests": "import unittest\n\nclass Test_new_session(unittest.TestCase):\n def test__new_session(self):\n \"\"\"Add a new session\"\"\"\n session_id = 1\n exp = dict(database=None, user=None, host=None, time_last_action=None, to_delete=False)\n self.log._new_session(session_id)\n self.assertEqual(exp, self.log._sessions[session_id])\n", "method_code": " def _new_session(self, session_id):\n \"\"\"Create a new session using the given session ID\n \n session_id[in] integer presenting a MySQL session\n \n Returns a dictionary.\n \"\"\"\n self._sessions[session_id] = dict(database=None, user=None, host=None, time_last_action=None, to_delete=False)\n return self._sessions[session_id]\n ", "context": "class GeneralQueryLog(LogParserBase):\n def _new_session(self, session_id): ...\n def __init__(self, stream): ...\n def _handle_connect(self, entry, session, argument): ...\n def _handle_init_db(self, entry, session, argument): ...\n def _handle_multi_line(self, entry, session, argument): ...\n def _handle_quit(self, entry, session, argument): ...\n def _parse_command(self, logentry, entry): ...\n def _parse_entry(self): ...\n\n self._sessions = {}\n self._cached_logentry = None\n self._commands = {'Quit': self._handle_quit, 'Init DB': self._handle_init_db, 'Query': self._handle_multi_line, 'Connect': self._handle_connect, 'Prepare': self._handle_multi_line, 'Execute': self._handle_multi_line, 'Fetch': self._handle_multi_line}\n", "repository": "xiepaup/dbatools", "test_name": "test__new_session", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000732.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_parse_command", "tests": "import unittest\n\nclass Test_parse_command(unittest.TestCase):\n def test_parse_command(self):\n \"\"\"Parse a line from General Query Log having a command\"\"\"\n self.assertEqual(None, self.log._parse_command(None, None))\n", "method_code": " def _parse_command(self, logentry, entry):\n \"\"\"Parse a log entry from the General Query Log\n \n logentry[in] a string or tuple\n entry[in] an instance of GeneralQueryLogEntry\n \n The logentry-parameter is either a line read from the log file or\n the result of a previous attempt to read a command.\n The entry argument should be an instance of GeneralQueryLogEntry.\n It returns the entry or None if nothing could be read.\n \n Raises LogParserError on errors.\n \n Returns the GeneralQueryLogEntry-instance or None\n \"\"\"\n if logentry is None:\n return None\n if isinstance(logentry, tuple):\n dt, session_id, command, argument = logentry\n elif logentry.endswith('started with:'):\n while logentry.endswith('started with:'):\n self._parse_header(logentry)\n logentry = self._get_next_line()\n if logentry is None:\n return None\n return self._parse_command(logentry, entry)\n else:\n info = _GENERAL_ENTRY_CRE.match(logentry)\n if info is None:\n raise LogParserError('Failed parsing command line: %s' % logentry)\n dt, session_id, command, argument = info.groups()\n self._cached_logentry = None\n session_id = int(session_id)\n entry['session_id'] = session_id\n try:\n session = self._sessions[session_id]\n except KeyError:\n session = self._new_session(session_id)\n entry['command'] = command\n if dt is not None:\n entry['datetime'] = datetime.datetime.strptime(dt, '%y%m%d %H:%M:%S')\n session['time_last_action'] = entry['datetime']\n else:\n entry['datetime'] = session['time_last_action']\n try:\n self._commands[command](entry, session, argument)\n except KeyError:\n entry['argument'] = argument\n for key in entry.keys():\n if key in session:\n entry[key] = session[key]\n if session['to_delete'] is True:\n del self._sessions[session_id]\n del session\n return entry\n ", "context": "class GeneralQueryLog(LogParserBase):\n def _parse_command(self, logentry, entry): ...\n def __init__(self, stream): ...\n def _new_session(self, session_id): ...\n def _handle_connect(self, entry, session, argument): ...\n def _handle_init_db(self, entry, session, argument): ...\n def _handle_multi_line(self, entry, session, argument): ...\n def _handle_quit(self, entry, session, argument): ...\n def _parse_entry(self): ...\n\n self._sessions = {}\n self._cached_logentry = None\n self._commands = {'Quit': self._handle_quit, 'Init DB': self._handle_init_db, 'Query': self._handle_multi_line, 'Connect': self._handle_connect, 'Prepare': self._handle_multi_line, 'Execute': self._handle_multi_line, 'Fetch': self._handle_multi_line}\n", "repository": "xiepaup/dbatools", "test_name": "test_parse_command", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000733.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_parse_entry", "tests": "import unittest\n\nclass Test_parse_entry(unittest.TestCase):\n def test_parse_entry(self):\n \"\"\"Parse a Slow Query Log entry\"\"\"\n self.assertEqual(None, self.log._parse_entry())\n for i, data in enumerate(SLOW_LOG_ENTRIES):\n self._fakelog_writelines(data, empty=True)\n self.assertEqual(SLOW_LOG_ENTRIES_EXP[i], self.log._parse_entry())\n self.log = SlowQueryLog(stream=self.fakelog)\n for i, data in enumerate(LOG_HEADERS):\n self._fakelog_writelines(data, empty=True)\n self.log._parse_entry()\n self.check_attributes(self.log, LOG_HEADERS_EXP[i])\n", "method_code": " def _parse_entry(self):\n \"\"\"Returns a parsed log entry\n \n The method _parse_entry() uses _parse_command() to parse\n a General Query Log entry. It is used by the iterator protocol methods.\n \n Returns a GeneralQueryLogEntry-instance or None.\n \"\"\"\n entry = GeneralQueryLogEntry()\n if self._cached_logentry is not None:\n self._parse_command(self._cached_logentry, entry)\n return entry\n else:\n line = self._get_next_line()\n if line is None:\n return None\n self._parse_command(line, entry)\n return entry\n ", "context": "class GeneralQueryLog(LogParserBase):\n def _parse_entry(self): ...\n def __init__(self, stream): ...\n def _new_session(self, session_id): ...\n def _handle_connect(self, entry, session, argument): ...\n def _handle_init_db(self, entry, session, argument): ...\n def _handle_multi_line(self, entry, session, argument): ...\n def _handle_quit(self, entry, session, argument): ...\n def _parse_command(self, logentry, entry): ...\n\n self._sessions = {}\n self._cached_logentry = None\n self._commands = {'Quit': self._handle_quit, 'Init DB': self._handle_init_db, 'Query': self._handle_multi_line, 'Connect': self._handle_connect, 'Prepare': self._handle_multi_line, 'Execute': self._handle_multi_line, 'Fetch': self._handle_multi_line}\n", "repository": "xiepaup/dbatools", "test_name": "test_parse_entry", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000734.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "next", "tests": "import unittest\n\nclass Test_next(unittest.TestCase):\n def test_next(self):\n \"\"\"Iterate through the log, reading entries (.next()-method)\"\"\"\n self.assertRaises(StopIteration, self.log.next)\n data = SLOW_LOG_ENTRIES[0]\n exp = SLOW_LOG_ENTRIES_EXP[0]\n self._fakelog_writelines(data, empty=True, rewind=True)\n self.assertEqual(exp, self.log.next())\n self.assertRaises(StopIteration, self.log.next)\n", "method_code": " def next(self):\n \"\"\"Returns the next log entry\n \n Raises StopIteration when no more entries are available.\n \n Returns a LogEntryBase-object.\n \"\"\"\n entry = self._parse_entry()\n if entry is None:\n raise StopIteration\n return entry\n ", "context": "class LogParserBase(object):\n def next(self): ...\n def __init__(self, stream): ...\n def _get_next_line(self): ...\n def _parse_header(self, line): ...\n def version(self): ...\n def program(self): ...\n def port(self): ...\n def socket(self): ...\n def start_datetime(self): ...\n def last_seen_datetime(self): ...\n def __iter__(self): ...\n def __str__(self): ...\n\n self._stream = None\n self._version = None\n self._program = None\n self._port = None\n self._socket = None\n self._start_datetime = None\n self._last_seen_datetime = None\n", "repository": "xiepaup/dbatools", "test_name": "test_next", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000735.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_parse_line", "tests": "import unittest\n\nclass Test_parse_line(unittest.TestCase):\n def test_parse_line(self):\n \"\"\"Parse a log line using regular expression Match-object\"\"\"\n regex = re.compile('(\\\\d{1}) (\\\\d{2}) (\\\\d{3}) (\\\\w{3})')\n line = '1 12 123 ham'\n exp = ('1', '12', '123', 'ham')\n self.assertEqual(exp, self.log._parse_line(regex, line))\n line = 'spam'\n self.assertRaises(LogParserError, self.log._parse_line, regex, line)\n", "method_code": " def _parse_line(self, regex, line):\n \"\"\"Parses a log line using given regular expression\n \n regex[in] a SRE_Match-object\n line[in] a string\n \n This function takes a log line and matches the regular expresion given\n with the regex argument. It returns the result of\n re.MatchObject.groups(), which is a tuple.\n \n Raises LogParserError on errors.\n \n Returns a tuple.\n \"\"\"\n info = regex.match(line)\n if info is None:\n raise LogParserError('Failed parsing Slow Query line: %s' % line[:30])\n return info.groups()\n ", "context": "class SlowQueryLog(LogParserBase):\n def _parse_line(self, regex, line): ...\n def __init__(self, stream): ...\n def _parse_connection_info(self, line, entry): ...\n def _parse_timestamp(self, line, entry): ...\n def _parse_statistics(self, line, entry): ...\n def _parse_query(self, line, entry): ...\n def _parse_entry(self): ...\n\n self._cached_line = None\n self._current_database = None\n", "repository": "xiepaup/dbatools", "test_name": "test_parse_line", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000736.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_parse_connection_info", "tests": "import unittest\n\nclass Test_parse_connection_info(unittest.TestCase):\n def test_parse_connection_info(self):\n \"\"\"Get connection info from a slow query log entry\"\"\"\n tests = [('# User@Host: root[root] @ localhost []', dict(user='root', host='localhost')), ('# User@Host: root[root] @ localhost [127.0.0.1]', dict(user='root', host='localhost')), ('# User@Host: root[root] @ [127.0.0.1]', dict(user='root', host='127.0.0.1')), ('# User@Host: [ham] @ localhost []', dict(user='ham', host='localhost')), ('# User@Host: [ham] @ [127.0.0.1]', dict(user='ham', host='127.0.0.1'))]\n for data, exp in tests:\n result = dict()\n try:\n self.log._parse_connection_info(data, result)\n except LogParserError:\n self.fail(\"Failed parsing (correct) line: '%s'\" % data)\n self.assertEqual(exp, result)\n self.assertRaises(LogParserError, self.log._parse_connection_info, 'ham spam ham spam', dict())\n", "method_code": " def _parse_connection_info(self, line, entry):\n \"\"\"Parses connection info\n \n line[in] a string\n entry[in] a SlowQueryLog-instance\n \n The line paramater should be a string, a line read from the Slow Query\n Log. The entry argument should be an instance of SlowQueryLogEntry.\n \n Raises LogParserError on failure.\n \"\"\"\n priv_user, unpriv_user, host, ip = self._parse_line(_SLOW_USERHOST_CRE, line)\n entry['user'] = priv_user if priv_user else unpriv_user\n entry['host'] = host if host else ip\n ", "context": "class SlowQueryLog(LogParserBase):\n def _parse_connection_info(self, line, entry): ...\n def __init__(self, stream): ...\n def _parse_line(self, regex, line): ...\n def _parse_timestamp(self, line, entry): ...\n def _parse_statistics(self, line, entry): ...\n def _parse_query(self, line, entry): ...\n def _parse_entry(self): ...\n\n self._cached_line = None\n self._current_database = None\n", "repository": "xiepaup/dbatools", "test_name": "test_parse_connection_info", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000737.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_parse_timestamp", "tests": "import unittest\n\nclass Test_parse_timestamp(unittest.TestCase):\n def test_parse_timestamp(self):\n \"\"\"Get the timestamp of the slow query log entry\"\"\"\n tests = [('# Time: 111102 12:48:46', dict(datetime=datetime.datetime(2011, 11, 2, 12, 48, 46))), ('# Time: 111102 9:48:46', dict(datetime=datetime.datetime(2011, 11, 2, 9, 48, 46)))]\n for data, exp in tests:\n result = dict()\n try:\n self.log._parse_timestamp(data, result)\n except LogParserError:\n self.fail(\"Failed parsing (correct) line: '%s'\" % data)\n self.assertEqual(exp, result)\n self.assertRaises(LogParserError, self.log._parse_timestamp, 'ham spam ham spam', dict())\n", "method_code": " def _parse_timestamp(self, line, entry):\n \"\"\"Parses a timestamp\n \n line[in] a string\n entry[in] a SlowQueryLog-instance\n \n The line paramater should be a string, a line read from the Slow Query\n Log. The entry argument should be an instance of SlowQueryLogEntry.\n \n Raises LogParserError on failure.\n \"\"\"\n info = self._parse_line(_SLOW_TIMESTAMP_CRE, line)\n entry['datetime'] = datetime.datetime.strptime(info[0], '%y%m%d %H:%M:%S')\n if self._start_datetime is None:\n self._start_datetime = entry['datetime']\n self._last_seen_datetime = entry['datetime']\n ", "context": "class SlowQueryLog(LogParserBase):\n def _parse_timestamp(self, line, entry): ...\n def __init__(self, stream): ...\n def _parse_line(self, regex, line): ...\n def _parse_connection_info(self, line, entry): ...\n def _parse_statistics(self, line, entry): ...\n def _parse_query(self, line, entry): ...\n def _parse_entry(self): ...\n\n self._cached_line = None\n self._current_database = None\n", "repository": "xiepaup/dbatools", "test_name": "test_parse_timestamp", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000738.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_parse_statistics", "tests": "import unittest\n\nclass Test_parse_statistics(unittest.TestCase):\n def test_parse_statistics(self):\n \"\"\"Get statistics of the slow query log entry\"\"\"\n tests = [('# Query_time: 0.000333 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0', dict(query_time=decimal.Decimal('0.000333'), lock_time=decimal.Decimal('0.000000'), rows_examined=0, rows_sent=1)), ('# Query_time: 123.000333 Lock_time: 323.000001 Rows_sent: 12 Rows_examined: 34', dict(query_time=decimal.Decimal('123.000333'), lock_time=decimal.Decimal('323.000001'), rows_examined=34, rows_sent=12))]\n for data, exp in tests:\n result = dict()\n try:\n self.log._parse_statistics(data, result)\n except LogParserError:\n self.fail(\"Failed parsing (correct) line: '%s'\" % data)\n self.assertEqual(exp, result)\n self.assertRaises(LogParserError, self.log._parse_statistics, 'ham spam ham spam', dict())\n", "method_code": " def _parse_statistics(self, line, entry):\n \"\"\"Parses statistics information\n \n line[in] a string\n entry[in] a SlowQueryLog-instance\n \n The line paramater should be a string, a line read from the Slow Query\n Log. The entry argument should be an instance of SlowQueryLogEntry.\n \n Raises LogParserError on errors.\n \"\"\"\n result = self._parse_line(_SLOW_STATS_CRE, line)\n entry['query_time'] = decimal.Decimal(result[0])\n entry['lock_time'] = decimal.Decimal(result[1])\n entry['rows_sent'] = int(result[2])\n entry['rows_examined'] = int(result[3])\n ", "context": "class SlowQueryLog(LogParserBase):\n def _parse_statistics(self, line, entry): ...\n def __init__(self, stream): ...\n def _parse_line(self, regex, line): ...\n def _parse_connection_info(self, line, entry): ...\n def _parse_timestamp(self, line, entry): ...\n def _parse_query(self, line, entry): ...\n def _parse_entry(self): ...\n\n self._cached_line = None\n self._current_database = None\n", "repository": "xiepaup/dbatools", "test_name": "test_parse_statistics", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000739.py"} {"focal_file": "mysqlTools/mysql_utilities/mysql/utilities/common/parser.py", "focal_class": null, "focal_method": "_parse_query", "tests": "import unittest\n\nclass Test_parse_query(unittest.TestCase):\n def test_parse_query(self):\n \"\"\"Get the queries of a slow query log entry\"\"\"\n tests = [(('SET timestamp=1320234526;', 'select @@version_comment limit 1;'), dict(database=None, datetime=datetime.datetime.fromtimestamp(1320234526), query='SET timestamp=1320234526;\\nselect @@version_comment limit 1;')), (('SET timestamp=1320234526;', 'select c1', 'from t1', 'where c1 like \"%a%\";'), dict(database=None, datetime=datetime.datetime.fromtimestamp(1320234526), query='SET timestamp=1320234526;\\nselect c1\\nfrom t1\\nwhere c1 like \"%a%\";')), (('use test', 'SET timestamp=1320234526;', 'select @@version_comment limit 1;'), dict(database='test', datetime=datetime.datetime.fromtimestamp(1320234526), query='use test\\nSET timestamp=1320234526;\\nselect @@version_comment limit 1;'))]\n for data, exp in tests:\n self._fakelog_writelines(data, empty=True)\n result = dict(database=None, query=None)\n try:\n self.log._parse_query(self.log._get_next_line(), result)\n except LogParserError:\n self.fail(\"Failed parsing (correct) line: '%s'\" % data)\n self.assertEqual(exp, result)\n self._fakelog_writelines(tests[0][0], empty=True)\n result = dict(database=None, query=None)\n exp = dict(database='test', datetime=datetime.datetime.fromtimestamp(1320234526), query='SET timestamp=1320234526;\\nselect @@version_comment limit 1;')\n try:\n self.log._parse_query(self.log._get_next_line(), result)\n except LogParserError:\n self.fail(\"Failed parsing (correct) line: '%s'\" % data)\n self.assertEqual(exp, result)\n", "method_code": " def _parse_query(self, line, entry):\n \"\"\"Parses the query\n \n line[in] a string\n entry[in] a SlowQueryLog-instance\n \n The line paramater should be a string, a line read from the Slow Query\n Log. The entry argument should be an instance of SlowQueryLogEntry.\n \n Query entries in the Slow Query Log could span several lines. They can\n optionally start with a USE-command and have session variables, such as\n 'timestamp', set before the actual query.\n \"\"\"\n query = []\n while True:\n if line is None:\n break\n if line.startswith('use'):\n entry['database'] = self._current_database = line.split(' ')[1]\n elif line.startswith('SET timestamp='):\n entry['datetime'] = datetime.datetime.fromtimestamp(int(line[14:].strip(';')))\n elif line.startswith('# Time:') or line.startswith('# User@Host') or line.endswith('started with:'):\n break\n query.append(line)\n line = self._get_next_line()\n if 'database' in entry:\n if entry['database'] is None and self._current_database is not None:\n entry['database'] = self._current_database\n entry['query'] = '\\n'.join(query)\n self._cached_line = line\n ", "context": "class SlowQueryLog(LogParserBase):\n def _parse_query(self, line, entry): ...\n def __init__(self, stream): ...\n def _parse_line(self, regex, line): ...\n def _parse_connection_info(self, line, entry): ...\n def _parse_timestamp(self, line, entry): ...\n def _parse_statistics(self, line, entry): ...\n def _parse_entry(self): ...\n\n self._cached_line = None\n self._current_database = None\n", "repository": "xiepaup/dbatools", "test_name": "test_parse_query", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000740.py"} {"focal_file": "py_tree/directory_explorer.py", "focal_class": null, "focal_method": "build_tree", "tests": "import unittest\n\nclass Test_build_tree(unittest.TestCase):\n def test_build_tree(self):\n \"\"\"Test the build_tree method.\"\"\"\n direxp = DirectoryExplorer(start_dir=self.test_dir, show_hidden=False)\n tree = direxp.build_tree()\n level = 0\n current_node = tree.get_root()\n while current_node.get_children():\n children = [ch.get_name() for ch in current_node.get_children()]\n self.assertTrue(self.dir_pattern_a % level in children)\n self.assertTrue(self.dir_pattern_b % level in children)\n if current_node.get_name() is self.dir_pattern_a % (level - 1):\n files = current_node.get_files()\n self.assertTrue(self.file_pattern_a % level in files)\n self.assertTrue(self.file_pattern_b % level in files)\n symlinks = current_node.get_symlinks()\n self.assertTrue(self.symlink_pattern_a % level in symlinks)\n self.assertTrue(self.symlink_pattern_b % level in symlinks)\n level += 1\n current_node = current_node.get_children()[0]\n", "method_code": " def build_tree(self):\n \"\"\"Builds a DirectoryTree by BFSing through directory contents.\n \n This method is very similar to explore() except that this method builds\n and returns a DirectoryTree object instead of alist of tuples.\n \n Returns:\n A DirectoryTree object.\n \"\"\"\n result = DirectoryTree(self._start_dir)\n recursion_level = 0\n current_level = deque()\n next_level = deque()\n current_level.append((self._start_dir, result.get_root()))\n while len(current_level) != 0:\n current_dir, current_node = current_level.popleft()\n try:\n listdir_result = os.listdir(current_dir)\n except OSError:\n continue\n files, directories, symlinks = self._sort_and_filter(listdir_result, current_dir)\n current_node.add_files(files)\n current_node.add_symlinks(symlinks)\n for directory in directories:\n current_node.add_child(directory)\n if recursion_level != self._recursion_limit:\n next_level.append((os.path.join(current_dir, directory), current_node.get_last_child()))\n if len(current_level) == 0 and recursion_level < self._recursion_limit:\n current_level = next_level\n next_level = deque()\n recursion_level += 1\n return result\n ", "context": "class DirectoryExplorer(object):\n def build_tree(self): ...\n def __init__(self, start_dir='.', show_hidden=False, recursion_limit=10): ...\n def _sort_and_filter(self, raw_list, root): ...\n def explore(self): ...\n\n self._start_dir = start_dir\n self._show_hidden = show_hidden\n self._recursion_limit = recursion_limit\n", "repository": "tdeh/py-tree", "test_name": "test_build_tree", "smells": [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000741.py"} {"focal_file": "py_tree/directory_tree.py", "focal_class": null, "focal_method": "get_name", "tests": "import unittest\n\nclass Test_get_name(unittest.TestCase):\n def test_get_name(self):\n \"\"\"Test the get_name() method.\"\"\"\n self.assertEqual(self.node_name, self.node.get_name())\n", "method_code": " def get_name(self):\n \"\"\"Get the node's name.\n \n Returns:\n The name of the node.\n \"\"\"\n return self._name\n ", "context": "class DirectoryNode(object):\n def get_name(self): ...\n def __init__(self, name): ...\n def add_child(self, name): ...\n def add_file(self, filename): ...\n def add_files(self, file_list): ...\n def add_symlinks(self, symlink_list): ...\n def children(self): ...\n def files(self): ...\n def get_children(self): ...\n def get_files(self): ...\n def get_symlinks(self): ...\n def get_last_child(self): ...\n\n self._name = name\n self._child_dirs = []\n self._files = []\n self._symlinks = []\n", "repository": "tdeh/py-tree", "test_name": "test_get_name", "smells": [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000742.py"} {"focal_file": "py_tree/directory_tree.py", "focal_class": null, "focal_method": "get_children", "tests": "import unittest\n\nclass Test_get_children(unittest.TestCase):\n def test_add_child_get_children(self):\n \"\"\"Test add_child and get_children methods.\"\"\"\n n_children = 50\n name_template = 'child%i'\n for i in range(n_children):\n self.node.add_child(name_template % i)\n child_dirs = self.node.get_children()\n for i in range(n_children):\n self.assertEqual(child_dirs[i].get_name(), name_template % i)\n", "method_code": " def get_children(self):\n \"\"\"Get the list of child directory under this directory.\n \n Returns:\n List of child directory under this directory.\n \"\"\"\n return self._child_dirs\n ", "context": "class DirectoryNode(object):\n def get_children(self): ...\n def __init__(self, name): ...\n def add_child(self, name): ...\n def add_file(self, filename): ...\n def add_files(self, file_list): ...\n def add_symlinks(self, symlink_list): ...\n def children(self): ...\n def files(self): ...\n def get_name(self): ...\n def get_files(self): ...\n def get_symlinks(self): ...\n def get_last_child(self): ...\n\n self._name = name\n self._child_dirs = []\n self._files = []\n self._symlinks = []\n", "repository": "tdeh/py-tree", "test_name": "test_add_child_get_children", "smells": [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000743.py"} {"focal_file": "py_tree/directory_tree.py", "focal_class": null, "focal_method": "get_files", "tests": "import unittest\n\nclass Test_get_files(unittest.TestCase):\n def test_add_file_get_files(self):\n \"\"\"Test add_file and get_files methods.\"\"\"\n n_files = 50\n name_template = 'file%i'\n for i in range(n_files):\n self.node.add_file(name_template % i)\n files = self.node.get_files()\n for i in range(n_files):\n self.assertEqual(files[i], name_template % i)\n\n def test_add_files_get_files(self):\n \"\"\"Test add_files and get_files methods.\"\"\"\n n_files = 50\n file_list = []\n name_template = 'file%i'\n for i in range(n_files):\n file_list.append(name_template % i)\n self.node.add_files(file_list)\n files = self.node.get_files()\n for i in range(n_files):\n self.assertEqual(files[i], name_template % i)\n", "method_code": " def get_files(self):\n \"\"\"Get the list of files under this directory.\n \n Returns:\n List of files under this directory.\n \"\"\"\n return self._files\n ", "context": "class DirectoryNode(object):\n def get_files(self): ...\n def __init__(self, name): ...\n def add_child(self, name): ...\n def add_file(self, filename): ...\n def add_files(self, file_list): ...\n def add_symlinks(self, symlink_list): ...\n def children(self): ...\n def files(self): ...\n def get_name(self): ...\n def get_children(self): ...\n def get_symlinks(self): ...\n def get_last_child(self): ...\n\n self._name = name\n self._child_dirs = []\n self._files = []\n self._symlinks = []\n", "repository": "tdeh/py-tree", "test_name": "test_add_file_get_files", "smells": [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000744.py"} {"focal_file": "py_tree/directory_tree.py", "focal_class": null, "focal_method": "get_last_child", "tests": "import unittest\n\nclass Test_get_last_child(unittest.TestCase):\n def test_get_last_child(self):\n \"\"\"Test the get_last_child method.\"\"\"\n self.assertIsNone(self.node.get_last_child())\n n_children = 50\n name_template = 'child%i'\n for i in range(n_children):\n self.node.add_child(name_template % i)\n self.assertEqual(self.node.get_last_child().get_name(), name_template % (n_children - 1))\n", "method_code": " def get_last_child(self):\n \"\"\"Get the last child added to the list of children.\n \n Returns:\n Last child node added to list if list is not empty else None.\n \"\"\"\n try:\n return self._child_dirs[-1]\n except IndexError:\n return None\n ", "context": "class DirectoryNode(object):\n def get_last_child(self): ...\n def __init__(self, name): ...\n def add_child(self, name): ...\n def add_file(self, filename): ...\n def add_files(self, file_list): ...\n def add_symlinks(self, symlink_list): ...\n def children(self): ...\n def files(self): ...\n def get_name(self): ...\n def get_children(self): ...\n def get_files(self): ...\n def get_symlinks(self): ...\n\n self._name = name\n self._child_dirs = []\n self._files = []\n self._symlinks = []\n", "repository": "tdeh/py-tree", "test_name": "test_get_last_child", "smells": [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000745.py"} {"focal_file": "py_tree/directory_tree.py", "focal_class": null, "focal_method": "get_root", "tests": "import unittest\n\nclass Test_get_root(unittest.TestCase):\n def test_get_root(self):\n \"\"\"Test the get_root() method.\"\"\"\n root_name = 'root'\n tree = DirectoryTree(root_name)\n self.assertEqual(root_name, tree.get_root().get_name())\n", "method_code": " def get_root(self):\n \"\"\"Get the root of the tree.\n \n Returns:\n DirectoryNode: The root node of the tree.\n \"\"\"\n return self._root\n ", "context": "class DirectoryTree(object):\n def get_root(self): ...\n def __init__(self, root_name): ...\n\n self._root = DirectoryNode(root_name)\n", "repository": "tdeh/py-tree", "test_name": "test_get_root", "smells": [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000746.py"} {"focal_file": "py_tree/tree_printer.py", "focal_class": null, "focal_method": "print_tree", "tests": "import unittest\n\nclass Test_print_tree(unittest.TestCase):\n def test_print_tree_visits_all(self):\n \"\"\"Tests that print_tree will visit all nodes.\"\"\"\n printer = TreePrinter(self._mock_tree)\n printer.print_tree()\n self._mock_tree.get_root.assert_called_once()\n self._mock_root.get_children.assert_called_once()\n self._mock_root.get_name.assert_called_once()\n for mock_node in self._mock_children:\n mock_node.get_children.assert_called_once()\n mock_node.get_name.assert_called_once()\n", "method_code": " def print_tree(self):\n \"\"\"Prints the tree provided to the constructor.\"\"\"\n root = self._tree.get_root()\n print(root.get_name())\n self._print_recursive(root, '')\n ", "context": "class TreePrinter(object):\n def print_tree(self): ...\n def __init__(self, tree, indentation_width=4, output_file=None): ...\n def _format_symlink_pair(self, symlink_pair): ...\n def _print_recursive(self, node, indent_str): ...\n\n self._tree = tree\n self._indentation_width = indentation_width\n self._indent_str = TreePrinter.LEVEL_CHAR.ljust(self._indentation_width, ' ')\n self._entry_prefix = TreePrinter.LEVEL_CHAR.ljust(self._indentation_width - 1, TreePrinter.ENTRY_CHAR)\n self._end_prefix = TreePrinter.END_CHAR.ljust(self._indentation_width - 1, TreePrinter.ENTRY_CHAR)\n\n LEVEL_CHAR = '|'\n ENTRY_CHAR = '-'\n END_CHAR = '`'\n SYMLINK_FORMAT = '%s -> %s'\n", "repository": "tdeh/py-tree", "test_name": "test_print_tree_visits_all", "smells": [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000747.py"} {"focal_file": "crashcourse/name_function.py", "focal_class": null, "focal_method": "get_formatted_name", "tests": "import unittest\n\nclass Test_get_formatted_name(unittest.TestCase):\n def test_first_last_name(self):\n \"\"\"Do names like 'Janis Joplin' work?\"\"\"\n formatted_name = get_formatted_name('janis', 'joplin')\n self.assertEqual(formatted_name, 'Janis Joplin')\n\n def test_first_last_middle_name(self):\n \"\"\"Do names like 'Wolfgang Amadeus Mozart' work?\"\"\"\n formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')\n self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')\n", "method_code": "def get_formatted_name(first, last, middle=''):\n \"\"\"Generate a neatly formatted full name.\"\"\"\n if middle:\n full_name = first + ' ' + middle + ' ' + last\n else:\n full_name = first + ' ' + last\n return full_name.title()", "context": "def get_formatted_name(first, last, middle=''): ...\ndef get_formatted_name(first, last, middle=''): ...\n", "repository": "shifteight/python", "test_name": "test_first_last_name", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000748.py"} {"focal_file": "stdlib/unittest_demo.py", "focal_class": null, "focal_method": "average", "tests": "import unittest\n\nclass Test_average(unittest.TestCase):\n def test_average(self):\n self.assertEqual(average([20, 30, 70]), 40.0)\n self.assertEqual(round(average([1, 5, 7]), 1), 4.3)\n with self.assertRaises(ZeroDivisionError):\n average([])\n with self.assertRaises(TypeError):\n average(20, 30, 70)\n", "method_code": "def average(values):\n \"\"\"Computes the arithmetic mean of a list of numbers.\n\n >>> print(average([20, 30, 70]))\n 40.0\n \"\"\"\n return sum(values) / len(values)", "context": "def average(values): ...\ndef average(values): ...\n", "repository": "shifteight/python", "test_name": "test_average", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000749.py"} {"focal_file": "sample/naive_optimizer.py", "focal_class": null, "focal_method": "objective", "tests": "import unittest\n\nclass Test_objective(unittest.TestCase):\n def test_objective(self):\n input = [20, 30, 40]\n a = MoveStrategy(input)\n b = Optimizer(input)\n self.assertEqual(Optimizer.objective(input), a.objective_value)\n", "method_code": " def objective(input_list, obj='tr'):\n point = MoveStrategy(input_list)\n return point.objective_value\n ", "context": "class Optimizer():\n @staticmethod\n def objective(input_list, obj='tr'): ...\n def __init__(self, list, obj='tr'): ...\n def print_results(self): ...\n\n self.initial_point = MoveStrategy(list, obj)\n self.cons = ({'type': 'ineq', 'fun': lambda x: np.array([x[0] - x[1]])}, {'type': 'ineq', 'fun': lambda x: np.array([x[0] - 60])}, {'type': 'ineq', 'fun': lambda x: np.array([x[1]])}, {'type': 'ineq', 'fun': lambda x: np.array([x[2]])}, {'type': 'ineq', 'fun': lambda x: np.array([-x[0] + 183])}, {'type': 'ineq', 'fun': lambda x: np.array([x[2] - x[1]])}, {'type': 'ineq', 'fun': lambda x: np.array([x[0] - x[2]])})\n self.optimize_result = optimize.minimize(Optimizer.objective, list, args=(obj,), constraints=self.cons, method='slsqp', options={'disp': False})\n self.final_point = MoveStrategy(self.optimize_result.x)\n", "repository": "collinmcnulty/moving-optimization", "test_name": "test_objective", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000750.py"} {"focal_file": "shelfcache/shelfcache.py", "focal_class": "Item", "focal_method": "get_item", "tests": "import unittest\n\nclass Test_Item_get_item(unittest.TestCase):\n def test_get_item_fresh(self):\n \"\"\"\n Get a fresh item with get().\n \"\"\"\n exp_time = datetime.utcnow() + timedelta(days=1)\n test_item = Item(data='data', expire_dt=exp_time)\n test_val = {'key': test_item}\n mock_shelf = make_mock_locked_shelf(test_val)\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n item = sc.get_item('key')\n self.assertEqual('data', item.data)\n self.assertEqual(exp_time, item.expire_dt)\n", "method_code": " def get_item(self, key) -> Optional[Item]:\n \"\"\"\n Get item from database. Like get(), but return an Item (with all\n metadata) instead of the simpler CacheResult.\n \"\"\"\n try:\n with self.shelf_t(self.db_path, flag='r') as shelf:\n val = shelf.get(key)\n return val\n except FileNotFoundError:\n logger.info('Cache db file does not exist at {}'.format(self.db_path))\n return None\n ", "context": "class ShelfCache():\n def get_item(self, key) -> Optional[Item]: ...\n def __init__(self, db_path='shelfcache.db', exp_seconds=-1, shelf_t: Type[LockedShelf]=RWShelf) -> None: ...\n def get(self, key) -> Optional[CacheResult]: ...\n def __getitem__(self, key) -> CacheResult: ...\n def create_or_update(self, key, data=None, expire_dt: Optional[datetime]=None, exp_seconds: Optional[int]=None) -> None: ...\n def __setitem__(self, key, value) -> None: ...\n def update_expires(self, key, expire_dt: Optional[datetime]=None) -> None: ...\n def replace_data(self, key, data: Optional[object]=None) -> None: ...\n def delete(self, key: str) -> None: ...\n def __delitem__(self, key) -> None: ...\n def __prune(self, dt: datetime, field_name='expire_dt') -> int: ...\n def prune_expired(self, older_than: Optional[datetime]=None) -> int: ...\n def prune_old(self, older_than: Optional[datetime]=None) -> int: ...\n def clear(self) -> None: ...\n\n self.db_path = db_path\n self.exp_seconds = exp_seconds\n self.shelf_t = shelf_t\n", "repository": "cristoper/shelfcache", "test_name": "test_get_item_fresh", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000751.py"} {"focal_file": "shelfcache/shelfcache.py", "focal_class": "ShelfCache", "focal_method": "create_or_update", "tests": "import unittest\n\nclass Test_ShelfCache_create_or_update(unittest.TestCase):\n def test_create_or_update_dt(self):\n \"\"\"\n Check that key and expire_dt is set with set() passing a datetime\n object.\n \"\"\"\n mock_shelf = make_mock_locked_shelf()\n mock_dict = mock_shelf.return_value.__enter__.return_value\n tomorrow = datetime.utcnow() + timedelta(days=1)\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc.create_or_update('key', data='val', expire_dt=tomorrow)\n item = mock_dict.get('key')\n data, exp = (item.data, item.expire_dt)\n self.assertEqual('val', data)\n self.assertEqual(exp, tomorrow)\n\n def test_create_or_update_updates(self):\n \"\"\"\n Check that updating an existing item with create_or_update will update\n the updated_dt.\n \"\"\"\n mock_shelf = make_mock_locked_shelf()\n mock_dict = mock_shelf.return_value.__enter__.return_value\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc.create_or_update('key', data='original')\n item = mock_dict.get('key')\n data, created, updated = (item.data, item.created_dt, item.updated_dt)\n self.assertEqual('original', data)\n self.assertEqual(created, updated)\n sc.create_or_update('key', data='new')\n item = mock_dict.get('key')\n data, created, updated = (item.data, item.created_dt, item.updated_dt)\n self.assertEqual('new', data)\n self.assertTrue(created < updated)\n\n def test_create_or_update_seconds(self):\n \"\"\"\n Check that key and expire_dt is set with set() passing seconds.\n \"\"\"\n mock_shelf = make_mock_locked_shelf()\n mock_dict = mock_shelf.return_value.__enter__.return_value\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc.create_or_update('key', data='val', exp_seconds=10)\n item = mock_dict.get('key')\n data, exp, created = (item.data, item.expire_dt, item.created_dt)\n future = created + timedelta(seconds=10)\n self.assertEqual('val', data)\n self.assertEqual(exp, future)\n\n def test_create_or_update_seconds_neg1(self):\n \"\"\"\n Check that passing -1 to exp_seconds results in item having no expiry\n datetime.\n \"\"\"\n mock_shelf = make_mock_locked_shelf()\n mock_dict = mock_shelf.return_value.__enter__.return_value\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc.create_or_update('key', data='val', exp_seconds=-1)\n item = mock_dict.get('key')\n data, exp = (item.data, item.expire_dt)\n self.assertEqual('val', data)\n self.assertIsNone(exp)\n", "method_code": " def create_or_update(self, key, data=None, expire_dt: Optional[datetime]=None, exp_seconds: Optional[int]=None) -> None:\n \"\"\"\n Create or update `key` with the given `data`.\n \n The expiry datetime of the cached item is set by either `expire_dt` or\n `exp_seconds`. If both are set, `expire_dt` will be used. If neither are\n set, the item will never expire.\n \n :param key: The key associated with the `data` to cache\n :param data: The data to cache (can be any pickle-able object)\n :param expire_dt: The date the cached item expires.\n :param exp_seconds: The number of seconds into the future that the\n cached item expires.\n \"\"\"\n item = Item(data=data)\n if expire_dt is None and exp_seconds and (exp_seconds > -1):\n expire_dt = item.created_dt + timedelta(seconds=exp_seconds)\n item.expire_dt = expire_dt\n with self.shelf_t(self.db_path, flag='c') as shelf:\n if key in shelf.keys():\n item.created_dt = shelf.get(key).created_dt\n item.updated_dt = datetime.utcnow()\n logger.info('Updated item for key: {}'.format(key))\n else:\n logger.info('Created item for key: {}'.format(key))\n shelf[key] = item\n ", "context": "class ShelfCache():\n def create_or_update(self, key, data=None, expire_dt: Optional[datetime]=None, exp_seconds: Optional[int]=None) -> None: ...\n def __init__(self, db_path='shelfcache.db', exp_seconds=-1, shelf_t: Type[LockedShelf]=RWShelf) -> None: ...\n def get(self, key) -> Optional[CacheResult]: ...\n def get_item(self, key) -> Optional[Item]: ...\n def __getitem__(self, key) -> CacheResult: ...\n def __setitem__(self, key, value) -> None: ...\n def update_expires(self, key, expire_dt: Optional[datetime]=None) -> None: ...\n def replace_data(self, key, data: Optional[object]=None) -> None: ...\n def delete(self, key: str) -> None: ...\n def __delitem__(self, key) -> None: ...\n def __prune(self, dt: datetime, field_name='expire_dt') -> int: ...\n def prune_expired(self, older_than: Optional[datetime]=None) -> int: ...\n def prune_old(self, older_than: Optional[datetime]=None) -> int: ...\n def clear(self) -> None: ...\n\n self.db_path = db_path\n self.exp_seconds = exp_seconds\n self.shelf_t = shelf_t\n", "repository": "cristoper/shelfcache", "test_name": "test_create_or_update_dt", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000752.py"} {"focal_file": "shelfcache/shelfcache.py", "focal_class": "ShelfCache", "focal_method": "update_expires", "tests": "import unittest\n\nclass Test_ShelfCache_update_expires(unittest.TestCase):\n def test_update_expires(self):\n \"\"\"\n Set an item, then ensure its expires date can be updated.\n \"\"\"\n wrapped_dict = {}\n mock_shelf = make_mock_locked_shelf(wrapped_dict)\n mock_dict = mock_shelf.return_value.__enter__.return_value\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc['key'] = 'val'\n item = mock_dict.get('key')\n old_exp = item.expire_dt\n self.assertIsNone(old_exp)\n tomorrow = datetime.utcnow() + timedelta(days=1)\n sc.update_expires('key', tomorrow)\n item = mock_dict.get('key')\n data, new_exp = (item.data, item.expire_dt)\n self.assertEqual('val', data)\n self.assertEqual(tomorrow, new_exp)\n", "method_code": " def update_expires(self, key, expire_dt: Optional[datetime]=None) -> None:\n \"\"\"\n Update a cached item's expire_dt without returning the actual data.\n \"\"\"\n if expire_dt is None:\n expire_dt = datetime.utcnow()\n d, _ = self[key]\n self.create_or_update(key, data=d, expire_dt=expire_dt)\n ", "context": "class ShelfCache():\n def update_expires(self, key, expire_dt: Optional[datetime]=None) -> None: ...\n def __init__(self, db_path='shelfcache.db', exp_seconds=-1, shelf_t: Type[LockedShelf]=RWShelf) -> None: ...\n def get(self, key) -> Optional[CacheResult]: ...\n def get_item(self, key) -> Optional[Item]: ...\n def __getitem__(self, key) -> CacheResult: ...\n def create_or_update(self, key, data=None, expire_dt: Optional[datetime]=None, exp_seconds: Optional[int]=None) -> None: ...\n def __setitem__(self, key, value) -> None: ...\n def replace_data(self, key, data: Optional[object]=None) -> None: ...\n def delete(self, key: str) -> None: ...\n def __delitem__(self, key) -> None: ...\n def __prune(self, dt: datetime, field_name='expire_dt') -> int: ...\n def prune_expired(self, older_than: Optional[datetime]=None) -> int: ...\n def prune_old(self, older_than: Optional[datetime]=None) -> int: ...\n def clear(self) -> None: ...\n\n self.db_path = db_path\n self.exp_seconds = exp_seconds\n self.shelf_t = shelf_t\n", "repository": "cristoper/shelfcache", "test_name": "test_update_expires", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000753.py"} {"focal_file": "shelfcache/shelfcache.py", "focal_class": "ShelfCache", "focal_method": "delete", "tests": "import unittest\n\nclass Test_ShelfCache_delete(unittest.TestCase):\n def test_delete(self):\n \"\"\"\n Set an item and then test that it can be deleted.\n \"\"\"\n mock_shelf = make_mock_locked_shelf()\n mock_dict = mock_shelf.return_value.__enter__.return_value\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc['key'] = 'val'\n item = mock_dict.get('key')\n data = item.data\n self.assertEqual('val', data)\n sc.delete('key')\n val = sc.get('key')\n self.assertIsNone(val)\n", "method_code": " def delete(self, key: str) -> None:\n \"\"\"\n Delete `key` from cache database.\n \"\"\"\n with self.shelf_t(self.db_path, flag='c') as shelf:\n del shelf[key]\n logger.info('Deleted item for key: {}'.format(key))\n ", "context": "class ShelfCache():\n def delete(self, key: str) -> None: ...\n def __init__(self, db_path='shelfcache.db', exp_seconds=-1, shelf_t: Type[LockedShelf]=RWShelf) -> None: ...\n def get(self, key) -> Optional[CacheResult]: ...\n def get_item(self, key) -> Optional[Item]: ...\n def __getitem__(self, key) -> CacheResult: ...\n def create_or_update(self, key, data=None, expire_dt: Optional[datetime]=None, exp_seconds: Optional[int]=None) -> None: ...\n def __setitem__(self, key, value) -> None: ...\n def update_expires(self, key, expire_dt: Optional[datetime]=None) -> None: ...\n def replace_data(self, key, data: Optional[object]=None) -> None: ...\n def __delitem__(self, key) -> None: ...\n def __prune(self, dt: datetime, field_name='expire_dt') -> int: ...\n def prune_expired(self, older_than: Optional[datetime]=None) -> int: ...\n def prune_old(self, older_than: Optional[datetime]=None) -> int: ...\n def clear(self) -> None: ...\n\n self.db_path = db_path\n self.exp_seconds = exp_seconds\n self.shelf_t = shelf_t\n", "repository": "cristoper/shelfcache", "test_name": "test_delete", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000754.py"} {"focal_file": "shelfcache/shelfcache.py", "focal_class": "ShelfCache", "focal_method": "clear", "tests": "import unittest\n\nclass Test_ShelfCache_clear(unittest.TestCase):\n def test_clear(self):\n \"\"\"\n Set some items then test that they are all deleted.\n \"\"\"\n wrapped_dict = {}\n mock_shelf = make_mock_locked_shelf(wrapped_dict)\n mock_dict = mock_shelf.return_value.__enter__.return_value\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc['key'] = 'val'\n sc['key2'] = 'val2'\n item1 = mock_dict.get('key')\n item2 = mock_dict.get('key2')\n d1 = item1.data\n d2 = item2.data\n self.assertEqual('val', d1)\n self.assertEqual('val2', d2)\n sc.clear()\n item1 = mock_dict.get('key')\n item2 = mock_dict.get('key2')\n self.assertIsNone(item1)\n self.assertIsNone(item2)\n", "method_code": " def clear(self) -> None:\n \"\"\"\n Delete all items in cache.\n \"\"\"\n with self.shelf_t(self.db_path, flag='c') as shelf:\n shelf.clear()\n logger.info('Deleted all items in cache.')\n ", "context": "class ShelfCache():\n def clear(self) -> None: ...\n def __init__(self, db_path='shelfcache.db', exp_seconds=-1, shelf_t: Type[LockedShelf]=RWShelf) -> None: ...\n def get(self, key) -> Optional[CacheResult]: ...\n def get_item(self, key) -> Optional[Item]: ...\n def __getitem__(self, key) -> CacheResult: ...\n def create_or_update(self, key, data=None, expire_dt: Optional[datetime]=None, exp_seconds: Optional[int]=None) -> None: ...\n def __setitem__(self, key, value) -> None: ...\n def update_expires(self, key, expire_dt: Optional[datetime]=None) -> None: ...\n def replace_data(self, key, data: Optional[object]=None) -> None: ...\n def delete(self, key: str) -> None: ...\n def __delitem__(self, key) -> None: ...\n def __prune(self, dt: datetime, field_name='expire_dt') -> int: ...\n def prune_expired(self, older_than: Optional[datetime]=None) -> int: ...\n def prune_old(self, older_than: Optional[datetime]=None) -> int: ...\n\n self.db_path = db_path\n self.exp_seconds = exp_seconds\n self.shelf_t = shelf_t\n", "repository": "cristoper/shelfcache", "test_name": "test_clear", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000755.py"} {"focal_file": "shelfcache/shelfcache.py", "focal_class": "ShelfCache", "focal_method": "prune_old", "tests": "import unittest\n\nclass Test_ShelfCache_prune_old(unittest.TestCase):\n def test_prune_old(self):\n \"\"\"\n Create some items and then test that the oldest is pruned.\n \"\"\"\n mock_shelf = make_mock_locked_shelf()\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc.create_or_update('old', data='old')\n today = datetime.utcnow()\n sc.create_or_update('new', data='new')\n sc.prune_old(older_than=today)\n old = sc.get('old')\n new = sc.get('new')\n self.assertIsNone(old)\n self.assertEqual('new', new.data)\n", "method_code": " def prune_old(self, older_than: Optional[datetime]=None) -> int:\n \"\"\"\n :param older_than: Delete all items in cache updated before the\n the given datetime. If `older_than` is None, use datetime.utcnow()\n \n Returns:\n The number of items that were pruned.\n \"\"\"\n if older_than is None:\n older_than = datetime.utcnow()\n return self.__prune(older_than, field_name='updated_dt')\n ", "context": "class ShelfCache():\n def prune_old(self, older_than: Optional[datetime]=None) -> int: ...\n def __init__(self, db_path='shelfcache.db', exp_seconds=-1, shelf_t: Type[LockedShelf]=RWShelf) -> None: ...\n def get(self, key) -> Optional[CacheResult]: ...\n def get_item(self, key) -> Optional[Item]: ...\n def __getitem__(self, key) -> CacheResult: ...\n def create_or_update(self, key, data=None, expire_dt: Optional[datetime]=None, exp_seconds: Optional[int]=None) -> None: ...\n def __setitem__(self, key, value) -> None: ...\n def update_expires(self, key, expire_dt: Optional[datetime]=None) -> None: ...\n def replace_data(self, key, data: Optional[object]=None) -> None: ...\n def delete(self, key: str) -> None: ...\n def __delitem__(self, key) -> None: ...\n def __prune(self, dt: datetime, field_name='expire_dt') -> int: ...\n def prune_expired(self, older_than: Optional[datetime]=None) -> int: ...\n def clear(self) -> None: ...\n\n self.db_path = db_path\n self.exp_seconds = exp_seconds\n self.shelf_t = shelf_t\n", "repository": "cristoper/shelfcache", "test_name": "test_prune_old", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000756.py"} {"focal_file": "shelfcache/shelfcache.py", "focal_class": "ShelfCache", "focal_method": "prune_expired", "tests": "import unittest\n\nclass Test_ShelfCache_prune_expired(unittest.TestCase):\n def test_prune_expired(self):\n \"\"\"\n Create some items and then test that the expired one is pruned.\n \"\"\"\n mock_shelf = make_mock_locked_shelf()\n tomorrow = datetime.utcnow() + timedelta(days=1)\n yesterday = datetime.utcnow() + timedelta(days=-1)\n sc = ShelfCache(db_path='dummy', shelf_t=mock_shelf)\n sc.create_or_update('old', data='old', expire_dt=yesterday)\n sc.create_or_update('new', data='new', expire_dt=tomorrow)\n sc.prune_expired()\n old = sc.get('old')\n new = sc.get('new')\n self.assertIsNone(old)\n self.assertEqual('new', new.data)\n", "method_code": " def prune_expired(self, older_than: Optional[datetime]=None) -> int:\n \"\"\"\n :param older_than: Delete all items in cache which have expired since\n the given datetime. If `older_than` is None, use datetime.utcnow()\n \n Returns:\n The number of items that were pruned.\n \"\"\"\n if older_than is None:\n older_than = datetime.utcnow()\n return self.__prune(older_than, field_name='expire_dt')\n ", "context": "class ShelfCache():\n def prune_expired(self, older_than: Optional[datetime]=None) -> int: ...\n def __init__(self, db_path='shelfcache.db', exp_seconds=-1, shelf_t: Type[LockedShelf]=RWShelf) -> None: ...\n def get(self, key) -> Optional[CacheResult]: ...\n def get_item(self, key) -> Optional[Item]: ...\n def __getitem__(self, key) -> CacheResult: ...\n def create_or_update(self, key, data=None, expire_dt: Optional[datetime]=None, exp_seconds: Optional[int]=None) -> None: ...\n def __setitem__(self, key, value) -> None: ...\n def update_expires(self, key, expire_dt: Optional[datetime]=None) -> None: ...\n def replace_data(self, key, data: Optional[object]=None) -> None: ...\n def delete(self, key: str) -> None: ...\n def __delitem__(self, key) -> None: ...\n def __prune(self, dt: datetime, field_name='expire_dt') -> int: ...\n def prune_old(self, older_than: Optional[datetime]=None) -> int: ...\n def clear(self) -> None: ...\n\n self.db_path = db_path\n self.exp_seconds = exp_seconds\n self.shelf_t = shelf_t\n", "repository": "cristoper/shelfcache", "test_name": "test_prune_expired", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000757.py"} {"focal_file": "neuronmi/mesh/shapes/utils.py", "focal_class": null, "focal_method": "find_first", "tests": "import unittest\n\nclass Test_find_first(unittest.TestCase):\n def test_find_first(self):\n my = find_first(4, range(19))\n truth = list(range(19)).index(4)\n self.assertTrue(my == truth)\n", "method_code": "def find_first(item, iterable):\n \"\"\"If iterable were indexable where would we find item\"\"\"\n pair = next(dropwhile(lambda ip: item != second(ip), enumerate(iter(iterable))))\n return first(pair)", "context": "def find_first(item, iterable): ...\ndef as_namedtuple(d): ...\ndef has_positive_values(d, keys=None): ...\ndef unit_vector(n): ...\ndef circle_points(c, r, a=np.array([0, 0, 1.0])): ...\ndef first(iterable): ...\ndef second(iterable): ...\ndef link_surfaces(model, tags, shape, links, tol=1e-05, metric=None, claim_last=True): ...\ndef find_first(item, iterable): ...\ndef entity_dim(arr, dim): ...\n", "repository": "MiroK/nEuronMI", "test_name": "test_find_first", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000758.py"} {"focal_file": "neuronmi/mesh/shapes/utils.py", "focal_class": null, "focal_method": "circle_points", "tests": "import unittest\n\nclass Test_circle_points(unittest.TestCase):\n def test_circle_points(self):\n n = np.array([1, 1, 1])\n n = n / np.linalg.norm(n)\n c = np.array([0, 0, 0])\n r = 0.24\n pts = circle_points(c, r, a=n)\n for p in pts:\n self.assertTrue(abs(np.dot(p - c, n)) < 1e-13)\n self.assertTrue(abs(np.linalg.norm(p - c) - r) < 1e-13)\n", "method_code": "def circle_points(c, r, a=np.array([0, 0, 1.0])):\n \"\"\"Four points on radius r circle in plane containing c with normal a\"\"\"\n assert len(c) == len(a) == 3\n n = unit_vector(a)\n lmbda, U = np.linalg.eigh(np.eye(3) - np.outer(n, n))\n assert abs(lmbda[0]) < 1e-14, 'This is not projection'\n u, v = U.T[1:]\n return np.array([c + r * u, c - r * u, c + r * v, c - r * v])", "context": "def circle_points(c, r, a=np.array([0, 0, 1.0])): ...\ndef as_namedtuple(d): ...\ndef has_positive_values(d, keys=None): ...\ndef unit_vector(n): ...\ndef circle_points(c, r, a=np.array([0, 0, 1.0])): ...\ndef first(iterable): ...\ndef second(iterable): ...\ndef link_surfaces(model, tags, shape, links, tol=1e-05, metric=None, claim_last=True): ...\ndef find_first(item, iterable): ...\ndef entity_dim(arr, dim): ...\n", "repository": "MiroK/nEuronMI", "test_name": "test_circle_points", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000759.py"} {"focal_file": "neuronmi/mesh/shapes/utils.py", "focal_class": null, "focal_method": "first", "tests": "import unittest\n\nclass Test_first(unittest.TestCase):\n def test_first(self):\n self.assertTrue(first((1, 0, 2)) == 1)\n", "method_code": "def first(iterable):\n \"\"\"A better [0]\"\"\"\n return next(iter(iterable))", "context": "def first(iterable): ...\ndef as_namedtuple(d): ...\ndef has_positive_values(d, keys=None): ...\ndef unit_vector(n): ...\ndef circle_points(c, r, a=np.array([0, 0, 1.0])): ...\ndef first(iterable): ...\ndef second(iterable): ...\ndef link_surfaces(model, tags, shape, links, tol=1e-05, metric=None, claim_last=True): ...\ndef find_first(item, iterable): ...\ndef entity_dim(arr, dim): ...\n", "repository": "MiroK/nEuronMI", "test_name": "test_first", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000760.py"} {"focal_file": "neuronmi/mesh/shapes/utils.py", "focal_class": null, "focal_method": "second", "tests": "import unittest\n\nclass Test_second(unittest.TestCase):\n def test_second(self):\n self.assertTrue(second((1, 0, 2)) == 0)\n", "method_code": "def second(iterable):\n \"\"\"A better [1]\"\"\"\n it = iter(iterable)\n next(it)\n return first(it)", "context": "def second(iterable): ...\ndef as_namedtuple(d): ...\ndef has_positive_values(d, keys=None): ...\ndef unit_vector(n): ...\ndef circle_points(c, r, a=np.array([0, 0, 1.0])): ...\ndef first(iterable): ...\ndef second(iterable): ...\ndef link_surfaces(model, tags, shape, links, tol=1e-05, metric=None, claim_last=True): ...\ndef find_first(item, iterable): ...\ndef entity_dim(arr, dim): ...\n", "repository": "MiroK/nEuronMI", "test_name": "test_second", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000761.py"} {"focal_file": "rest_framework/serializers/fields.py", "focal_class": null, "focal_method": "bind", "tests": "import unittest\n\nclass Test_bind(unittest.TestCase):\n def test_bind(self):\n \"\"\"\n Testing bind method.\n\n \"\"\"\n field = self.field_class(**self.create_params())\n field.bind('test_label', self)\n self.assert_bind(field, 'test_label', self, 'Test label')\n field = self.field_class(**self.create_params(label='test_label'))\n field.bind('test_label', self)\n self.assert_bind(field, 'test_label', self, 'test_label')\n", "method_code": " def bind(self, field_name, parent):\n \"\"\"\n Initialization field name and parent instance .\n Called when a field is added to an instance of the parent..\n \n :param str field_name: Field name.\n :param Serializer parent: Serializer class on which the field is located.\n \n \"\"\"\n self.field_name = field_name\n self.parent = parent\n if self.label is None:\n self.label = field_name.replace('_', ' ').capitalize()\n ", "context": "class Field(object):\n def bind(self, field_name, parent): ...\n def __init__(self, required=True, default=None, label=None, validators=None, error_messages=None, source=None, allow_none=None): ...\n def __deepcopy__(self, memo={}): ...\n def validators(self): ...\n def validators(self, validators): ...\n def get_validators(self): ...\n def fail_validate(self, detail=None, status=400): ...\n def fail_field_validation(self, key, **kwargs): ...\n def to_internal_value(self, data): ...\n def _to_representation(self, value): ...\n def to_representation(self, value): ...\n def get_default(self): ...\n def _get_field_name(self): ...\n def _get_attribute_name(self): ...\n def _get_attribute(self, instance): ...\n def get_attribute(self, instance): ...\n def validate_empty_values(self, data): ...\n def run_validation(self, data): ...\n def run_validators(self, value): ...\n\n self.label = label\n self.default = default\n self.source = source\n self.allow_none = allow_none\n self.required = bool(required) if self.default is None else False\n self._src_validators = validators\n self._validators = ([RequiredValidator()] if self.required else []) + (validators or [])[:]\n self._src_messages = messages\n self.error_messages = messages\n\n default_error_messages = {'required': 'This field is required.', 'null': 'This field cannot be null.'}\n default_validators = []\n", "repository": "nxexox/python-rest-framework", "test_name": "test_bind", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000762.py"} {"focal_file": "rest_framework/serializers/fields.py", "focal_class": null, "focal_method": "fail_field_validation", "tests": "import unittest\n\nclass Test_fail_field_validation(unittest.TestCase):\n def test_fail_field_validation(self):\n \"\"\"\n Testing fail_field_validation method.\n\n \"\"\"\n field = self.field_class(**self.create_params())\n try:\n field.fail_field_validation('required')\n self.fail('`.fail_field_validation()` must throw as exception `ValidationError`.')\n except ValidationError:\n pass\n try:\n field.fail_field_validation('test')\n self.fail('`.fail_field_validation()` must throw as exception `AssertionError`.')\n except AssertionError:\n pass\n field = self.field_class(**self.create_params(error_messages={'test': '{test}-test'}))\n try:\n field.fail_field_validation('test', test='test')\n self.fail('`.fail_field_validation()` must throw as exception `ValidationError`.')\n except ValidationError as e:\n assert e.detail == 'test-test', 'The error message should be `{}`, reality `{}`.'.format('test-test', e.detail)\n", "method_code": " def fail_field_validation(self, key, **kwargs):\n \"\"\"\n We throw a normal error if something went wrong during data processing.\n \n :param str key: Error type. Key for dict `self.default_error_messages`.\n :param kwargs: Data to format error message.\n \n :raise AssertionError: If you have not found the key in the `self.error_messages`.\n :raise ValidationError: If you find the key in the `self.error_messages`.\n \n \"\"\"\n try:\n msg = self.error_messages[key]\n except KeyError:\n class_name = self.__class__.__name__\n msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)\n raise AssertionError(msg)\n message_string = msg.format(**kwargs)\n raise ValidationError(detail=message_string, status=key)\n ", "context": "class Field(object):\n def fail_field_validation(self, key, **kwargs): ...\n def __init__(self, required=True, default=None, label=None, validators=None, error_messages=None, source=None, allow_none=None): ...\n def __deepcopy__(self, memo={}): ...\n def bind(self, field_name, parent): ...\n def validators(self): ...\n def validators(self, validators): ...\n def get_validators(self): ...\n def fail_validate(self, detail=None, status=400): ...\n def to_internal_value(self, data): ...\n def _to_representation(self, value): ...\n def to_representation(self, value): ...\n def get_default(self): ...\n def _get_field_name(self): ...\n def _get_attribute_name(self): ...\n def _get_attribute(self, instance): ...\n def get_attribute(self, instance): ...\n def validate_empty_values(self, data): ...\n def run_validation(self, data): ...\n def run_validators(self, value): ...\n\n self.label = label\n self.default = default\n self.source = source\n self.allow_none = allow_none\n self.required = bool(required) if self.default is None else False\n self._src_validators = validators\n self._validators = ([RequiredValidator()] if self.required else []) + (validators or [])[:]\n self._src_messages = messages\n self.error_messages = messages\n\n default_error_messages = {'required': 'This field is required.', 'null': 'This field cannot be null.'}\n default_validators = []\n", "repository": "nxexox/python-rest-framework", "test_name": "test_fail_field_validation", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000763.py"} {"focal_file": "rest_framework/serializers/fields.py", "focal_class": null, "focal_method": "fail_validate", "tests": "import unittest\n\nclass Test_fail_validate(unittest.TestCase):\n def test_fail_validate(self):\n \"\"\"\n Testing fail method.\n\n \"\"\"\n field = self.field_class(**self.create_params())\n detail = {'error': 'test'}\n try:\n field.fail_validate(detail=detail)\n self.fail('`.fail()` must throw as exception `ValidationError`.')\n except ValidationError as e:\n self.assertEqual(e.detail, detail, 'ValidationError.detail not equal source error. Should be: `{}`, reality: `{}`.'.format(detail, e.detail))\n self.assertEqual(e.status, 400, 'ValidationError.status = `{}`. This is not 400.'.format(e.status))\n status = 404\n try:\n field.fail_validate(detail=detail, status=status)\n self.fail('`.fail()` must throw as exception `ValidationError`.')\n except ValidationError as e:\n self.assertEqual(e.status, status, 'ValidationError.status not equal source status. Should be: `{}`, reality: `{}`.'.format(status, e.status))\n", "method_code": " def fail_validate(self, detail=None, status=400):\n \"\"\"\n We throw a normal error if custom validation error.\n \n :param Union[str, dict] detail: Detail validation error\n :param int status: Code for response\n \n :raise AssertionError: If you have not found the key in the `self.error_messages`.\n :raise ValidationError: If you find the key in the `self.error_messages`.\n \n \"\"\"\n raise ValidationError(detail=detail, status=status)\n ", "context": "class Field(object):\n def fail_validate(self, detail=None, status=400): ...\n def __init__(self, required=True, default=None, label=None, validators=None, error_messages=None, source=None, allow_none=None): ...\n def __deepcopy__(self, memo={}): ...\n def bind(self, field_name, parent): ...\n def validators(self): ...\n def validators(self, validators): ...\n def get_validators(self): ...\n def fail_field_validation(self, key, **kwargs): ...\n def to_internal_value(self, data): ...\n def _to_representation(self, value): ...\n def to_representation(self, value): ...\n def get_default(self): ...\n def _get_field_name(self): ...\n def _get_attribute_name(self): ...\n def _get_attribute(self, instance): ...\n def get_attribute(self, instance): ...\n def validate_empty_values(self, data): ...\n def run_validation(self, data): ...\n def run_validators(self, value): ...\n\n self.label = label\n self.default = default\n self.source = source\n self.allow_none = allow_none\n self.required = bool(required) if self.default is None else False\n self._src_validators = validators\n self._validators = ([RequiredValidator()] if self.required else []) + (validators or [])[:]\n self._src_messages = messages\n self.error_messages = messages\n\n default_error_messages = {'required': 'This field is required.', 'null': 'This field cannot be null.'}\n default_validators = []\n", "repository": "nxexox/python-rest-framework", "test_name": "test_fail_validate", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000764.py"} {"focal_file": "rest_framework/serializers/fields.py", "focal_class": null, "focal_method": "get_default", "tests": "import unittest\n\nclass Test_get_default(unittest.TestCase):\n def test_get_default(self):\n \"\"\"\n Testing the get_default method.\n\n \"\"\"\n field = self.field_class(**self.create_params())\n res = field.get_default()\n assert res is None, '`.get_default()` must return None, reality: {}.'.format(res)\n field = self.field_class(**self.create_params(default=1))\n res = field.get_default()\n assert res == 1, '`.get_default()` must return 1, reality: {}.'.format(res)\n field = self.field_class(**self.create_params(default=lambda: 100))\n res = field.get_default()\n assert res == 100, '`.get_default()` must return 100, reality: {}.'.format(res)\n", "method_code": " def get_default(self):\n \"\"\"\n Return default value.\n If necessary, initially call the callable object to get the default value..\n \n :return: Default value.\n :rtype: object\n \n \"\"\"\n if callable(self.default):\n return self.default()\n return self.default\n ", "context": "class Field(object):\n def get_default(self): ...\n def __init__(self, required=True, default=None, label=None, validators=None, error_messages=None, source=None, allow_none=None): ...\n def __deepcopy__(self, memo={}): ...\n def bind(self, field_name, parent): ...\n def validators(self): ...\n def validators(self, validators): ...\n def get_validators(self): ...\n def fail_validate(self, detail=None, status=400): ...\n def fail_field_validation(self, key, **kwargs): ...\n def to_internal_value(self, data): ...\n def _to_representation(self, value): ...\n def to_representation(self, value): ...\n def _get_field_name(self): ...\n def _get_attribute_name(self): ...\n def _get_attribute(self, instance): ...\n def get_attribute(self, instance): ...\n def validate_empty_values(self, data): ...\n def run_validation(self, data): ...\n def run_validators(self, value): ...\n\n self.label = label\n self.default = default\n self.source = source\n self.allow_none = allow_none\n self.required = bool(required) if self.default is None else False\n self._src_validators = validators\n self._validators = ([RequiredValidator()] if self.required else []) + (validators or [])[:]\n self._src_messages = messages\n self.error_messages = messages\n\n default_error_messages = {'required': 'This field is required.', 'null': 'This field cannot be null.'}\n default_validators = []\n", "repository": "nxexox/python-rest-framework", "test_name": "test_get_default", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000765.py"} {"focal_file": "rest_framework/serializers/fields.py", "focal_class": null, "focal_method": "get_attribute", "tests": "import unittest\n\nclass Test_get_attribute(unittest.TestCase):\n def test_get_attribute(self):\n \"\"\"\n Testing get_attribute method.\n\n \"\"\"\n params = dict(field_name='test_get_attribute_field', call_bind=True, required=False, default=None, attr=self.test_get_attribute, set_self=True)\n res = self.create_method_for_get_attribute(**params).get_attribute(self)\n assert res == self.test_get_attribute, '`.get_attribute()` must return {}, reality {}.'.format(self.test_get_attribute, res)\n params.update(default=100, call_bind=False, attr=None, set_self=False)\n res = self.create_method_for_get_attribute(**params).get_attribute(self)\n assert res == 100, '`.get_attribute()` must return 100, reality {}.'.format(res)\n params.update(required=True, default=None)\n try:\n self.create_method_for_get_attribute(**params).get_attribute(self)\n self.fail('`.get_attribute()` must throw as exception `SkipError`.')\n except SkipError:\n pass\n params.update(field_name=None, required=False, call_bind=True)\n try:\n res = self.create_method_for_get_attribute(label='test', **params).get_attribute(self)\n self.fail('`.get_attribute()` must throw as exception `TypeError`, return `{}`.'.format(res))\n except TypeError:\n pass\n except Exception as e:\n self.fail('`.get_attribute()` must throw as exception `TypeError`, reality {}.'.format(type(e)))\n", "method_code": "def get_attribute(obj, attr_name):\n \"\"\"\n Return object attribute. Can work with dictionaries.\n\n :param object obj: Object for search attribute.\n :param str attr_name: Attribute name.\n\n :return: Found attribute or exception.\n :rtype: object\n\n :raise AttributeError: If attribute not found.\n\n \"\"\"\n if isinstance(obj, Mapping):\n attr = obj[attr_name]\n else:\n attr = getattr(obj, attr_name)\n return attr", "context": "def get_attribute(obj, attr_name): ...\ndef get_attribute(obj, attr_name): ...\n", "repository": "nxexox/python-rest-framework", "test_name": "test_get_attribute", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000766.py"} {"focal_file": "rest_framework/serializers/fields.py", "focal_class": null, "focal_method": "validate_empty_values", "tests": "import unittest\n\nclass Test_validate_empty_values(unittest.TestCase):\n def test_validate_empty_values(self):\n \"\"\"\n Testing validation on an empty type.\n\n \"\"\"\n field = self.field_class(**self.create_params(required=False))\n is_empty, data = field.validate_empty_values(None)\n assert is_empty is True, '`.validate_empty_values()` must return True.'\n assert data is None, '`.validate_empty_values()` must return None.'\n field = self.field_class(**self.create_params(required=True))\n try:\n field.validate_empty_values(None)\n self.fail('`.validate_empty_values()` must throw as exception `ValidationError`.')\n except ValidationError:\n pass\n field = self.field_class(**self.create_params(required=True))\n is_empty, data = field.validate_empty_values(123)\n assert is_empty is False, '`.validate_empty_values()` must return False.'\n assert data == 123, '`.validate_empty_values()` must return 123.'\n", "method_code": " def validate_empty_values(self, data):\n \"\"\"\n Check if the value is empty.\n \n :param object data: Data for check.\n \n :return: The result of check, and current data.\n If there is a default value and nothing is passed, returns the default.\n Tuple: (is None, actual data)\n :rtype: tuple\n \n :raise ValidationError: If validation on an empty field did not pass.\n \n \"\"\"\n is_empty, data = (data is None, data if data is not None else self.default)\n if is_empty and (not self.required):\n return (is_empty, data)\n if is_empty:\n raise ValidationError(detail=self.error_messages['required'])\n return (is_empty, data)\n ", "context": "class Field(object):\n def validate_empty_values(self, data): ...\n def __init__(self, required=True, default=None, label=None, validators=None, error_messages=None, source=None, allow_none=None): ...\n def __deepcopy__(self, memo={}): ...\n def bind(self, field_name, parent): ...\n def validators(self): ...\n def validators(self, validators): ...\n def get_validators(self): ...\n def fail_validate(self, detail=None, status=400): ...\n def fail_field_validation(self, key, **kwargs): ...\n def to_internal_value(self, data): ...\n def _to_representation(self, value): ...\n def to_representation(self, value): ...\n def get_default(self): ...\n def _get_field_name(self): ...\n def _get_attribute_name(self): ...\n def _get_attribute(self, instance): ...\n def get_attribute(self, instance): ...\n def run_validation(self, data): ...\n def run_validators(self, value): ...\n\n self.label = label\n self.default = default\n self.source = source\n self.allow_none = allow_none\n self.required = bool(required) if self.default is None else False\n self._src_validators = validators\n self._validators = ([RequiredValidator()] if self.required else []) + (validators or [])[:]\n self._src_messages = messages\n self.error_messages = messages\n\n default_error_messages = {'required': 'This field is required.', 'null': 'This field cannot be null.'}\n default_validators = []\n", "repository": "nxexox/python-rest-framework", "test_name": "test_validate_empty_values", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000767.py"} {"focal_file": "rest_framework/serializers/fields.py", "focal_class": null, "focal_method": "run_validation", "tests": "import unittest\n\nclass Test_run_validation(unittest.TestCase):\n def test_run_validation_base_field(self):\n \"\"\"\n Testing start validation for base field.\n\n \"\"\"\n to_internal_value = lambda x: x\n field = self.field_class(**self.create_params())\n setattr(field, 'to_internal_value', to_internal_value)\n res = field.run_validation(123)\n assert res == 123, '`.run_validation()` must return 123.'\n field = self.field_class(**self.create_params(required=True))\n setattr(field, 'to_internal_value', to_internal_value)\n res = field.run_validation(123)\n assert res == 123, '`.run_validation()` must return 123.'\n try:\n field.run_validation(None)\n self.fail('`.run_validation()` must throw as exception `ValidationError`.')\n except ValidationError:\n pass\n", "method_code": " def run_validation(self, data):\n \"\"\"\n Starts data transformed, then validation..\n \n :param object data: Data worth checking, transformed, etc..\n \n :return: Transformed Validated Data.\n :rtype: object\n \n :raise ValidationError: If the field failed validation.\n \n \"\"\"\n is_empty, data = self.validate_empty_values(data)\n if is_empty and (not self.required):\n return data\n value = self.to_internal_value(data)\n self.run_validators(value)\n return value\n ", "context": "class Field(object):\n def run_validation(self, data): ...\n def __init__(self, required=True, default=None, label=None, validators=None, error_messages=None, source=None, allow_none=None): ...\n def __deepcopy__(self, memo={}): ...\n def bind(self, field_name, parent): ...\n def validators(self): ...\n def validators(self, validators): ...\n def get_validators(self): ...\n def fail_validate(self, detail=None, status=400): ...\n def fail_field_validation(self, key, **kwargs): ...\n def to_internal_value(self, data): ...\n def _to_representation(self, value): ...\n def to_representation(self, value): ...\n def get_default(self): ...\n def _get_field_name(self): ...\n def _get_attribute_name(self): ...\n def _get_attribute(self, instance): ...\n def get_attribute(self, instance): ...\n def validate_empty_values(self, data): ...\n def run_validators(self, value): ...\n\n self.label = label\n self.default = default\n self.source = source\n self.allow_none = allow_none\n self.required = bool(required) if self.default is None else False\n self._src_validators = validators\n self._validators = ([RequiredValidator()] if self.required else []) + (validators or [])[:]\n self._src_messages = messages\n self.error_messages = messages\n\n default_error_messages = {'required': 'This field is required.', 'null': 'This field cannot be null.'}\n default_validators = []\n", "repository": "nxexox/python-rest-framework", "test_name": "test_run_validation_base_field", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000768.py"} {"focal_file": "rest_framework/serializers/fields.py", "focal_class": null, "focal_method": "run_validators", "tests": "import unittest\n\nclass Test_run_validators(unittest.TestCase):\n def test_run_validators(self):\n \"\"\"\n Testing work validators\n\n \"\"\"\n field = self.field_class(**self.create_params(required=False, validators=[]))\n field.run_validators(123)\n field = self.field_class(**self.create_params(required=True, validators=[]))\n field.run_validators(123)\n try:\n field.run_validators(None)\n self.fail('`.run_validators()` must throw as exception `ValidationError`.')\n except ValidationError:\n pass\n\n def test_validator(value):\n if value == 1:\n raise ValidationError(1)\n field = self.field_class(**self.create_params(required=True, validators=[test_validator]))\n field.run_validators(10)\n try:\n field.run_validators(1)\n self.fail('`.run_validators()` must throw as exception `ValidationError`.')\n except ValidationError:\n pass\n", "method_code": " def run_validators(self, value):\n \"\"\"\n Validates all field validators.\n \n :param object value: Data for validation.\n \n :raise ValidationError: If validation fails.\n \n \"\"\"\n errors = []\n for validator in self.validators or []:\n try:\n validator(value)\n except ValidationError as e:\n errors.append(e.detail)\n if errors:\n raise ValidationError(detail=errors)\n ", "context": "class Field(object):\n def run_validators(self, value): ...\n def __init__(self, required=True, default=None, label=None, validators=None, error_messages=None, source=None, allow_none=None): ...\n def __deepcopy__(self, memo={}): ...\n def bind(self, field_name, parent): ...\n def validators(self): ...\n def validators(self, validators): ...\n def get_validators(self): ...\n def fail_validate(self, detail=None, status=400): ...\n def fail_field_validation(self, key, **kwargs): ...\n def to_internal_value(self, data): ...\n def _to_representation(self, value): ...\n def to_representation(self, value): ...\n def get_default(self): ...\n def _get_field_name(self): ...\n def _get_attribute_name(self): ...\n def _get_attribute(self, instance): ...\n def get_attribute(self, instance): ...\n def validate_empty_values(self, data): ...\n def run_validation(self, data): ...\n\n self.label = label\n self.default = default\n self.source = source\n self.allow_none = allow_none\n self.required = bool(required) if self.default is None else False\n self._src_validators = validators\n self._validators = ([RequiredValidator()] if self.required else []) + (validators or [])[:]\n self._src_messages = messages\n self.error_messages = messages\n\n default_error_messages = {'required': 'This field is required.', 'null': 'This field cannot be null.'}\n default_validators = []\n", "repository": "nxexox/python-rest-framework", "test_name": "test_run_validators", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000769.py"} {"focal_file": "rest_framework/views/mixins.py", "focal_class": null, "focal_method": "get_request_serializer", "tests": "import unittest\n\nclass Test_get_request_serializer(unittest.TestCase):\n def test_empty_serializer(self):\n\n class ForTest(ForTests, GetSerializerMixin):\n serializer_classes = {}\n mixin = ForTest()\n self.assertIsNone(mixin.get_request_serializer())\n self.assertIsNone(mixin.get_response_serializer())\n self.assertIsNone(mixin.get_serializer('in'))\n self.assertIsNone(mixin.get_serializer('out'))\n", "method_code": " def get_request_serializer(self):\n \"\"\"\n Search Serializer for request.\n \n :return: Found serializer or None.\n :rtype: Optional[Type[rest_framework.serializers.Serializer]]\n \n \"\"\"\n return self.get_serializer('in')\n ", "context": "class GetSerializerMixin(GetRequestAbstractMixin):\n def get_request_serializer(self): ...\n def get_serializer(self, key): ...\n def get_response_serializer(self): ...\n\n serializer_classes = {}\n", "repository": "nxexox/python-rest-framework", "test_name": "test_empty_serializer", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000770.py"} {"focal_file": "rest_framework/views/mixins.py", "focal_class": null, "focal_method": "get_serializer", "tests": "import unittest\n\nclass Test_get_serializer(unittest.TestCase):\n def test_get_serializer(self):\n\n class ForTest(ForTests, GetSerializerMixin):\n serializer_classes = {}\n mixin = ForTest()\n self.assertIsNone(mixin.get_serializer('in'))\n self.assertIsNone(mixin.get_serializer('out'))\n self.assertIsNone(mixin.get_serializer('IN'))\n self.assertIsNone(mixin.get_serializer('OUT'))\n self.assertIsNone(mixin.get_serializer('In'))\n self.assertIsNone(mixin.get_serializer('Out'))\n self.assertIsNone(mixin.get_serializer('iN'))\n self.assertIsNone(mixin.get_serializer('oUt'))\n self.assertIsNone(mixin.get_serializer('not_valid_key'))\n\n def test_get_single_serializer(self):\n\n class ForTest(ForTests, GetSerializerMixin):\n serializer_classes = {'get': self.serializer_for_tests}\n mixin = ForTest()\n assert issubclass(mixin.get_serializer('in'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('out'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('IN'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('OUT'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('In'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('Out'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('iN'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('oUt'), self.serializer_for_tests)\n self.assertIsNone(mixin.get_serializer('not_valid_key'))\n\n def test_full_serializers(self):\n\n class ForTest(ForTests, GetSerializerMixin):\n serializer_classes = {'get': {'in': self.serializer_for_tests, 'out': self.serializer_for_tests}}\n mixin = ForTest()\n assert issubclass(mixin.get_serializer('in'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('out'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('IN'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('OUT'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('In'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('Out'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('iN'), self.serializer_for_tests)\n assert issubclass(mixin.get_serializer('oUt'), self.serializer_for_tests)\n self.assertIsNone(mixin.get_serializer('not_valid_key'))\n", "method_code": " def get_serializer(self, key):\n \"\"\"\n Search serializer.\n \n :param str key: Key for search. Must be one from `in`, `out`.\n \n :return: Found serializer or None.\n :rtype: Optional[Type[rest_framework.serializers.Serializer]]\n \n \"\"\"\n if key.lower() not in ('in', 'out'):\n return None\n serializers = self.serializer_classes.get(self.current_request_method.lower(), dict())\n if isinstance(serializers, dict):\n return serializers.get(key, serializers.get(key.lower(), serializers.get(key.upper(), None)))\n elif issubclass(serializers, Serializer):\n return serializers\n ", "context": "class GetSerializerMixin(GetRequestAbstractMixin):\n def get_serializer(self, key): ...\n def get_response_serializer(self): ...\n def get_request_serializer(self): ...\n\n serializer_classes = {}\n", "repository": "nxexox/python-rest-framework", "test_name": "test_get_serializer", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000771.py"} {"focal_file": "rest_framework/views/mixins.py", "focal_class": null, "focal_method": "get_response", "tests": "import unittest\n\nclass Test_get_response(unittest.TestCase):\n def test_get_response(self):\n try:\n\n class ForTest(ForTests, GetResponseMixin):\n pass\n except AttributeError:\n pass\n\n def get_response(data, status, content_type='application/json'):\n return Response(data, status, content_type)\n\n class ForTest(ForTests, GetResponseMixin):\n response_class = get_response\n mixin = ForTest()\n resp = mixin.get_response({'test': 'test'}, status_code=400, is_serialized=False)\n self.assertEqual(resp.data, {'test': 'test'})\n self.assertEqual(resp.status, 400)\n", "method_code": " def get_response(self, obj=None, is_serialized=True, status_code=200):\n \"\"\"\n Create and return response object.\n \n :param object obj: Object for response body.\n :param bool is_serialized: Is data serialization required?\n :param int status_code: Code server response.\n \n :return: Response object.\n :rtype: aiohttp.web_response.Response\n \n \"\"\"\n data = obj\n if is_serialized and obj is not None:\n data = self.get_response_serializer()(obj).data\n return self.response_class.__func__(data, status=status_code, content_type=self.response_content_type)\n ", "context": "class GetResponseMixin(GetSerializerMixin):\n def get_response(self, obj=None, is_serialized=True, status_code=200): ...\n def __new__(cls, *args, **kwargs): ...\n def get_list_response(self, objs=None, is_serialized=True, status_code=200, *args, **kwargs): ...\n\n response_class = None\n pagination_class = LimitOffsetObjectsPaginator\n response_content_type = 'application/json'\n", "repository": "nxexox/python-rest-framework", "test_name": "test_get_response", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000772.py"} {"focal_file": "rest_framework/views/mixins.py", "focal_class": null, "focal_method": "get_list_response", "tests": "import unittest\n\nclass Test_get_list_response(unittest.TestCase):\n def test_get_list_response(self):\n try:\n\n class ForTest(ForTests, GetResponseMixin):\n pass\n except AttributeError:\n pass\n\n def get_response(data, status, content_type='application/json'):\n return Response(data, status, content_type)\n\n class ForTest(ForTests, GetResponseMixin):\n response_class = get_response\n pagination_class = LimitOffsetObjectsPaginator\n mixin = ForTest()\n resp = mixin.get_list_response([{'test': 'test'}], status_code=400, limit=1, offset=0, count=1, is_serialized=False)\n self.assertEqual(resp.data, {'limit': 1, 'offset': 0, 'count': 1, 'objects': [{'test': 'test'}]})\n self.assertEqual(resp.status, 400)\n", "method_code": " def get_list_response(self, objs=None, is_serialized=True, status_code=200, *args, **kwargs):\n \"\"\"\n Create and return response, object, for list objects.\n \n :param list objs: List object for return response.\n :param bool is_serialized: Is data serialization required?\n :param int status_code: Code server response.\n \n :return: Response object.\n \n \"\"\"\n data = objs\n if is_serialized and objs is not None:\n data = self.get_response_serializer()(instance=objs, many=True).data\n paginate_data = self.pagination_class(objects=data).paginate(*args, **kwargs)\n return self.get_response(paginate_data, is_serialized=False, status_code=status_code)\n ", "context": "class GetResponseMixin(GetSerializerMixin):\n def get_list_response(self, objs=None, is_serialized=True, status_code=200, *args, **kwargs): ...\n def __new__(cls, *args, **kwargs): ...\n def get_response(self, obj=None, is_serialized=True, status_code=200): ...\n\n response_class = None\n pagination_class = LimitOffsetObjectsPaginator\n response_content_type = 'application/json'\n", "repository": "nxexox/python-rest-framework", "test_name": "test_get_list_response", "smells": [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000773.py"} {"focal_file": "dataduct/config/config.py", "focal_class": null, "focal_method": "get_config_files", "tests": "import unittest\n\nclass Test_get_config_files(unittest.TestCase):\n @staticmethod\n @patch.dict('os.environ', {}, clear=True)\n def test_get_config_files_no_enviroment_variable():\n \"\"\"Tests that correct config file paths are returned when there's no\n enviroment variable\n \"\"\"\n expected = ['/etc/dataduct.cfg', expanduser('~/.dataduct/dataduct.cfg')]\n result = get_config_files()\n eq_(result, expected)\n\n @staticmethod\n @patch.dict('os.environ', {'DATADUCT_CONFIG_PATH': '/test/test.cfg'})\n def test_get_config_files_with_enviroment_variable():\n \"\"\"Tests that correct config file paths are returned when there is\n an enviroment variable\n \"\"\"\n expected = ['/etc/dataduct.cfg', expanduser('~/.dataduct/dataduct.cfg'), '/test/test.cfg']\n result = get_config_files()\n eq_(result, expected)\n", "method_code": "def get_config_files():\n \"\"\"Get the config file for dataduct\n\n Note:\n The order of precedence is:\n 1. /etc/dataduct.cfg\n 2. ~/.dataduct/dataduct.cfg\n 3. DATADUCT_CONFIG_PATH environment variable, if it exists\n\n Returns:\n A list of file paths of dataduct config file locations, in ascending\n order of precedence. There is no guarantee that the files exist.\n \"\"\"\n dataduct_config_path = join('/etc', CFG_FILE)\n dataduct_user_config_path = join(expanduser('~'), CONFIG_DIR, CFG_FILE)\n config_files = [dataduct_config_path, dataduct_user_config_path]\n if 'DATADUCT_CONFIG_PATH' in environ:\n for path in environ['DATADUCT_CONFIG_PATH'].split(':'):\n config_files.append(expanduser(path))\n return config_files", "context": "def get_config_files(): ...\ndef get_config_files(): ...\ndef load_yaml(config_files): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000774.py"} {"focal_file": "dataduct/config/config_actions.py", "focal_class": null, "focal_method": "s3_config_path", "tests": "import unittest\n\nclass Test_s3_config_path(unittest.TestCase):\n @staticmethod\n def test_s3_config_path():\n \"\"\"Tests that s3_config_path correctly returns the S3 base path\n \"\"\"\n config = Config()\n config.etl['S3_BASE_PATH'] = 'test/path'\n config.etl['S3_ETL_BUCKET'] = 'test_bucket'\n config_actions.CONFIG_STR = 'test_config_str'\n config_actions.CFG_FILE = 'test_cfg_file.cfg'\n result = config_actions.s3_config_path()\n eq_(result.bucket, 'test_bucket')\n eq_(result.key, 'test/path/test_config_str/test_cfg_file.cfg')\n", "method_code": "def s3_config_path():\n \"\"\"S3 uri for the config files\n \"\"\"\n key = [config.etl.get('S3_BASE_PATH', ''), CONFIG_STR, CFG_FILE]\n return S3Path(bucket=config.etl['S3_ETL_BUCKET'], key=key)", "context": "def s3_config_path(): ...\ndef s3_config_path(): ...\ndef sync_to_s3(): ...\ndef sync_from_s3(filename): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000775.py"} {"focal_file": "dataduct/data_access/connection.py", "focal_class": null, "focal_method": "get_redshift_config", "tests": "import unittest\n\nclass Test_get_redshift_config(unittest.TestCase):\n @staticmethod\n def test_get_redshift_config_correctly_returns():\n \"\"\"Tests that get_redshift_config can successfully retrieve the\n redshift config\n \"\"\"\n config = Config()\n config.redshift = 'test'\n eq_(connection.get_redshift_config(), 'test')\n\n @staticmethod\n @raises(ETLConfigError)\n def test_get_redshift_config_no_config_raises():\n \"\"\"Tests that get_redshift_config raises an exception if the redshift\n config cannot be found\n \"\"\"\n config = Config()\n del config.redshift\n connection.get_redshift_config()\n", "method_code": "def get_redshift_config():\n \"\"\"Get redshift config from config file and return the dictionary\n \"\"\"\n if not hasattr(config, 'redshift'):\n raise ETLConfigError('Redshift config not found')\n return config.redshift", "context": "def get_redshift_config(): ...\ndef get_redshift_config(): ...\ndef redshift_connection(redshift_creds=None, autocommit=True, **kwargs): ...\ndef get_sql_config(database_name): ...\ndef rds_connection(database_name=None, sql_creds=None, cursorclass=MySQLdb.cursors.SSCursor, **kwargs): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000776.py"} {"focal_file": "dataduct/database/parsers/select_query.py", "focal_class": null, "focal_method": "parse_select_columns", "tests": "import unittest\n\nclass Test_parse_select_columns(unittest.TestCase):\n @staticmethod\n def test_columns():\n \"\"\"Basic test for select statement\n \"\"\"\n query = \"SELECT x,CASE WHEN y=10 THEN 5 ELSE z AS a,CASE WHEN x THEN COUNT(MIN(x,y)) ELSE MIN(x) END AS b,COUNT(1) AS c,CASE WHEN course_platform = 'spark' THEN 'v1-' || topic_id::VARCHAR ELSE course_id END AS course_id FROM abc\"\n result = ['x', 'CASE WHEN y=10 THEN 5 ELSE z AS a', 'CASE WHEN x THEN COUNT(MIN(x,y)) ELSE MIN(x) END AS b', 'COUNT(1) AS c', \"CASE WHEN course_platform = 'spark' THEN 'v1-' \" + '|| topic_id::VARCHAR ELSE course_id END AS course_id']\n result_names = ['x', 'a', 'b', 'c', 'course_id']\n columns = parse_select_columns(query)\n eq_(columns, result)\n column_names = [parse_column_name(c) for c in columns]\n eq_(column_names, result_names)\n", "method_code": "def parse_select_columns(string):\n \"\"\"Parse a select query and return the columns\n\n Args:\n string(str): Input string to be parsed\n\n Returns:\n result(list of str): List of columns\n \"\"\"\n if string == '':\n return list()\n if string.upper().startswith('WITH'):\n suppressor = _with + delimitedList(_db_name + _as + subquery)\n string = suppressor.suppress().transformString(string)\n suppressor = MatchFirst(_from) + restOfLine\n string = suppressor.suppress().transformString(string)\n parser = _select + delimitedList(field_parser).setResultsName('columns')\n output = parser.parseString(string).columns.asList()\n return [column.strip() for column in output]", "context": "def parse_select_columns(string): ...\ndef deduplicate_with_order(seq): ...\ndef parse_select_base(string): ...\ndef parse_select_dependencies(string): ...\ndef parse_select_columns(string): ...\ndef parse_column_name(string): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000777.py"} {"focal_file": "dataduct/database/sql/sql_script.py", "focal_class": null, "focal_method": "append", "tests": "import unittest\n\nclass Test_append(unittest.TestCase):\n @staticmethod\n def test_append_script():\n \"\"\"Appending a script to sql script\n \"\"\"\n script = SqlScript('SELECT 1;')\n script_new = SqlScript('SELECT 2;')\n script.append(script_new)\n eq_(script.sql(), 'SELECT 1;\\nSELECT 2;')\n\n @staticmethod\n def test_append_string():\n \"\"\"Appending a string to sql script\n \"\"\"\n script = SqlScript('SELECT 1;')\n script.append('SELECT 2;')\n eq_(script.sql(), 'SELECT 1;\\nSELECT 2;')\n", "method_code": " def append(self, elements):\n \"\"\"Append the elements to the SQL script\n \"\"\"\n if elements is None:\n return self.copy()\n if isinstance(elements, SqlStatement):\n self.add_statement(elements)\n return self.copy()\n if isinstance(elements, str):\n elements = self.__class__(elements)\n for element in elements:\n self.add_statement(element)\n return self.copy()\n ", "context": "class SqlScript(object):\n def append(self, elements): ...\n def __init__(self, sql=None, statements=None, filename=None): ...\n def __str__(self): ...\n def __iter__(self): ...\n def __len__(self): ...\n def statements(self): ...\n def sql(self): ...\n def _sanitize_sql(self): ...\n def _initialize_statements(self): ...\n def copy(self): ...\n def add_statement(self, statement): ...\n def wrap_transaction(self): ...\n def creates_table(self): ...\n def creates_view(self): ...\n\n self._raw_sql = sql\n self._raw_statements = self._sanitize_sql()\n self._statements = self._initialize_statements()\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000778.py"} {"focal_file": "dataduct/database/sql/sql_script.py", "focal_class": null, "focal_method": "copy", "tests": "import unittest\n\nclass Test_copy(unittest.TestCase):\n @staticmethod\n def test_copy():\n \"\"\"Copy a sql script\n \"\"\"\n script = SqlScript('SELECT 1;')\n script_new = script.copy()\n eq_(script.sql(), script_new.sql())\n assert_not_equal(id(script), id(script_new))\n", "method_code": " def copy(self):\n \"\"\"Create a copy of the SQL Script object\n \"\"\"\n return deepcopy(self)\n ", "context": "class SqlScript(object):\n def copy(self): ...\n def __init__(self, sql=None, statements=None, filename=None): ...\n def __str__(self): ...\n def __iter__(self): ...\n def __len__(self): ...\n def statements(self): ...\n def sql(self): ...\n def _sanitize_sql(self): ...\n def _initialize_statements(self): ...\n def append(self, elements): ...\n def add_statement(self, statement): ...\n def wrap_transaction(self): ...\n def creates_table(self): ...\n def creates_view(self): ...\n\n self._raw_sql = sql\n self._raw_statements = self._sanitize_sql()\n self._statements = self._initialize_statements()\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000779.py"} {"focal_file": "dataduct/database/sql/sql_script.py", "focal_class": null, "focal_method": "wrap_transaction", "tests": "import unittest\n\nclass Test_wrap_transaction(unittest.TestCase):\n @staticmethod\n def test_wrap_transaction():\n \"\"\"Wrap the sql script in a transaction\n \"\"\"\n script = SqlScript('SELECT 1;').wrap_transaction()\n result = 'BEGIN;\\nSELECT 1;\\nCOMMIT;'\n eq_(script.sql(), result)\n", "method_code": " def wrap_transaction(self):\n \"\"\"Wrap the script in transaction\n \"\"\"\n new_script = self.__class__()\n new_script.append([BeginStatement()] + self.statements + [CommitStatement()])\n return new_script\n ", "context": "class SqlScript(object):\n def wrap_transaction(self): ...\n def __init__(self, sql=None, statements=None, filename=None): ...\n def __str__(self): ...\n def __iter__(self): ...\n def __len__(self): ...\n def statements(self): ...\n def sql(self): ...\n def _sanitize_sql(self): ...\n def _initialize_statements(self): ...\n def copy(self): ...\n def append(self, elements): ...\n def add_statement(self, statement): ...\n def creates_table(self): ...\n def creates_view(self): ...\n\n self._raw_sql = sql\n self._raw_statements = self._sanitize_sql()\n self._statements = self._initialize_statements()\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000780.py"} {"focal_file": "dataduct/database/sql/sql_script.py", "focal_class": null, "focal_method": "creates_table", "tests": "import unittest\n\nclass Test_creates_table(unittest.TestCase):\n @staticmethod\n def test_creates_table_success():\n \"\"\"Correctly recognizes that the sql creates a table\n \"\"\"\n script = SqlScript('CREATE TABLE test_begin (session_id INTEGER);')\n eq_(script.creates_table(), True)\n\n @staticmethod\n def test_creates_table_failure():\n \"\"\"Correctly recognizes that the sql does not create a table\n \"\"\"\n script = SqlScript('SELECT * FROM test_begin;')\n eq_(script.creates_table(), False)\n\n @staticmethod\n def test_creates_table_failure_bad_syntax():\n \"\"\"Correctly recognizes bad syntax when creating a view\n \"\"\"\n script = SqlScript('CREATE TABLE test_begin AS (SELECT * FROM test_table);')\n eq_(script.creates_table(), False)\n\n @staticmethod\n def test_creates_view_failure():\n \"\"\"Correctly recognizes that the sql does not create a view\n \"\"\"\n script = SqlScript('SELECT * FROM test_begin;')\n eq_(script.creates_table(), False)\n", "method_code": " def creates_table(self):\n \"\"\"SQL script creates a table.\n \"\"\"\n return self.statements[0].creates_table()\n ", "context": "class SqlScript(object):\n def creates_table(self): ...\n def __init__(self, sql=None, statements=None, filename=None): ...\n def __str__(self): ...\n def __iter__(self): ...\n def __len__(self): ...\n def statements(self): ...\n def sql(self): ...\n def _sanitize_sql(self): ...\n def _initialize_statements(self): ...\n def copy(self): ...\n def append(self, elements): ...\n def add_statement(self, statement): ...\n def wrap_transaction(self): ...\n def creates_view(self): ...\n\n self._raw_sql = sql\n self._raw_statements = self._sanitize_sql()\n self._statements = self._initialize_statements()\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000781.py"} {"focal_file": "dataduct/database/sql/sql_script.py", "focal_class": null, "focal_method": "creates_view", "tests": "import unittest\n\nclass Test_creates_view(unittest.TestCase):\n @staticmethod\n def test_creates_view_success():\n \"\"\"Correctly recognizes that the sql creates a view\n \"\"\"\n script = SqlScript('CREATE VIEW test_begin AS (SELECT * FROM test_table);')\n eq_(script.creates_view(), True)\n\n @staticmethod\n def test_creates_view_failure_bad_syntax():\n \"\"\"Correctly recognizes bad syntax when creating a view\n \"\"\"\n script = SqlScript('CREATE VIEW test_begin (session_id INTEGER);')\n eq_(script.creates_view(), False)\n", "method_code": " def creates_view(self):\n \"\"\"SQL script creates a view.\n \"\"\"\n return self.statements[0].creates_view()\n ", "context": "class SqlScript(object):\n def creates_view(self): ...\n def __init__(self, sql=None, statements=None, filename=None): ...\n def __str__(self): ...\n def __iter__(self): ...\n def __len__(self): ...\n def statements(self): ...\n def sql(self): ...\n def _sanitize_sql(self): ...\n def _initialize_statements(self): ...\n def copy(self): ...\n def append(self, elements): ...\n def add_statement(self, statement): ...\n def wrap_transaction(self): ...\n def creates_table(self): ...\n\n self._raw_sql = sql\n self._raw_statements = self._sanitize_sql()\n self._statements = self._initialize_statements()\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000782.py"} {"focal_file": "dataduct/database/database.py", "focal_class": null, "focal_method": "copy", "tests": "import unittest\n\nclass Test_copy(unittest.TestCase):\n def test_database_copy(self):\n \"\"\"Copying a database is a deepcopy\n \"\"\"\n database = Database(relations=[self.basic_table])\n database_copy = database.copy()\n assert_not_equal(database_copy.relation(self.basic_table.full_name), None)\n database_copy._relations = {}\n assert_not_equal(database.relation(self.basic_table.full_name), None)\n", "method_code": " def copy(self):\n \"\"\"Create a copy of the database object\n \"\"\"\n return deepcopy(self)\n ", "context": "class Database(object):\n def copy(self): ...\n def __init__(self, relations=None, files=None): ...\n def _initialize_relations(files): ...\n def add_relation(self, relation): ...\n def relations(self): ...\n def relation(self, relation_name): ...\n def num_views(self): ...\n def num_tables(self): ...\n def has_cycles(self, relation=None, visited=None): ...\n def sorted_relations(self): ...\n def relations_script(self, function_name, **kwargs): ...\n def grant_relations_script(self): ...\n def create_relations_script(self, grant_permissions=True): ...\n def drop_relations_script(self): ...\n def recreate_relations_script(self, grant_permissions=True): ...\n def recreate_table_dependencies(self, table_name, grant_permissions=True): ...\n def _make_node_label(relation): ...\n def visualize(self, filename=None, tables_to_show=None): ...\n\n self._relations = {}\n", "repository": "hillsdale18/ProjectX", "test_name": "test_database_copy", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000783.py"} {"focal_file": "dataduct/database/database.py", "focal_class": null, "focal_method": "has_cycles", "tests": "import unittest\n\nclass Test_has_cycles(unittest.TestCase):\n def test_database_has_cycles(self):\n \"\"\"Check if a database has cycles\n \"\"\"\n database = Database(relations=[self.first_table_dependent, self.second_table_dependent])\n eq_(database.has_cycles(), True)\n\n def test_database_has_no_cycles(self):\n \"\"\"Check if a database has no cycles\n \"\"\"\n database = Database(relations=[self.first_table_dependent, self.second_table])\n eq_(database.has_cycles(), False)\n\n def test_database_has_no_cycles_2(self):\n \"\"\"Check if a database has no cycles\n \"\"\"\n database = Database(relations=[self.first_table, self.second_table_dependent])\n eq_(database.has_cycles(), False)\n", "method_code": " def has_cycles(self, relation=None, visited=None):\n \"\"\"Check if the database has no circular dependencies\n \"\"\"\n if visited is None:\n visited = list()\n if relation:\n relations_to_check = [self.relation(x) for x in relation.dependencies if x != relation and self.relation(x) is not None]\n else:\n relations_to_check = self._relations.values()\n for relation in relations_to_check:\n if relation.full_name in visited:\n return True\n visited_copy = deepcopy(visited)\n visited_copy.append(relation.full_name)\n if self.has_cycles(relation, visited_copy):\n return True\n return False\n ", "context": "class Database(object):\n def has_cycles(self, relation=None, visited=None): ...\n def __init__(self, relations=None, files=None): ...\n def copy(self): ...\n def _initialize_relations(files): ...\n def add_relation(self, relation): ...\n def relations(self): ...\n def relation(self, relation_name): ...\n def num_views(self): ...\n def num_tables(self): ...\n def sorted_relations(self): ...\n def relations_script(self, function_name, **kwargs): ...\n def grant_relations_script(self): ...\n def create_relations_script(self, grant_permissions=True): ...\n def drop_relations_script(self): ...\n def recreate_relations_script(self, grant_permissions=True): ...\n def recreate_table_dependencies(self, table_name, grant_permissions=True): ...\n def _make_node_label(relation): ...\n def visualize(self, filename=None, tables_to_show=None): ...\n\n self._relations = {}\n", "repository": "hillsdale18/ProjectX", "test_name": "test_database_has_cycles", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000784.py"} {"focal_file": "dataduct/database/database.py", "focal_class": null, "focal_method": "sorted_relations", "tests": "import unittest\n\nclass Test_sorted_relations(unittest.TestCase):\n def test_database_sorted_relations(self):\n \"\"\"Get the topological sort of the database\n \"\"\"\n database = Database(relations=[self.first_table_dependent, self.second_table])\n relations = database.sorted_relations()\n eq_(len(relations), 2)\n eq_(relations[0].table_name, self.second_table.full_name)\n eq_(relations[1].table_name, self.first_table_dependent.full_name)\n\n @raises(RuntimeError)\n def test_database_sorted_relations_cyclic(self):\n \"\"\"Get the topological sort of the database with cycles\n \"\"\"\n database = Database(relations=[self.first_table_dependent, self.second_table_dependent])\n database.sorted_relations()\n", "method_code": " def sorted_relations(self):\n \"\"\"Topological sort of the relations for dependency management\n \"\"\"\n if self.has_cycles():\n logger.warning('Database has cycles')\n sorted_relations = []\n graph = dict(((x.full_name, x.dependencies) for x in self.relations()))\n while graph:\n acyclic = False\n for relation_name, dependencies in graph.items():\n for dependency in dependencies:\n if dependency in graph:\n break\n else:\n acyclic = True\n graph.pop(relation_name)\n sorted_relations.append(self.relation(relation_name))\n if not acyclic:\n raise RuntimeError('A cyclic dependency occurred')\n return sorted_relations\n ", "context": "class Database(object):\n def sorted_relations(self): ...\n def __init__(self, relations=None, files=None): ...\n def copy(self): ...\n def _initialize_relations(files): ...\n def add_relation(self, relation): ...\n def relations(self): ...\n def relation(self, relation_name): ...\n def num_views(self): ...\n def num_tables(self): ...\n def has_cycles(self, relation=None, visited=None): ...\n def relations_script(self, function_name, **kwargs): ...\n def grant_relations_script(self): ...\n def create_relations_script(self, grant_permissions=True): ...\n def drop_relations_script(self): ...\n def recreate_relations_script(self, grant_permissions=True): ...\n def recreate_table_dependencies(self, table_name, grant_permissions=True): ...\n def _make_node_label(relation): ...\n def visualize(self, filename=None, tables_to_show=None): ...\n\n self._relations = {}\n", "repository": "hillsdale18/ProjectX", "test_name": "test_database_sorted_relations", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000785.py"} {"focal_file": "dataduct/database/database.py", "focal_class": null, "focal_method": "create_relations_script", "tests": "import unittest\n\nclass Test_create_relations_script(unittest.TestCase):\n def test_database_create_relations_script(self):\n \"\"\"Creating relations in the database\n \"\"\"\n result = ['CREATE TABLE test_table ( id INTEGER )', 'CREATE VIEW test_view AS ( SELECT id FROM test_table )']\n compare_scripts(self.script_database.create_relations_script(False), result)\n", "method_code": " def create_relations_script(self, grant_permissions=True):\n \"\"\"SQL Script for creating all the relations of the database\n \"\"\"\n return self.relations_script('create_script', grant_permissions=grant_permissions)\n ", "context": "class Database(object):\n def create_relations_script(self, grant_permissions=True): ...\n def __init__(self, relations=None, files=None): ...\n def copy(self): ...\n def _initialize_relations(files): ...\n def add_relation(self, relation): ...\n def relations(self): ...\n def relation(self, relation_name): ...\n def num_views(self): ...\n def num_tables(self): ...\n def has_cycles(self, relation=None, visited=None): ...\n def sorted_relations(self): ...\n def relations_script(self, function_name, **kwargs): ...\n def grant_relations_script(self): ...\n def drop_relations_script(self): ...\n def recreate_relations_script(self, grant_permissions=True): ...\n def recreate_table_dependencies(self, table_name, grant_permissions=True): ...\n def _make_node_label(relation): ...\n def visualize(self, filename=None, tables_to_show=None): ...\n\n self._relations = {}\n", "repository": "hillsdale18/ProjectX", "test_name": "test_database_create_relations_script", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000786.py"} {"focal_file": "dataduct/database/database.py", "focal_class": null, "focal_method": "drop_relations_script", "tests": "import unittest\n\nclass Test_drop_relations_script(unittest.TestCase):\n def test_database_drop_relations_script(self):\n \"\"\"Dropping relations in the database\n \"\"\"\n result = ['DROP TABLE IF EXISTS test_table CASCADE', 'DROP VIEW IF EXISTS test_view CASCADE']\n compare_scripts(self.script_database.drop_relations_script(), result)\n", "method_code": " def drop_relations_script(self):\n \"\"\"SQL Script for dropping all the relations for the database\n \"\"\"\n return self.relations_script('drop_script')\n ", "context": "class Database(object):\n def drop_relations_script(self): ...\n def __init__(self, relations=None, files=None): ...\n def copy(self): ...\n def _initialize_relations(files): ...\n def add_relation(self, relation): ...\n def relations(self): ...\n def relation(self, relation_name): ...\n def num_views(self): ...\n def num_tables(self): ...\n def has_cycles(self, relation=None, visited=None): ...\n def sorted_relations(self): ...\n def relations_script(self, function_name, **kwargs): ...\n def grant_relations_script(self): ...\n def create_relations_script(self, grant_permissions=True): ...\n def recreate_relations_script(self, grant_permissions=True): ...\n def recreate_table_dependencies(self, table_name, grant_permissions=True): ...\n def _make_node_label(relation): ...\n def visualize(self, filename=None, tables_to_show=None): ...\n\n self._relations = {}\n", "repository": "hillsdale18/ProjectX", "test_name": "test_database_drop_relations_script", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000787.py"} {"focal_file": "dataduct/database/database.py", "focal_class": null, "focal_method": "recreate_relations_script", "tests": "import unittest\n\nclass Test_recreate_relations_script(unittest.TestCase):\n def test_database_recreate_relations_script(self):\n \"\"\"Recreating relations in the database\n \"\"\"\n result = ['DROP TABLE IF EXISTS test_table CASCADE', 'CREATE TABLE test_table ( id INTEGER )', 'DROP VIEW IF EXISTS test_view CASCADE', 'CREATE VIEW test_view AS ( SELECT id FROM test_table )']\n compare_scripts(self.script_database.recreate_relations_script(False), result)\n", "method_code": " def recreate_relations_script(self, grant_permissions=True):\n \"\"\"SQL Script for recreating all the relations of the database\n \"\"\"\n return self.relations_script('recreate_script', grant_permissions=grant_permissions)\n ", "context": "class Database(object):\n def recreate_relations_script(self, grant_permissions=True): ...\n def __init__(self, relations=None, files=None): ...\n def copy(self): ...\n def _initialize_relations(files): ...\n def add_relation(self, relation): ...\n def relations(self): ...\n def relation(self, relation_name): ...\n def num_views(self): ...\n def num_tables(self): ...\n def has_cycles(self, relation=None, visited=None): ...\n def sorted_relations(self): ...\n def relations_script(self, function_name, **kwargs): ...\n def grant_relations_script(self): ...\n def create_relations_script(self, grant_permissions=True): ...\n def drop_relations_script(self): ...\n def recreate_table_dependencies(self, table_name, grant_permissions=True): ...\n def _make_node_label(relation): ...\n def visualize(self, filename=None, tables_to_show=None): ...\n\n self._relations = {}\n", "repository": "hillsdale18/ProjectX", "test_name": "test_database_recreate_relations_script", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000788.py"} {"focal_file": "dataduct/database/database.py", "focal_class": null, "focal_method": "recreate_table_dependencies", "tests": "import unittest\n\nclass Test_recreate_table_dependencies(unittest.TestCase):\n def test_database_recreate_table_dependencies(self):\n \"\"\"Recreating table dependencies\n \"\"\"\n view = create_view('CREATE VIEW view AS (\\n SELECT id1 FROM second_table\\n );')\n database = Database(relations=[self.first_table_dependent, self.second_table, view])\n result = ['ALTER TABLE first_table ADD FOREIGN KEY (id2) REFERENCES second_table (id2)', 'DROP VIEW IF EXISTS view CASCADE', 'CREATE VIEW view AS ( SELECT id1 FROM second_table )']\n compare_scripts(database.recreate_table_dependencies('second_table', False), result)\n eq_(database.recreate_table_dependencies('first_table', False).sql(), ';')\n", "method_code": " def recreate_table_dependencies(self, table_name, grant_permissions=True):\n \"\"\"Recreate the dependencies for a particular table from the database\n \"\"\"\n result = SqlScript()\n for relation in self.relations():\n if relation.full_name == table_name:\n continue\n if isinstance(relation, Table):\n for column_names, ref_name, ref_columns in relation.foreign_key_references():\n if ref_name == table_name:\n result.append(relation.foreign_key_reference_script(source_columns=column_names, reference_name=ref_name, reference_columns=ref_columns))\n if isinstance(relation, View):\n if table_name in relation.dependencies:\n result.append(relation.recreate_script(grant_permissions=grant_permissions))\n return result\n ", "context": "class Database(object):\n def recreate_table_dependencies(self, table_name, grant_permissions=True): ...\n def __init__(self, relations=None, files=None): ...\n def copy(self): ...\n def _initialize_relations(files): ...\n def add_relation(self, relation): ...\n def relations(self): ...\n def relation(self, relation_name): ...\n def num_views(self): ...\n def num_tables(self): ...\n def has_cycles(self, relation=None, visited=None): ...\n def sorted_relations(self): ...\n def relations_script(self, function_name, **kwargs): ...\n def grant_relations_script(self): ...\n def create_relations_script(self, grant_permissions=True): ...\n def drop_relations_script(self): ...\n def recreate_relations_script(self, grant_permissions=True): ...\n def _make_node_label(relation): ...\n def visualize(self, filename=None, tables_to_show=None): ...\n\n self._relations = {}\n", "repository": "hillsdale18/ProjectX", "test_name": "test_database_recreate_table_dependencies", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000789.py"} {"focal_file": "dataduct/database/history_table.py", "focal_class": null, "focal_method": "update_history_script", "tests": "import unittest\n\nclass Test_update_history_script(unittest.TestCase):\n def test_history_script(self):\n \"\"\"Diff comparison of generated SQL script\n \"\"\"\n expected_script = ['CREATE TEMPORARY TABLE test_table_temp ( id INTEGER,value VARCHAR(25), PRIMARY KEY( id ) )', 'INSERT INTO test_table_temp (SELECT * FROM test_table)', \"UPDATE test_history_table SET expiration_ts = SYSDATE - INTERVAL '0.000001 seconds' FROM test_table WHERE test_history_table.id = test_table.id AND ( test_history_table.value != test_table.value OR ( test_history_table.value IS NULL AND test_table.value IS NOT NULL ) OR ( test_history_table.value IS NOT NULL AND test_table.value IS NULL ) ) AND expiration_ts = '9999-12-31 23:59:59.999999'\", \"UPDATE test_history_table SET expiration_ts = SYSDATE - INTERVAL '0.000001 seconds' WHERE ( id ) NOT IN ( SELECT id FROM test_table ) AND expiration_ts = '9999-12-31 23:59:59.999999'\", \"DELETE FROM test_table_temp WHERE (id) IN (SELECT DISTINCT id FROM (SELECT id, value FROM test_history_table WHERE expiration_ts = '9999-12-31 23:59:59.999999'))\", \"INSERT INTO test_history_table (SELECT * FROM (SELECT SYSDATE, '9999-12-31 23:59:59.999999'::TIMESTAMP, id, value FROM test_table_temp))\", 'DROP TABLE IF EXISTS test_table_temp CASCADE']\n actual_script = self.basic_history_table.update_history_script(self.basic_table)\n eq_(len(actual_script), len(expected_script))\n for actual, expected in zip(actual_script, expected_script):\n eq_(actual.sql(), expected)\n", "method_code": " def update_history_script(self, source):\n \"\"\"SQL script to update the history table\n \n Args:\n source (Table): The source from which to update history\n \n Returns:\n SqlScript: a SQL statement that updates history\n \n Raises:\n ValueError: If source is not a Table object\n \"\"\"\n if not isinstance(source, Table):\n raise ValueError('Source must be a table')\n temp_table = Table(source.temporary_clone_script())\n result = temp_table.create_script(grant_permissions=False)\n result.append(temp_table.insert_script(source))\n result.append(self._expire_history_script(source))\n result.append(temp_table.delete_matching_rows_script(self._select_current_script()))\n select_statement = SelectStatement(\"\\n SELECT SYSDATE, '{expiration_max}'::TIMESTAMP, {columns}\\n FROM {temp_table_name}\\n \".format(expiration_max=HIST_EXPIRATION_MAX, columns=', '.join([c.name for c in temp_table.columns()]), temp_table_name=temp_table.full_name))\n result.append(self.insert_script(select_statement))\n result.append(temp_table.drop_script())\n return result\n ", "context": "class HistoryTable(Table):\n def update_history_script(self, source): ...\n def __init__(self, sql): ...\n def _select_current_script(self): ...\n def _expire_history_script(self, source): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "test_history_script", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000790.py"} {"focal_file": "dataduct/database/table.py", "focal_class": null, "focal_method": "unload_script", "tests": "import unittest\n\nclass Test_unload_script(unittest.TestCase):\n def test_unload_script(self):\n \"\"\"Tests if the unload script generates successfully\n \"\"\"\n result = [\"UNLOAD ('SELECT * FROM test_table;') TO 's3://test/' CREDENTIALS 'aws_access_key_id=a;aws_secret_access_key=b' DELIMITER '\\t' ESCAPE NULL AS 'NULL'\"]\n compare_scripts(self.basic_table.unload_script('s3://test/', 'a', 'b'), result)\n\n def test_unload_script_with_token(self):\n \"\"\"Tests if the unload script generates successfully\n \"\"\"\n result = [\"UNLOAD ('SELECT * FROM test_table;') TO 's3://test/' CREDENTIALS 'aws_access_key_id=a;aws_secret_access_key=b;token=c' DELIMITER '\\t' ESCAPE NULL AS 'NULL'\"]\n compare_scripts(self.basic_table.unload_script('s3://test/', 'a', 'b', 'c'), result)\n", "method_code": " def unload_script(self, s3_path, access_key, secret_key, token=None):\n \"\"\"Sql script to unload table to S3\n \"\"\"\n script = \"UNLOAD ('{select_script}') TO '{s3_path}' CREDENTIALS '{creds}' DELIMITER '\\t' ESCAPE NULL AS 'NULL'\".format(select_script=self.select_script(), s3_path=s3_path, creds=stringify_credentials(access_key, secret_key, token))\n return SqlScript(script)\n ", "context": "class Table(Relation):\n def unload_script(self, s3_path, access_key, secret_key, token=None): ...\n def __init__(self, sql): ...\n def update_attributes_from_columns(self): ...\n def update_columns_with_constrains(self): ...\n def columns(self): ...\n def column(self, column_name): ...\n def primary_keys(self): ...\n def primary_key_names(self): ...\n def foreign_key_references(self): ...\n def dependencies(self): ...\n def temporary_clone_script(self): ...\n def exists_clone_script(self): ...\n def drop_script(self): ...\n def analyze_script(self): ...\n def rename_script(self, new_name): ...\n def delete_script(self, where_condition=''): ...\n def foreign_key_reference_script(self, source_columns, reference_name, reference_columns): ...\n def select_duplicates_script(self): ...\n def _source_sql(self, source_relation): ...\n def insert_script(self, source_relation): ...\n def delete_matching_rows_script(self, source_relation): ...\n def de_duplication_script(self): ...\n def upsert_script(self, source_relation, enforce_primary_key=True, delete_existing=False): ...\n def check_not_exists_script(self): ...\n def load_script(self, s3_path, access_key, secret_key, token=None): ...\n\n self.sql_statement = sql\n self.parameters = parameters\n self.full_name = parameters.get('full_name')\n self.temporary = parameters.get('temporary')\n self.exists_check = parameters.get('exists_check', False)\n self.sort_keys = parameters.get('sortkey', list())\n self.dist_keys = parameters.get('distkey', list())\n self.diststyle = parameters.get('diststyle', 'EVEN')\n self._constraints = parameters.get('constraints', list())\n self._columns = dict()\n self.schema_name, self.table_name = self.initialize_name()\n", "repository": "hillsdale18/ProjectX", "test_name": "test_unload_script", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000791.py"} {"focal_file": "dataduct/database/table.py", "focal_class": null, "focal_method": "load_script", "tests": "import unittest\n\nclass Test_load_script(unittest.TestCase):\n def test_load_script(self):\n \"\"\"Tests if the unload script generates successfully\n \"\"\"\n result = [\"COPY test_table FROM 's3://test/' CREDENTIALS 'aws_access_key_id=a;aws_secret_access_key=b' DELIMITER '\\t' ESCAPE NULL AS 'NULL'\"]\n compare_scripts(self.basic_table.load_script('s3://test/', 'a', 'b'), result)\n\n def test_load_script_with_token(self):\n \"\"\"Tests if the unload script generates successfully\n \"\"\"\n result = [\"COPY test_table FROM 's3://test/' CREDENTIALS 'aws_access_key_id=a;aws_secret_access_key=b;token=c' DELIMITER '\\t' ESCAPE NULL AS 'NULL'\"]\n compare_scripts(self.basic_table.load_script('s3://test/', 'a', 'b', 'c'), result)\n", "method_code": " def load_script(self, s3_path, access_key, secret_key, token=None):\n \"\"\"Sql script to load table from S3\n \"\"\"\n script = \"COPY {name} FROM '{s3_path}' CREDENTIALS '{creds}' DELIMITER '\\t' ESCAPE NULL AS 'NULL'\".format(name=self.full_name, s3_path=s3_path, creds=stringify_credentials(access_key, secret_key, token))\n return SqlScript(script)\n ", "context": "class Table(Relation):\n def load_script(self, s3_path, access_key, secret_key, token=None): ...\n def __init__(self, sql): ...\n def update_attributes_from_columns(self): ...\n def update_columns_with_constrains(self): ...\n def columns(self): ...\n def column(self, column_name): ...\n def primary_keys(self): ...\n def primary_key_names(self): ...\n def foreign_key_references(self): ...\n def dependencies(self): ...\n def temporary_clone_script(self): ...\n def exists_clone_script(self): ...\n def drop_script(self): ...\n def analyze_script(self): ...\n def rename_script(self, new_name): ...\n def delete_script(self, where_condition=''): ...\n def foreign_key_reference_script(self, source_columns, reference_name, reference_columns): ...\n def select_duplicates_script(self): ...\n def _source_sql(self, source_relation): ...\n def insert_script(self, source_relation): ...\n def delete_matching_rows_script(self, source_relation): ...\n def de_duplication_script(self): ...\n def upsert_script(self, source_relation, enforce_primary_key=True, delete_existing=False): ...\n def check_not_exists_script(self): ...\n def unload_script(self, s3_path, access_key, secret_key, token=None): ...\n\n self.sql_statement = sql\n self.parameters = parameters\n self.full_name = parameters.get('full_name')\n self.temporary = parameters.get('temporary')\n self.exists_check = parameters.get('exists_check', False)\n self.sort_keys = parameters.get('sortkey', list())\n self.dist_keys = parameters.get('distkey', list())\n self.diststyle = parameters.get('diststyle', 'EVEN')\n self._constraints = parameters.get('constraints', list())\n self._columns = dict()\n self.schema_name, self.table_name = self.initialize_name()\n", "repository": "hillsdale18/ProjectX", "test_name": "test_load_script", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000792.py"} {"focal_file": "dataduct/etl/etl_actions.py", "focal_class": null, "focal_method": "read_pipeline_definition", "tests": "import unittest\n\nclass Test_read_pipeline_definition(unittest.TestCase):\n def test_read_pipeline_definition(self):\n \"\"\"Test if the pipeline definition is parsed correctly\n \"\"\"\n with TempDirectory() as directory:\n directory.write('test_definition.yaml', self.test_yaml)\n result = read_pipeline_definition(os.path.join(directory.path, 'test_definition.yaml'))\n eq_(result, self.test_definition)\n", "method_code": "def read_pipeline_definition(file_path):\n \"\"\"Function reads the yaml pipeline definitions.\n\n Function reads the yaml pipeline definitions. We also remove the variables\n key as that was only used for yaml placeholders.\n\n Args:\n file_path (str): Path to the pipeline definition.\n\n Returns:\n dict: parsed yaml definition as dictionary.\n\n Raises:\n ETLInputError: If `file_path` extention is not yaml\n \"\"\"\n extension = file_path.split('.').pop()\n if extension != 'yaml':\n raise ETLInputError('Pipeline definition should have a yaml extention')\n with open(file_path) as f:\n definition = yaml.load(f.read())\n definition.pop('variables', None)\n return definition", "context": "def read_pipeline_definition(file_path): ...\ndef read_pipeline_definition(file_path): ...\ndef create_pipeline(definition): ...\ndef validate_pipeline(etl, force=False): ...\ndef activate_pipeline(etl): ...\ndef visualize_pipeline(etl, activities_only=False, filename=None): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "test_read_pipeline_definition", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000793.py"} {"focal_file": "dataduct/etl/etl_actions.py", "focal_class": null, "focal_method": "create_pipeline", "tests": "import unittest\n\nclass Test_create_pipeline(unittest.TestCase):\n def test_create_pipeline(self):\n \"\"\"Test if simple pipeline creation is correct\n \"\"\"\n result = create_pipeline(self.test_definition)\n assert result.name.endswith(self.test_definition['name'])\n eq_(result.frequency, self.test_definition['frequency'])\n eq_(result.load_hour, int(self.load_hour))\n eq_(result.load_min, int(self.load_min))\n eq_(result.max_retries, self.test_definition['max_retries'])\n steps = result.steps\n assert 'ExtractLocalStep0' in steps\n assert 'LoadRedshiftStep0' in steps\n", "method_code": "def create_pipeline(definition):\n \"\"\"Creates the pipeline and add the steps specified to the pipeline\n\n Args:\n definition(dict): YAML definition parsed from the datapipeline\n \"\"\"\n steps = definition.pop('steps')\n etl = ETLPipeline(**definition)\n etl.create_steps(steps)\n etl.create_teardown_step()\n logger.info('Created pipeline. Name: %s', etl.name)\n return etl", "context": "def create_pipeline(definition): ...\ndef read_pipeline_definition(file_path): ...\ndef create_pipeline(definition): ...\ndef validate_pipeline(etl, force=False): ...\ndef activate_pipeline(etl): ...\ndef visualize_pipeline(etl, activities_only=False, filename=None): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "test_create_pipeline", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000794.py"} {"focal_file": "dataduct/utils/hook.py", "focal_class": null, "focal_method": "default_before_hook", "tests": "import unittest\n\nclass Test_default_before_hook(unittest.TestCase):\n @staticmethod\n def test_default_before_hook_simple():\n \"\"\"Tests that the default before hook works properly (nothing changes)\n \"\"\"\n args, kwargs = default_before_hook(1, '2', three=3)\n eq_(args, (1, '2'))\n eq_(kwargs, {'three': 3})\n\n @staticmethod\n def test_default_before_hook_no_params():\n \"\"\"Tests that the default before hook works properly even with no\n parameters\n \"\"\"\n args, kwargs = default_before_hook()\n eq_(args, ())\n eq_(kwargs, {})\n\n @staticmethod\n def test_default_before_hook_only_args():\n \"\"\"Tests that the default before hook works properly with only args\n \"\"\"\n args, kwargs = default_before_hook(1, '2')\n eq_(args, (1, '2'))\n eq_(kwargs, {})\n\n @staticmethod\n def test_default_before_hook_only_kwargs():\n \"\"\"Tests that the default before hook works properly with only kwargs\n \"\"\"\n args, kwargs = default_before_hook(one=1, two='2')\n eq_(args, ())\n eq_(kwargs, {'one': 1, 'two': '2'})\n", "method_code": "def default_before_hook(*args, **kwargs):\n \"\"\"The default before hook, will act like it's not even there\n \"\"\"\n return (args, kwargs)", "context": "def default_before_hook(*args, **kwargs): ...\ndef default_before_hook(*args, **kwargs): ...\ndef default_after_hook(result): ...\ndef get_hooks(hook_name): ...\ndef hook(hook_name): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000795.py"} {"focal_file": "dataduct/utils/hook.py", "focal_class": null, "focal_method": "default_after_hook", "tests": "import unittest\n\nclass Test_default_after_hook(unittest.TestCase):\n @staticmethod\n def test_default_after_hook_simple():\n \"\"\"Tests that the default after hook works properly\n \"\"\"\n result = default_after_hook('test')\n eq_(result, 'test')\n", "method_code": "def default_after_hook(result):\n \"\"\"The default after hook, will act like it's not even there\n \"\"\"\n return result", "context": "def default_after_hook(result): ...\ndef default_before_hook(*args, **kwargs): ...\ndef default_after_hook(result): ...\ndef get_hooks(hook_name): ...\ndef hook(hook_name): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000796.py"} {"focal_file": "dataduct/utils/hook.py", "focal_class": null, "focal_method": "hook", "tests": "import unittest\n\nclass Test_hook(unittest.TestCase):\n def test_both_before_and_after_hook(self):\n \"\"\"Tests that you can have an before and an after hook\n \"\"\"\n hook_file = '\\n'.join(['def before_hook(number):', ' return [number + 1], {}', 'def after_hook(result):', ' return result + 2'])\n self.temp_directory.write('test_hook.py', hook_file)\n\n @hook('test_hook')\n def test_hook(number):\n return number\n eq_(test_hook(1), 4)\n\n @hook('test_hook')\n def test_hook(number):\n return number\n", "method_code": "def hook(hook_name):\n \"\"\"The hook decorator creator\n \"\"\"\n before_hook, after_hook = get_hooks(hook_name)\n\n def hook_decorator(func):\n \"\"\"The hook decorator\n \"\"\"\n\n def function_wrapper(*args, **kwargs):\n \"\"\"The hook wrapper for the function\n \"\"\"\n new_args, new_kwargs = before_hook(*args, **kwargs)\n result = func(*new_args, **new_kwargs)\n new_result = after_hook(result)\n return new_result\n return function_wrapper\n return hook_decorator", "context": "def hook(hook_name): ...\ndef default_before_hook(*args, **kwargs): ...\ndef default_after_hook(result): ...\ndef get_hooks(hook_name): ...\ndef hook(hook_name): ...\n", "repository": "hillsdale18/ProjectX", "test_name": "test_both_before_and_after_hook", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000797.py"} {"focal_file": "xtide.py", "focal_class": null, "focal_method": "run_xtide", "tests": "import unittest\n\nclass Test_run_xtide(unittest.TestCase):\n def test_run_xtide_basic(self):\n ret = xtide.run_xtide('San Francisco Bay Entrance', 1000000000)\n self.assertTrue(len(ret) > 10)\n self.assertEqual(len(ret[5]), 2)\n\n def test_run_xtide_start_stop(self):\n ret = xtide.run_xtide('San Francisco Bay Entrance', 1000000000, 1000000600)\n self.assertEqual(len(ret), 10)\n\n def test_run_xtide_bad_station(self):\n with self.assertRaises(Exception):\n xtide.run_xtide('ASDFGHJKL', 1000000000)\n\n def test_run_xtide_bad_tcd_file(self):\n with self.assertRaises(Exception):\n xtide.run_xtide('ASDFGHJKL', 1000000000, tcd_file='asdfqwer')\n", "method_code": "def run_xtide(site_name, start_time=None, stop_time=None, tcd_file=default_tcd):\n \"\"\"Run XTide's command-line tool to compute tide magnitudes for each\n minute between start_time and stop_time.\n\n Arguments:\n site_name: XTide station name. May be an elevation or current station.\n start_time: Unix-time (seconds). Defaults to now.\n stop_time: Unix-time (seconds). Defaults to now + 12 hours.\n tcd_file: Path of XTide \"TCD\" tidal constituents database file to use.\n Returns: [[unix-time, magnitude], ...]\n Throws: ValueError, CalledProgramError, Exception\n\n \"\"\"\n try:\n start_time = float(start_time)\n except:\n start_time = time.time()\n try:\n stop_time = float(stop_time)\n except:\n stop_time = start_time + 12 * 60 * 60\n site_name_clean = re.sub('[^A-Za-z0-9()., ]', '', site_name[0:100])\n if site_name != site_name_clean:\n raise Exception('INVALID_SITE')\n start_str = time.strftime('%Y-%m-%d %H:%M', time.localtime(start_time))\n stop_str = time.strftime('%Y-%m-%d %H:%M', time.localtime(stop_time))\n _env = dict(os.environ)\n if tcd_file:\n _env['HFILE_PATH'] = tcd_file\n xtide, xtide_err = Popen(['tide', '-l', site_name, '-b', start_str, '-e', stop_str, '-m', 'r', '-s', '00:01'], stdout=PIPE, stderr=PIPE, env=_env).communicate()\n m = re.search('XTide (?:Fatal )?Error:\\\\s+.*$', xtide_err, re.MULTILINE)\n if m:\n raise Exception(m.group(0))\n p = re.compile('^([\\\\d.]+)\\\\s+([-\\\\d.]+)$', re.M)\n return [[int(seconds), float(level)] for seconds, level in re.findall(p, xtide)]", "context": "def run_xtide(site_name, start_time=None, stop_time=None, tcd_file=default_tcd): ...\ndef run_xtide(site_name, start_time=None, stop_time=None, tcd_file=default_tcd): ...\ndef target_spans(levels, target=0.0, levels2=None, target2=0.0, maxima=False, now=False): ...\ndef xtide_graph(site_name, start_time=None, tcd_file=default_tcd): ...\n", "repository": "leverich/tidely", "test_name": "test_run_xtide_basic", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000798.py"} {"focal_file": "xtide.py", "focal_class": null, "focal_method": "target_spans", "tests": "import unittest\n\nclass Test_target_spans(unittest.TestCase):\n def test_span_basic(self):\n ret = make_levels([2, 1, 0, -1, -2, -1, 0, 1, 2])\n spans = xtide.target_spans(ret)\n self.assertEqual(len(spans), 3)\n self.assertEqual(spans[0]['state'], 1)\n self.assertEqual(spans[1]['state'], 0)\n self.assertEqual(spans[2]['state'], 1)\n spans = xtide.target_spans(ret, 100000)\n self.assertEqual(len(spans), 1)\n\n def test_span_now(self):\n now_time = time.time()\n ret = xtide.run_xtide('San Francisco Bay Entrance', start_time=now_time - 120, stop_time=now_time + 24 * 60 * 60)\n spans = xtide.target_spans(ret, now=True)\n filtered = filter(lambda x: 'now' in x, spans)\n self.assertEqual(len(filtered), 1)\n", "method_code": "def target_spans(levels, target=0.0, levels2=None, target2=0.0, maxima=False, now=False):\n \"\"\"Convert list of tide predictions (from run_xtide(site)) into\n spans. A new span is created each time a sequence of tide\n predictions crosses a target magnitude (default 0.0). If levels2\n and target2 are given, a new span is created if either set of\n predictions crosses its target.\n\n If two lists are given, their times must align exactly or the\n output is undefined.\n\n A span is of the form:\n { state: int, start: float, end: float,\n maximum: [ magnitude, time ],\n now: [ magnitude, time ] }\n\n Start and end are unix timestamps. State encodes which of level\n and level2 is above its target:\n\n 3 if level2 and level is above target\n 2 if level2 is above target\n 1 if level is above target\n 0 if neither is above target\n\n maximum and now are optional, and mark events within a span.\n\n \"\"\"\n assert len(levels) > 1\n try:\n target = float(target)\n except:\n target = 0.0\n try:\n target2 = float(target2)\n except:\n target2 = 0.0\n if levels2:\n assert len(levels) == len(levels2)\n assert levels[0][0] == levels2[0][0]\n last_state = None\n last_time = levels[0][0]\n this_time = levels[0][0]\n now_buffer = None\n if now:\n now_time = time.time()\n lt_now = levels[0][0] < now_time\n max_buffer = None\n if maxima:\n prev_level = None\n prev_dir = None\n prev_time = None\n if levels2:\n zip_levels = zip(levels, levels2)\n else:\n zip_levels = zip(levels, [[None, None] for i in range(len(levels))])\n\n def get_state(a, b=None):\n return (0 if a < target else 1) + (0 if b is None or b < target2 else 2)\n\n def make_span(last_state, last_time, this_time, now_buffer, max_buffer):\n span = {'state': last_state, 'start': last_time, 'end': this_time - 1}\n if now_buffer:\n span['now'] = now_buffer\n if max_buffer:\n span['maximum'] = max_buffer\n return span\n spans = []\n for (seconds, level), (seconds2, level2) in zip_levels:\n this_state = get_state(level, level2)\n this_time = seconds\n if now and lt_now and (this_time > now_time):\n now_buffer = [level, seconds]\n lt_now = False\n if maxima:\n if prev_level:\n this_dir = prev_level < level\n if prev_dir is not None and this_dir != prev_dir:\n max_buffer = [prev_level, prev_time]\n prev_dir = this_dir\n prev_level = level\n prev_time = this_time\n if last_state is not None and this_state != last_state:\n spans.append(make_span(last_state, last_time, this_time, now_buffer, max_buffer))\n now_buffer = None\n max_buffer = None\n last_time = this_time\n last_state = this_state\n spans.append(make_span(last_state, last_time, this_time, now_buffer, max_buffer))\n return spans", "context": "def target_spans(levels, target=0.0, levels2=None, target2=0.0, maxima=False, now=False): ...\ndef run_xtide(site_name, start_time=None, stop_time=None, tcd_file=default_tcd): ...\ndef target_spans(levels, target=0.0, levels2=None, target2=0.0, maxima=False, now=False): ...\ndef xtide_graph(site_name, start_time=None, tcd_file=default_tcd): ...\n", "repository": "leverich/tidely", "test_name": "test_span_basic", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000799.py"} {"focal_file": "apiview/views/dtd/jsonschema.py", "focal_class": null, "focal_method": "json2schema", "tests": "import unittest\n\nclass Test_json2schema(unittest.TestCase):\n def test_json2schema(self):\n self.assertEqual(json2schema([])['type'], 'array')\n self.assertEqual(json2schema({})['type'], 'object')\n self.assertEqual(json2schema({'a': 1.1})['properties']['a']['type'], 'number')\n self.assertEqual(json2schema({'a': 1})['properties']['a']['type'], 'integer')\n self.assertEqual(json2schema({'a': ''})['properties']['a']['type'], 'string')\n self.assertEqual(json2schema({'a': []})['properties']['a']['type'], 'array')\n self.assertEqual(json2schema({'a': {}})['properties']['a']['type'], 'object')\n", "method_code": "def json2schema(node, name=None, path=(), check_value=True):\n \"\"\"Return a strict validation schema for the given JSON node\"\"\"\n node_type = type(node)\n if node_type not in reversed_types:\n for type_, schemta in iteritems(reversed_types):\n if isinstance(node, type_):\n reversed_types[node_type] = schemta\n break\n else:\n raise DTDSchemaError('Unexpected type %s at path %s' % (node_type, path), instance=node, path=path)\n schema = DEFAULT_SCHEMA_NODE.copy()\n schema['type'] = reversed_types[node_type]\n if schema['type'] == 'array':\n length = len(node)\n if length:\n sub_schemas = []\n sub_path = get_subpath(name, path)\n sub_types = set()\n for sub_node in node:\n sub_schema = json2schema(sub_node, path=sub_path, check_value=False)\n sub_types.add(sub_schema['type'])\n sub_schemas.append(sub_schema)\n if not sub_types.intersection(['array', 'object']):\n if check_value:\n schema['value'] = node\n sub_schemas = [{'type': _type} for _type in sub_types]\n schema['items'] = {'anyOf': sub_schemas}\n schema['maxItems'] = schema['minItems'] = length\n else:\n schema['value'] = node\n schema['minItems'] = 0\n schema['additionalItems'] = False\n elif schema['type'] == 'object':\n sub_items = []\n sub_path = get_subpath(name, path)\n for sub_name, sub_node in iteritems(node):\n sub_items.append((sub_name, json2schema(sub_node, sub_name, sub_path, check_value=check_value)))\n if sub_items:\n properties = {}\n for sub_name, sub_schema in sub_items:\n properties[sub_name] = sub_schema\n schema['properties'] = properties\n schema['required'] = list(properties)\n schema['additionalProperties'] = False\n elif check_value:\n schema['value'] = node\n return schema", "context": "def json2schema(node, name=None, path=(), check_value=True): ...\ndef _value(validator, value, instance, schema): ...\ndef get_subnode(root, path): ...\ndef get_subpath(name, path): ...\ndef json2schema(node, name=None, path=(), check_value=True): ...\ndef gen_errors(data, schema, valudator=None): ...\ndef validate(data, schema, validator=None): ...\ndef flex_schema_by_err(schema, err): ...\ndef flex_schema_by_errs(schema, errs): ...\ndef flex_type(schema, err): ...\ndef flex_required(schema, err): ...\ndef flex_minItems(schema, err): ...\ndef flex_maxItems(schema, err): ...\ndef flex_value(schema, err): ...\ndef flex_additionalProperties(schema, err): ...\ndef flex_anyOf(schema, err): ...\n", "repository": "007gzs/django_restframework_apiview", "test_name": "test_json2schema", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000800.py"} {"focal_file": "apiview/views/dtd/jsonschema.py", "focal_class": null, "focal_method": "flex_schema_by_errs", "tests": "import unittest\n\nclass Test_flex_schema_by_errs(unittest.TestCase):\n def test_flex_schema_by_errs(self):\n data = {'string': 'value', 'int': 1, 'num': 1.0, 'array': [1, 2, 3, 4], 'object': {'sub_object': {'sub_string': 'value', 'sub_int': 1, 'sub_num': 1.0, 'sub_array': [{'in_array': 'string'}, {'in_array': 1}]}}}\n schema = json2schema(data)\n data['int'] = 2\n self.assertEqual(next(gen_errors(data, schema)).validator, 'value')\n flex_schema_by_errs(schema, list(gen_errors(data, schema)))\n self.assertFalse(list(gen_errors(data, schema)))\n data['int'] = 2.0\n self.assertEqual(next(gen_errors(data, schema)).validator, 'type')\n flex_schema_by_errs(schema, list(gen_errors(data, schema)))\n self.assertFalse(list(gen_errors(data, schema)))\n data['object']['sub_object']['sub_int'] = 2\n self.assertEqual(next(gen_errors(data, schema)).validator, 'value')\n flex_schema_by_errs(schema, list(gen_errors(data, schema)))\n self.assertFalse(list(gen_errors(data, schema)))\n data['array'] = [1, 2]\n self.assertEqual(len(list(gen_errors(data, schema))), 2)\n flex_schema_by_errs(schema, list(gen_errors(data, schema)))\n self.assertFalse(list(gen_errors(data, schema)))\n data['array'] = [1, 2, 3, 4] * 2\n self.assertEqual(next(gen_errors(data, schema)).validator, 'maxItems')\n flex_schema_by_errs(schema, list(gen_errors(data, schema)))\n self.assertFalse(list(gen_errors(data, schema)))\n data['array'] = [1, 2, '5']\n self.assertEqual(next(gen_errors(data, schema)).validator, 'anyOf')\n flex_schema_by_errs(schema, list(gen_errors(data, schema)))\n self.assertFalse(list(gen_errors(data, schema)))\n data['new_object'] = {'some': 'new object'}\n self.assertEqual(next(gen_errors(data, schema)).validator, 'additionalProperties')\n flex_schema_by_errs(schema, list(gen_errors(data, schema)))\n self.assertFalse(list(gen_errors(data, schema)))\n data['object']['sub_object']['sub_array'] = [1, 2, '5', {'some': 'mixed value'}]\n self.assertEqual(next(gen_errors(data, schema)).validator, 'anyOf')\n flex_schema_by_errs(schema, list(gen_errors(data, schema)))\n self.assertFalse(list(gen_errors(data, schema)))\n", "method_code": "def flex_schema_by_errs(schema, errs):\n \"\"\"Flex schema according to the DTDValidationErrors\"\"\"\n for err in errs:\n flex_schema_by_err(schema, err)", "context": "def flex_schema_by_errs(schema, errs): ...\ndef _value(validator, value, instance, schema): ...\ndef get_subnode(root, path): ...\ndef get_subpath(name, path): ...\ndef json2schema(node, name=None, path=(), check_value=True): ...\ndef gen_errors(data, schema, valudator=None): ...\ndef validate(data, schema, validator=None): ...\ndef flex_schema_by_err(schema, err): ...\ndef flex_schema_by_errs(schema, errs): ...\ndef flex_type(schema, err): ...\ndef flex_required(schema, err): ...\ndef flex_minItems(schema, err): ...\ndef flex_maxItems(schema, err): ...\ndef flex_value(schema, err): ...\ndef flex_additionalProperties(schema, err): ...\ndef flex_anyOf(schema, err): ...\n", "repository": "007gzs/django_restframework_apiview", "test_name": "test_flex_schema_by_errs", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000801.py"} {"focal_file": "avatars/core/color.py", "focal_class": "Color", "focal_method": "brighter_or_darker_than", "tests": "import unittest\n\nclass Test_Color_brighter_or_darker_than(unittest.TestCase):\n def test_brighter_or_darker1(self):\n color1 = Color('#556677')\n color2 = Color('#667788')\n self.assertEqual(color1.brighter_or_darker_than(color2, 25).hex, '#333d48')\n\n def test_brighter_or_darker2(self):\n color1 = Color('#667788')\n color2 = Color('#556677')\n self.assertEqual(color1.brighter_or_darker_than(color2, 25).hex, '#899fb6')\n", "method_code": " def brighter_or_darker_than(self, color, difference):\n primary_h, primary_s, primary_v = self.hsv\n secondary_h, secondary_s, secondary_v = color.hsv\n if primary_v <= secondary_v:\n return self.darker_than(color, difference)\n else:\n return self.brighter_than(color, difference)\n ", "context": "class Color(object):\n def brighter_or_darker_than(self, color, difference): ...\n def __init__(self, color_hex=None): ...\n def set_hsv(self, hue, saturation, value): ...\n def set_hsl(self, hue, saturation, lightness): ...\n def set_rgb(self, red, green, blue): ...\n def clone(self): ...\n def hex(self): ...\n def hsv(self): ...\n def hsl(self): ...\n def __str__(self): ...\n def lighten(self): ...\n def darken(self): ...\n def lighten_than(self, ratio): ...\n def darken_than(self, ratio): ...\n def brighter_than(self, color, difference): ...\n def darker_than(self, color, difference): ...\n\n self._rgb = hex2rgb(color_hex) if color_hex else (0, 0, 0)\n self._hsv = None\n self._hsl = None\n", "repository": "007gzs/avatars", "test_name": "test_brighter_or_darker1", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000802.py"} {"focal_file": "payment_page_sdk/signature_handler.py", "focal_class": null, "focal_method": "check", "tests": "import unittest\n\nclass Test_check(unittest.TestCase):\n def test_check(self):\n compare_data = copy.deepcopy(self.payment_data)\n signature = compare_data['body']['signature']\n del compare_data['body']['signature']\n self.assertTrue(self.signature_handler.check(compare_data['body'], signature))\n", "method_code": " def check(self, params: dict, signature):\n \"\"\"\n Check signature\n \n :param dict params:\n :param signature:\n :return:\n \"\"\"\n return self.sign(params) == signature\n ", "context": "class SignatureHandler(object):\n def check(self, params: dict, signature): ...\n def __init__(self, secret_key: str): ...\n def sign(self, params: dict) -> str: ...\n def __get_params_to_sign(self, params: dict, ignore=None, prefix='', sort=True) -> dict: ...\n\n self.__secretKey = secret_key\n\n ITEMS_DELIMITER = ';'\n IGNORE_KEYS = ['frame_mode']\n __secretKey = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_check", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000803.py"} {"focal_file": "payment_page_sdk/signature_handler.py", "focal_class": null, "focal_method": "sign", "tests": "import unittest\n\nclass Test_sign(unittest.TestCase):\n def test_sign(self):\n compare_data = copy.deepcopy(self.payment_data)\n del compare_data['body']['signature']\n self.assertEqual(self.payment_data['body']['signature'], self.signature_handler.sign(compare_data['body']))\n", "method_code": " def sign(self, params: dict) -> str:\n \"\"\"\n Return signature\n \n :param params:\n :return:\n \"\"\"\n secret_key = self.__secretKey.encode('utf-8')\n params_to_sign = self.__get_params_to_sign(params, self.IGNORE_KEYS)\n params_to_sign_list = list(OrderedDict(sorted(params_to_sign.items(), key=lambda t: t[0])).values())\n string_to_sign = self.ITEMS_DELIMITER.join(params_to_sign_list).encode('utf-8')\n return base64.b64encode(hmac.new(secret_key, string_to_sign, hmac._hashlib.sha512).digest()).decode()\n ", "context": "class SignatureHandler(object):\n def sign(self, params: dict) -> str: ...\n def __init__(self, secret_key: str): ...\n def check(self, params: dict, signature): ...\n def __get_params_to_sign(self, params: dict, ignore=None, prefix='', sort=True) -> dict: ...\n\n self.__secretKey = secret_key\n\n ITEMS_DELIMITER = ';'\n IGNORE_KEYS = ['frame_mode']\n __secretKey = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_sign", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000804.py"} {"focal_file": "payment_page_sdk/callback.py", "focal_class": null, "focal_method": "get_payment", "tests": "import unittest\n\nclass Test_get_payment(unittest.TestCase):\n def test_get_payment(self):\n self.assertEqual(self.callback.get_payment(), self.payment_data['payment'])\n", "method_code": " def get_payment(self):\n \"\"\"\n Get payment info\n \n :return: mixed\n \"\"\"\n return self.get_value('payment')\n ", "context": "class Callback(object):\n def get_payment(self): ...\n def __init__(self, data: str, signature_handler: SignatureHandler): ...\n def get_payment_status(self) -> str: ...\n def get_payment_id(self) -> str: ...\n def get_signature(self) -> str: ...\n def decode_response(self, raw_data: str) -> dict: ...\n def check_signature(self) -> bool: ...\n def get_value(self, pathname: str): ...\n def __remove_param(self, name: str, data: dict): ...\n\n self.__data = self.decode_response(data)\n self.__signatureHandler = signature_handler\n\n SUCCESS_STATUS = 'success'\n DECLINE_STATUS = 'decline'\n AW_3DS_STATUS = 'awaiting 3ds result'\n AW_RED_STATUS = 'awaiting redirect result'\n AW_CUS_STATUS = 'awaiting customer'\n AW_CLA_STATUS = 'awaiting clarification'\n AW_CAP_STATUS = 'awaiting capture'\n CANCELLED_STATUS = 'cancelled'\n REFUNDED_STATUS = 'refunded'\n PART_REFUNDED_STATUS = 'partially refunded'\n PROCESSING_STATUS = 'processing'\n ERROR_STATUS = 'error'\n REVERSED_STATUS = 'reversed'\n __data = None\n __signatureHandler = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_get_payment", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000805.py"} {"focal_file": "payment_page_sdk/callback.py", "focal_class": null, "focal_method": "get_payment_status", "tests": "import unittest\n\nclass Test_get_payment_status(unittest.TestCase):\n def test_get_payment_status(self):\n self.assertEqual(self.callback.get_payment_status(), self.payment_data['payment']['status'])\n", "method_code": " def get_payment_status(self) -> str:\n \"\"\"\n Get payment status\n \n :return: str\n \"\"\"\n return self.get_value('payment.status')\n ", "context": "class Callback(object):\n def get_payment_status(self) -> str: ...\n def __init__(self, data: str, signature_handler: SignatureHandler): ...\n def get_payment(self): ...\n def get_payment_id(self) -> str: ...\n def get_signature(self) -> str: ...\n def decode_response(self, raw_data: str) -> dict: ...\n def check_signature(self) -> bool: ...\n def get_value(self, pathname: str): ...\n def __remove_param(self, name: str, data: dict): ...\n\n self.__data = self.decode_response(data)\n self.__signatureHandler = signature_handler\n\n SUCCESS_STATUS = 'success'\n DECLINE_STATUS = 'decline'\n AW_3DS_STATUS = 'awaiting 3ds result'\n AW_RED_STATUS = 'awaiting redirect result'\n AW_CUS_STATUS = 'awaiting customer'\n AW_CLA_STATUS = 'awaiting clarification'\n AW_CAP_STATUS = 'awaiting capture'\n CANCELLED_STATUS = 'cancelled'\n REFUNDED_STATUS = 'refunded'\n PART_REFUNDED_STATUS = 'partially refunded'\n PROCESSING_STATUS = 'processing'\n ERROR_STATUS = 'error'\n REVERSED_STATUS = 'reversed'\n __data = None\n __signatureHandler = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_get_payment_status", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000806.py"} {"focal_file": "payment_page_sdk/callback.py", "focal_class": null, "focal_method": "get_payment_id", "tests": "import unittest\n\nclass Test_get_payment_id(unittest.TestCase):\n def test_get_payment_id(self):\n self.assertEqual(self.callback.get_payment_id(), self.payment_data['payment']['id'])\n", "method_code": " def get_payment_id(self) -> str:\n \"\"\"\n Get payment ID\n \n :return: str\n \"\"\"\n return self.get_value('payment.id')\n ", "context": "class Callback(object):\n def get_payment_id(self) -> str: ...\n def __init__(self, data: str, signature_handler: SignatureHandler): ...\n def get_payment(self): ...\n def get_payment_status(self) -> str: ...\n def get_signature(self) -> str: ...\n def decode_response(self, raw_data: str) -> dict: ...\n def check_signature(self) -> bool: ...\n def get_value(self, pathname: str): ...\n def __remove_param(self, name: str, data: dict): ...\n\n self.__data = self.decode_response(data)\n self.__signatureHandler = signature_handler\n\n SUCCESS_STATUS = 'success'\n DECLINE_STATUS = 'decline'\n AW_3DS_STATUS = 'awaiting 3ds result'\n AW_RED_STATUS = 'awaiting redirect result'\n AW_CUS_STATUS = 'awaiting customer'\n AW_CLA_STATUS = 'awaiting clarification'\n AW_CAP_STATUS = 'awaiting capture'\n CANCELLED_STATUS = 'cancelled'\n REFUNDED_STATUS = 'refunded'\n PART_REFUNDED_STATUS = 'partially refunded'\n PROCESSING_STATUS = 'processing'\n ERROR_STATUS = 'error'\n REVERSED_STATUS = 'reversed'\n __data = None\n __signatureHandler = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_get_payment_id", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000807.py"} {"focal_file": "payment_page_sdk/callback.py", "focal_class": null, "focal_method": "get_signature", "tests": "import unittest\n\nclass Test_get_signature(unittest.TestCase):\n def test_get_signature(self):\n self.assertEqual(self.callback.get_signature(), self.payment_data['signature'])\n", "method_code": " def get_signature(self) -> str:\n \"\"\"\n Get signature\n \n :return: str\n \"\"\"\n sign_paths = ['signature', 'general.signature']\n for sign_path in sign_paths:\n sign = self.get_value(sign_path)\n if sign is not None:\n return sign\n raise ProcessException('Signature undefined')\n ", "context": "class Callback(object):\n def get_signature(self) -> str: ...\n def __init__(self, data: str, signature_handler: SignatureHandler): ...\n def get_payment(self): ...\n def get_payment_status(self) -> str: ...\n def get_payment_id(self) -> str: ...\n def decode_response(self, raw_data: str) -> dict: ...\n def check_signature(self) -> bool: ...\n def get_value(self, pathname: str): ...\n def __remove_param(self, name: str, data: dict): ...\n\n self.__data = self.decode_response(data)\n self.__signatureHandler = signature_handler\n\n SUCCESS_STATUS = 'success'\n DECLINE_STATUS = 'decline'\n AW_3DS_STATUS = 'awaiting 3ds result'\n AW_RED_STATUS = 'awaiting redirect result'\n AW_CUS_STATUS = 'awaiting customer'\n AW_CLA_STATUS = 'awaiting clarification'\n AW_CAP_STATUS = 'awaiting capture'\n CANCELLED_STATUS = 'cancelled'\n REFUNDED_STATUS = 'refunded'\n PART_REFUNDED_STATUS = 'partially refunded'\n PROCESSING_STATUS = 'processing'\n ERROR_STATUS = 'error'\n REVERSED_STATUS = 'reversed'\n __data = None\n __signatureHandler = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_get_signature", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000808.py"} {"focal_file": "payment_page_sdk/callback.py", "focal_class": null, "focal_method": "decode_response", "tests": "import unittest\n\nclass Test_decode_response(unittest.TestCase):\n def test_decode_response(self):\n with self.assertRaises(ProcessException):\n self.callback.decode_response(json.dumps(self.payment_data) + '1')\n", "method_code": " def decode_response(self, raw_data: str) -> dict:\n \"\"\"\n Cast raw data to array\n \n :param str raw_data:\n :return: dict\n \n :raise: ProcessException\n \"\"\"\n try:\n data = json.loads(raw_data)\n except ValueError:\n raise ProcessException('Error on response decoding')\n return data\n ", "context": "class Callback(object):\n def decode_response(self, raw_data: str) -> dict: ...\n def __init__(self, data: str, signature_handler: SignatureHandler): ...\n def get_payment(self): ...\n def get_payment_status(self) -> str: ...\n def get_payment_id(self) -> str: ...\n def get_signature(self) -> str: ...\n def check_signature(self) -> bool: ...\n def get_value(self, pathname: str): ...\n def __remove_param(self, name: str, data: dict): ...\n\n self.__data = self.decode_response(data)\n self.__signatureHandler = signature_handler\n\n SUCCESS_STATUS = 'success'\n DECLINE_STATUS = 'decline'\n AW_3DS_STATUS = 'awaiting 3ds result'\n AW_RED_STATUS = 'awaiting redirect result'\n AW_CUS_STATUS = 'awaiting customer'\n AW_CLA_STATUS = 'awaiting clarification'\n AW_CAP_STATUS = 'awaiting capture'\n CANCELLED_STATUS = 'cancelled'\n REFUNDED_STATUS = 'refunded'\n PART_REFUNDED_STATUS = 'partially refunded'\n PROCESSING_STATUS = 'processing'\n ERROR_STATUS = 'error'\n REVERSED_STATUS = 'reversed'\n __data = None\n __signatureHandler = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_decode_response", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000809.py"} {"focal_file": "payment_page_sdk/payment.py", "focal_class": "Payment", "focal_method": "get_params", "tests": "import unittest\n\nclass Test_Payment_get_params(unittest.TestCase):\n def test_get_params(self):\n payment = Payment('1')\n payment.payment_id = 'test-payment'\n payment.best_before = datetime(2055, 5, 5)\n self.assertEqual(self.compare_data, payment.get_params())\n", "method_code": " def get_params(self) -> dict:\n \"\"\"\n Get payment parameters\n \n :return: dict\n \"\"\"\n return self.__dict__\n ", "context": "class Payment(object):\n def get_params(self) -> dict: ...\n def __init__(self, project_id: str, payment_id: str=''): ...\n def __setattr__(self, name, value): ...\n\n self.__dict__['project_id'] = project_id\n self.__dict__['interface_type'] = json.dumps({'id': self.INTERFACE_TYPE})\n\n PURCHASE_TYPE = 'purchase'\n PAYOUT_TYPE = 'payout'\n RECURRING_TYPE = 'recurring'\n INTERFACE_TYPE = 24\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_get_params", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000810.py"} {"focal_file": "payment_page_sdk/payment_page.py", "focal_class": null, "focal_method": "get_url", "tests": "import unittest\n\nclass Test_get_url(unittest.TestCase):\n def test_get_url(self):\n payment = Payment('1', 'test-payment')\n payment.best_before = datetime(2055, 5, 5)\n self.assertEqual(urlparse.parse_qs(urlparse.urlparse(self.compare_url).query), urlparse.parse_qs(urlparse.urlparse(self.payment_page.get_url(payment)).query))\n", "method_code": " def get_url(self, payment: Payment) -> str:\n \"\"\"\n Get full URL for payment\n \n :param Payment payment:\n :return:\n \"\"\"\n return self.__baseUrl + '?' + urllib.parse.urlencode(payment.get_params()) + '&signature=' + urllib.parse.quote_plus(self.__signatureHandler.sign(payment.get_params()))\n ", "context": "class PaymentPage(object):\n def get_url(self, payment: Payment) -> str: ...\n def __init__(self, signature_handler: SignatureHandler, base_url: str=''): ...\n\n self.__signatureHandler = signature_handler\n\n __baseUrl = 'https://paymentpage.ecommpay.com/payment'\n __signatureHandler = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_get_url", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000811.py"} {"focal_file": "payment_page_sdk/gate.py", "focal_class": null, "focal_method": "get_purchase_payment_page_url", "tests": "import unittest\n\nclass Test_get_purchase_payment_page_url(unittest.TestCase):\n def test_get_purchase_payment_page_url(self):\n payment = Payment('1', 'test-payment')\n payment.best_before = datetime(2055, 5, 5)\n purchase_payment_page_url = self.gate.get_purchase_payment_page_url(payment)\n url_parsed_params = urlparse.parse_qs(urlparse.urlparse(self.compare_url).query)\n gen_url_parsed_params = urlparse.parse_qs(urlparse.urlparse(purchase_payment_page_url).query)\n self.assertEqual(url_parsed_params, gen_url_parsed_params)\n", "method_code": " def get_purchase_payment_page_url(self, payment: Payment) -> str:\n \"\"\"\n Get URL for purchase payment page\n \n :param Payment payment:\n :return:\n \"\"\"\n return self.__paymentPageUrlBuilder.get_url(payment)\n ", "context": "class Gate(object):\n def get_purchase_payment_page_url(self, payment: Payment) -> str: ...\n def __init__(self, secret: str, base_url: str=''): ...\n def handle_callback(self, data): ...\n\n self.__signatureHandler = SignatureHandler(secret)\n self.__paymentPageUrlBuilder = PaymentPage(self.__signatureHandler, base_url)\n\n CURRENCY_RUB = 'RUB'\n CURRENCY_USD = 'USD'\n CURRENCY_EUR = 'EUR'\n __paymentPageUrlBuilder = None\n __signatureHandler = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_get_purchase_payment_page_url", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000812.py"} {"focal_file": "payment_page_sdk/gate.py", "focal_class": null, "focal_method": "handle_callback", "tests": "import unittest\n\nclass Test_handle_callback(unittest.TestCase):\n def test_handle_callback(self):\n callback_data_raw = json.dumps(self.callback_data)\n callback = self.gate.handle_callback(callback_data_raw)\n self.assertTrue(isinstance(callback, Callback))\n", "method_code": " def handle_callback(self, data):\n \"\"\"\n Callback handler\n \n :param data:\n :return:\n \"\"\"\n return Callback(data, self.__signatureHandler)\n ", "context": "class Gate(object):\n def handle_callback(self, data): ...\n def __init__(self, secret: str, base_url: str=''): ...\n def get_purchase_payment_page_url(self, payment: Payment) -> str: ...\n\n self.__signatureHandler = SignatureHandler(secret)\n self.__paymentPageUrlBuilder = PaymentPage(self.__signatureHandler, base_url)\n\n CURRENCY_RUB = 'RUB'\n CURRENCY_USD = 'USD'\n CURRENCY_EUR = 'EUR'\n __paymentPageUrlBuilder = None\n __signatureHandler = None\n", "repository": "ITECOMMPAY/paymentpage-sdk-python", "test_name": "test_handle_callback", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000813.py"} {"focal_file": "ria/bipartite_sum.py", "focal_class": null, "focal_method": "update_anomalous_score", "tests": "import unittest\n\nclass Test_update_anomalous_score(unittest.TestCase):\n def test_update_anomalous_score(self):\n \"\"\"Test updating anomalous scores.\n\n A new anomalous score is the weighted average of differences\n between current summary and reviews. The weights come from credibilities.\n\n Therefore, the new anomalous score is defined as\n\n .. math::\n\n {\\\\rm anomalous}(r)\n = \\\\sum_{p \\\\in P} \\\\mbox{review}(p) \\\\times \\\\mbox{credibility}(p)\n - 0.5\n\n where :math:`P` is a set of products reviewed by this reviewer,\n review(:math:`p`) and credibility(:math:`p`) are\n review and credibility of product :math:`p`, respectively.\n \"\"\"\n res = 0\n for i, r in enumerate(self.reviews[0].values()):\n p = self.products[i]\n c = self.reviewers[0]._credibility(p)\n res += p.summary.difference(r) * c - 0.5\n old = self.reviewers[0].anomalous_score\n self.assertAlmostEqual(self.reviewers[0].update_anomalous_score(), abs(old - res))\n self.assertAlmostEqual(self.reviewers[0].anomalous_score, res)\n", "method_code": " def update_anomalous_score(self):\n \"\"\"Update anomalous score.\n \n New anomalous score is the summation of weighted differences\n between current summary and reviews. The weights come from credibilities.\n \n Therefore, the new anomalous score is defined as\n \n .. math::\n \n {\\\\rm anomalous}(r)\n = \\\\sum_{p \\\\in P} \\\\mbox{review}(p) \\\\times \\\\mbox{credibility}(p) - 0.5\n \n where :math:`P` is a set of products reviewed by this reviewer,\n review(:math:`p`) and credibility(:math:`p`) are\n review and credibility of product :math:`p`, respectively.\n \n Returns:\n absolute difference between old anomalous score and updated one.\n \"\"\"\n old = self.anomalous_score\n products = self._graph.retrieve_products(self)\n self.anomalous_score = sum((p.summary.difference(self._graph.retrieve_review(self, p)) * self._credibility(p) - 0.5 for p in products))\n return abs(self.anomalous_score - old)\n \n __slots__ = ()\n", "context": "class Reviewer(bipartite.Reviewer):\n def update_anomalous_score(self): ...", "repository": "rgmining/ria", "test_name": "test_update_anomalous_score", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000814.py"} {"focal_file": "ria/bipartite.py", "focal_class": null, "focal_method": "update_anomalous_score", "tests": "import unittest\n\nclass Test_update_anomalous_score(unittest.TestCase):\n def test_update_anomalous_score(self):\n \"\"\"Test updating anomalous scores.\n\n A new anomalous score is the weighted average of differences\n between current summary and reviews. The weights come from credibilities.\n\n Therefore, the new anomalous score is defined as\n\n .. math::\n\n {\\\\rm anomalous}(r) = \\\\frac{\n \\\\sum_{p \\\\in P} {\\\\rm credibility}(p)|\n {\\\\rm review}(r, p)-{\\\\rm summary}(p)|\n }{\n \\\\sum_{p \\\\in P} {\\\\rm credibility}(p)\n }\n\n where :math:`P` is a set of products reviewed by reviewer :math:`p`,\n review(:math:`r`, :math:`p`) is the rating reviewer :math:`r` posted\n to product :math:`p`, summary(:math:`p`) and credibility(:math:`p`) are\n summary and credibility of product :math:`p`, respectively.\n \"\"\"\n res = 0\n weight = 0\n for i, r in enumerate(self.reviews[0].values()):\n p = self.products[i]\n c = self.reviewers[0]._credibility(p)\n res += p.summary.difference(r) * c\n weight += c\n expected = res / weight\n old = self.reviewers[0].anomalous_score\n self.assertAlmostEqual(self.reviewers[0].update_anomalous_score(), abs(old - expected))\n self.assertAlmostEqual(self.reviewers[0].anomalous_score, expected)\n", "method_code": " def update_anomalous_score(self):\n \"\"\"Update anomalous score.\n \n New anomalous score is a weighted average of differences\n between current summary and reviews. The weights come from credibilities.\n \n Therefore, the new anomalous score of reviewer :math:`p` is as\n \n .. math::\n \n {\\\\rm anomalous}(r) = \\\\frac{\n \\\\sum_{p \\\\in P} {\\\\rm credibility}(p)|\n {\\\\rm review}(r, p)-{\\\\rm summary}(p)|\n }{\n \\\\sum_{p \\\\in P} {\\\\rm credibility}(p)\n }\n \n where :math:`P` is a set of products reviewed by reviewer :math:`p`,\n review(:math:`r`, :math:`p`) is the rating reviewer :math:`r` posted\n to product :math:`p`, summary(:math:`p`) and credibility(:math:`p`) are\n summary and credibility of product :math:`p`, respectively.\n \n Returns:\n absolute difference between old anomalous score and updated one.\n \"\"\"\n products = self._graph.retrieve_products(self)\n diffs = [p.summary.difference(self._graph.retrieve_review(self, p)) for p in products]\n old = self.anomalous_score\n try:\n self.anomalous_score = np.average(diffs, weights=list(map(self._credibility, products)))\n except ZeroDivisionError:\n self.anomalous_score = np.average(diffs)\n return abs(self.anomalous_score - old)\n ", "context": "class Reviewer(_Node):\n def update_anomalous_score(self): ...\n def __init__(self, graph, credibility, name=None, anomalous=None): ...\n def anomalous_score(self): ...\n def anomalous_score(self, v): ...\n\n self._anomalous = anomalous\n self._credibility = credibility\n\n __slots__ = ('_anomalous', '_credibility')\n", "repository": "rgmining/ria", "test_name": "test_update_anomalous_score", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000815.py"} {"focal_file": "ria/bipartite.py", "focal_class": null, "focal_method": "update_summary", "tests": "import unittest\n\nclass Test_update_summary(unittest.TestCase):\n def test_update_summary(self):\n \"\"\"Test updating summary.\n\n The updated summary of a product :math:`p` is a weighted average of\n reviews. The weights are computed by a given weight function.\n\n .. math::\n\n {\\\\rm summary}(p) = \\\\frac{\n \\\\sum_{r \\\\in R} \\\\mbox{weight}(r) \\\\times \\\\mbox{review}(r, p)\n }{\n \\\\sum_{r \\\\in R} \\\\mbox{weight}(r)\n },\n\n where :math:`R` is a set of reviewers reviewing this product,\n review(:math:`r, p`) and weight(:math:`r`) are\n the review and weight of the reviewer :math:`r`, respectively.\n \"\"\"\n w = self.graph._weight_generator(self.reviewers)\n res = 0\n weights = 0\n for i, r in enumerate(self.reviewers):\n res += self.reviews[i][2].score * w(r.anomalous_score)\n weights += w(r.anomalous_score)\n old = self.products[2].summary.score\n expected = res / weights\n self.products[2].update_summary(w)\n self.assertAlmostEqual(self.products[2].update_summary(w), abs(old - expected))\n self.assertAlmostEqual(self.products[2].summary.score, expected)\n", "method_code": " def update_summary(self, w):\n \"\"\"Update summary.\n \n The new summary is a weighted average of reviews i.e.\n \n .. math::\n \n \\\\frac{\\\\sum_{r \\\\in R} \\\\mbox{weight}(r) \\\\times \\\\mbox{review}(r)}\n {\\\\sum_{r \\\\in R} \\\\mbox{weight}(r)},\n \n where :math:`R` is a set of reviewers reviewing this product,\n :math:`\\\\mbox{review}(r)` and :math:`\\\\mbox{weight}(r)` are\n the review and weight of the reviewer :math:`r`, respectively.\n \n Args:\n w: A weight function.\n \n Returns:\n absolute difference between old summary and updated one.\n \"\"\"\n old = self.summary.v\n reviewers = self._graph.retrieve_reviewers(self)\n reviews = [self._graph.retrieve_review(r, self).score for r in reviewers]\n weights = [w(r.anomalous_score) for r in reviewers]\n if sum(weights) == 0:\n self.summary = np.mean(reviews)\n else:\n self.summary = np.average(reviews, weights=weights)\n return abs(self.summary.v - old)\n ", "context": "class Product(_Node):\n def update_summary(self, w): ...\n def __init__(self, graph, name=None, summary_cls=AverageSummary): ...\n def summary(self): ...\n def summary(self, v): ...\n\n self._summary = None\n self._summary_cls = summary_cls\n\n __slots__ = ('_summary', '_summary_cls')\n", "repository": "rgmining/ria", "test_name": "test_update_summary", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000816.py"} {"focal_file": "ria/bipartite.py", "focal_class": null, "focal_method": "new_reviewer", "tests": "import unittest\n\nclass Test_new_reviewer(unittest.TestCase):\n def test_new_reviewer(self):\n \"\"\"Test for creating reviewers.\n \"\"\"\n name1 = 'test-reviewer1'\n r1 = self.graph.new_reviewer(name1, 0.1)\n self.assertEqual(r1.name, name1)\n self.assertIsInstance(r1, self.graph._reviewer_cls)\n self.assertAlmostEqual(r1.anomalous_score, 0.1)\n name2 = 'test-reviewer2'\n r2 = self.graph.new_reviewer(name2)\n self.assertEqual(r2.name, name2)\n self.assertAlmostEqual(r2.anomalous_score, 0.5)\n self.assertEqual(len(self.graph.reviewers), 2)\n self.assertIn(r1, self.graph.reviewers)\n self.assertIn(r2, self.graph.reviewers)\n\n def test_with_random_reviewers(self):\n \"\"\"Test with random reviewers.\n \"\"\"\n reviewers = [self.graph.new_reviewer('reviewer-{0}'.format(i), random.random()) for i in range(10)]\n w = self.graph._weight_generator(reviewers)\n scores = [r.anomalous_score for r in reviewers]\n mu = np.average(scores)\n sigma = np.std(scores)\n for r in reviewers:\n exp = np.exp(self.alpha * (r.anomalous_score - mu) / sigma)\n self.assertAlmostEqual(w(r.anomalous_score), 1.0 / (1.0 + exp))\n", "method_code": " def new_reviewer(self, name, anomalous=None):\n \"\"\"Create a new reviewer.\n \n Args:\n name: name of the new reviewer.\n anomalous: initial anomalous score. (default: None)\n \n Returns:\n A new reviewer instance.\n \"\"\"\n n = self._reviewer_cls(self, name=name, credibility=self.credibility, anomalous=anomalous)\n self.graph.add_node(n)\n self.reviewers.append(n)\n return n\n ", "context": "class BipartiteGraph(object):\n def new_reviewer(self, name, anomalous=None): ...\n def __init__(self, summary=AverageSummary, alpha=1, credibility=WeightedCredibility, reviewer=Reviewer, product=Product): ...\n def new_product(self, name): ...\n def add_review(self, reviewer, product, review, date=None): ...\n def retrieve_products(self, reviewer): ...\n def retrieve_reviewers(self, product): ...\n def retrieve_review(self, reviewer, product): ...\n def update(self): ...\n def _weight_generator(self, reviewers): ...\n def dump_credibilities(self, output): ...\n def to_pydot(self): ...\n\n self.alpha = alpha\n self.graph = nx.DiGraph()\n self.reviewers = []\n self.products = []\n self._summary_cls = summary\n self._review_cls = summary.review_class()\n self.credibility = credibility(self)\n self._reviewer_cls = reviewer\n self._product_cls = product\n", "repository": "rgmining/ria", "test_name": "test_new_reviewer", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000817.py"} {"focal_file": "ria/bipartite.py", "focal_class": null, "focal_method": "new_product", "tests": "import unittest\n\nclass Test_new_product(unittest.TestCase):\n def test_new_product(self):\n \"\"\"Test for creating products.\n \"\"\"\n name = 'test-product'\n p = self.graph.new_product(name)\n self.assertEqual(p.name, name)\n self.assertIsInstance(p, self.graph._product_cls)\n self.assertEqual(len(self.graph.products), 1)\n self.assertIn(p, self.graph.products)\n", "method_code": " def new_product(self, name):\n \"\"\"Create a new product.\n \n Args:\n name: name of the new product.\n \n Returns:\n A new product instance.\n \"\"\"\n n = self._product_cls(self, name, summary_cls=self._summary_cls)\n self.graph.add_node(n)\n self.products.append(n)\n return n\n ", "context": "class BipartiteGraph(object):\n def new_product(self, name): ...\n def __init__(self, summary=AverageSummary, alpha=1, credibility=WeightedCredibility, reviewer=Reviewer, product=Product): ...\n def new_reviewer(self, name, anomalous=None): ...\n def add_review(self, reviewer, product, review, date=None): ...\n def retrieve_products(self, reviewer): ...\n def retrieve_reviewers(self, product): ...\n def retrieve_review(self, reviewer, product): ...\n def update(self): ...\n def _weight_generator(self, reviewers): ...\n def dump_credibilities(self, output): ...\n def to_pydot(self): ...\n\n self.alpha = alpha\n self.graph = nx.DiGraph()\n self.reviewers = []\n self.products = []\n self._summary_cls = summary\n self._review_cls = summary.review_class()\n self.credibility = credibility(self)\n self._reviewer_cls = reviewer\n self._product_cls = product\n", "repository": "rgmining/ria", "test_name": "test_new_product", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000818.py"} {"focal_file": "ria/bipartite.py", "focal_class": null, "focal_method": "add_review", "tests": "import unittest\n\nclass Test_add_review(unittest.TestCase):\n def test_add_review(self):\n \"\"\"Test for adding reviews.\n\n This test uses the following sample graph.\n\n .. graphviz::\n\n digraph bipartite {\n graph [rankdir = LR];\n \"reviewer-0\";\n \"reviewer-1\";\n \"product-0\";\n \"product-1\";\n \"product-2\";\n \"reviewer-0\" -> \"product-0\" [label=\"0.1\"];\n \"reviewer-0\" -> \"product-1\" [label=\"0.1\"];\n \"reviewer-0\" -> \"product-2\" [label=\"0.1\"];\n \"reviewer-1\" -> \"product-1\" [label=\"0.8\"];\n \"reviewer-1\" -> \"product-2\" [label=\"0.8\"];\n }\n\n \"\"\"\n reviewers = [self.graph.new_reviewer('reviewer-{0}'.format(i)) for i in range(2)]\n products = [self.graph.new_product('product-{0}'.format(i)) for i in range(3)]\n for i, r in enumerate(reviewers):\n for j in range(i, len(products)):\n rating = 0.1 if i == 0 else 0.8\n review = self.graph.add_review(r, products[j], rating)\n self.assertEqual(review.score, rating)\n with self.assertRaises(TypeError):\n self.graph.add_review(reviewers[0], reviewers[0], 0.1)\n with self.assertRaises(TypeError):\n self.graph.add_review(products[0], products[0], 0.1)\n", "method_code": " def add_review(self, reviewer, product, review, date=None):\n \"\"\"Add a new review from a given reviewer to a given product.\n \n Args:\n reviewer: an instance of Reviewer.\n product: an instance of Product.\n review: a float value.\n date: date the review issued.\n \n Returns:\n the added new review object.\n \n Raises:\n TypeError: when given reviewer and product aren't instance of\n specified reviewer and product class when this graph is constructed.\n \"\"\"\n if not isinstance(reviewer, self._reviewer_cls):\n raise TypeError(\"Type of given reviewer isn't acceptable:\", reviewer, ', expected:', self._reviewer_cls)\n elif not isinstance(product, self._product_cls):\n raise TypeError(\"Type of given product isn't acceptable:\", product, ', expected:', self._product_cls)\n r = self._review_cls(review, date=date)\n self.graph.add_edge(reviewer, product, review=r)\n return r\n ", "context": "class BipartiteGraph(object):\n def add_review(self, reviewer, product, review, date=None): ...\n def __init__(self, summary=AverageSummary, alpha=1, credibility=WeightedCredibility, reviewer=Reviewer, product=Product): ...\n def new_reviewer(self, name, anomalous=None): ...\n def new_product(self, name): ...\n def retrieve_products(self, reviewer): ...\n def retrieve_reviewers(self, product): ...\n def retrieve_review(self, reviewer, product): ...\n def update(self): ...\n def _weight_generator(self, reviewers): ...\n def dump_credibilities(self, output): ...\n def to_pydot(self): ...\n\n self.alpha = alpha\n self.graph = nx.DiGraph()\n self.reviewers = []\n self.products = []\n self._summary_cls = summary\n self._review_cls = summary.review_class()\n self.credibility = credibility(self)\n self._reviewer_cls = reviewer\n self._product_cls = product\n", "repository": "rgmining/ria", "test_name": "test_add_review", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000819.py"} {"focal_file": "ria/bipartite.py", "focal_class": null, "focal_method": "retrieve_reviewers", "tests": "import unittest\n\nclass Test_retrieve_reviewers(unittest.TestCase):\n def test_retrieve_reviewers(self):\n \"\"\"Test retriving reviewers from a product.\n \"\"\"\n self.assertEqual(set(self.graph.retrieve_reviewers(self.products[0])), set(self.reviewers[:1]))\n self.assertEqual(set(self.graph.retrieve_reviewers(self.products[1])), set(self.reviewers))\n self.assertEqual(set(self.graph.retrieve_reviewers(self.products[2])), set(self.reviewers))\n with self.assertRaises(TypeError):\n self.graph.retrieve_reviewers(self.reviewers[0])\n", "method_code": " def retrieve_reviewers(self, product):\n \"\"\"Retrieve reviewers who reviewed a given product.\n \n Args:\n product: A product specifying reviewers.\n \n Returns:\n A list of reviewers who review the product.\n \n Raises:\n TypeError: when given product isn't instance of specified product\n class when this graph is constructed.\n \"\"\"\n if not isinstance(product, self._product_cls):\n raise TypeError(\"Type of given product isn't acceptable:\", product, ', expected:', self._product_cls)\n return list(self.graph.predecessors(product))\n ", "context": "class BipartiteGraph(object):\n @memoized\n def retrieve_reviewers(self, product): ...\n def __init__(self, summary=AverageSummary, alpha=1, credibility=WeightedCredibility, reviewer=Reviewer, product=Product): ...\n def new_reviewer(self, name, anomalous=None): ...\n def new_product(self, name): ...\n def add_review(self, reviewer, product, review, date=None): ...\n def retrieve_products(self, reviewer): ...\n def retrieve_review(self, reviewer, product): ...\n def update(self): ...\n def _weight_generator(self, reviewers): ...\n def dump_credibilities(self, output): ...\n def to_pydot(self): ...\n\n self.alpha = alpha\n self.graph = nx.DiGraph()\n self.reviewers = []\n self.products = []\n self._summary_cls = summary\n self._review_cls = summary.review_class()\n self.credibility = credibility(self)\n self._reviewer_cls = reviewer\n self._product_cls = product\n", "repository": "rgmining/ria", "test_name": "test_retrieve_reviewers", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000820.py"} {"focal_file": "ria/bipartite.py", "focal_class": null, "focal_method": "retrieve_products", "tests": "import unittest\n\nclass Test_retrieve_products(unittest.TestCase):\n def test_retrieve_products(self):\n \"\"\"Test retriving proucts from a reviewer\n\n Sample graph used in this test is as same as\n :meth:`test_retrieve_reviewers`.\n \"\"\"\n self.assertEqual(set(self.graph.retrieve_products(self.reviewers[0])), set(self.products))\n self.assertEqual(set(self.graph.retrieve_products(self.reviewers[1])), set(self.products[1:]))\n with self.assertRaises(TypeError):\n self.graph.retrieve_products(self.products[0])\n", "method_code": " def retrieve_products(self, reviewer):\n \"\"\"Retrieve products reviewed by a given reviewer.\n \n Args:\n reviewer: A reviewer.\n \n Returns:\n A list of products which the reviewer reviews.\n \n Raises:\n TypeError: when given reviewer isn't instance of specified reviewer\n class when this graph is constructed.\n \"\"\"\n if not isinstance(reviewer, self._reviewer_cls):\n raise TypeError(\"Type of given reviewer isn't acceptable:\", reviewer, ', expected:', self._reviewer_cls)\n return list(self.graph.successors(reviewer))\n ", "context": "class BipartiteGraph(object):\n @memoized\n def retrieve_products(self, reviewer): ...\n def __init__(self, summary=AverageSummary, alpha=1, credibility=WeightedCredibility, reviewer=Reviewer, product=Product): ...\n def new_reviewer(self, name, anomalous=None): ...\n def new_product(self, name): ...\n def add_review(self, reviewer, product, review, date=None): ...\n def retrieve_reviewers(self, product): ...\n def retrieve_review(self, reviewer, product): ...\n def update(self): ...\n def _weight_generator(self, reviewers): ...\n def dump_credibilities(self, output): ...\n def to_pydot(self): ...\n\n self.alpha = alpha\n self.graph = nx.DiGraph()\n self.reviewers = []\n self.products = []\n self._summary_cls = summary\n self._review_cls = summary.review_class()\n self.credibility = credibility(self)\n self._reviewer_cls = reviewer\n self._product_cls = product\n", "repository": "rgmining/ria", "test_name": "test_retrieve_products", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000821.py"} {"focal_file": "ria/bipartite.py", "focal_class": null, "focal_method": "retrieve_review", "tests": "import unittest\n\nclass Test_retrieve_review(unittest.TestCase):\n def test_retrieve_review(self):\n \"\"\"Test retriving reviews from a reviewer and a product.\n\n Sample graph used in this test is as same as\n :meth:`test_retrieve_reviewers`.\n \"\"\"\n for i, r in enumerate(self.reviewers):\n for j, p in enumerate(self.products):\n if j in self.reviews[i]:\n self.assertEqual(self.graph.retrieve_review(r, p), self.reviews[i][j])\n with self.assertRaises(TypeError):\n self.graph.retrieve_review(self.reviewers[0], self.reviewers[1])\n with self.assertRaises(TypeError):\n self.graph.retrieve_review(self.products[0], self.products[1])\n", "method_code": " def retrieve_review(self, reviewer, product):\n \"\"\"Retrieve review that the given reviewer put the given product.\n \n Args:\n reviewer: An instance of Reviewer.\n product: An instance of Product.\n \n Returns:\n A review object.\n \n Raises:\n TypeError: when given reviewer and product aren't instance of\n specified reviewer and product class when this graph is constructed.\n KeyError: When the reviewer does not review the product.\n \"\"\"\n if not isinstance(reviewer, self._reviewer_cls):\n raise TypeError(\"Type of given reviewer isn't acceptable:\", reviewer, ', expected:', self._reviewer_cls)\n elif not isinstance(product, self._product_cls):\n raise TypeError(\"Type of given product isn't acceptable:\", product, ', expected:', self._product_cls)\n try:\n return self.graph[reviewer][product]['review']\n except TypeError:\n raise KeyError('{0} does not review {1}.'.format(reviewer, product))\n ", "context": "class BipartiteGraph(object):\n @memoized\n def retrieve_review(self, reviewer, product): ...\n def __init__(self, summary=AverageSummary, alpha=1, credibility=WeightedCredibility, reviewer=Reviewer, product=Product): ...\n def new_reviewer(self, name, anomalous=None): ...\n def new_product(self, name): ...\n def add_review(self, reviewer, product, review, date=None): ...\n def retrieve_products(self, reviewer): ...\n def retrieve_reviewers(self, product): ...\n def update(self): ...\n def _weight_generator(self, reviewers): ...\n def dump_credibilities(self, output): ...\n def to_pydot(self): ...\n\n self.alpha = alpha\n self.graph = nx.DiGraph()\n self.reviewers = []\n self.products = []\n self._summary_cls = summary\n self._review_cls = summary.review_class()\n self.credibility = credibility(self)\n self._reviewer_cls = reviewer\n self._product_cls = product\n", "repository": "rgmining/ria", "test_name": "test_retrieve_review", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000822.py"} {"focal_file": "ria/credibility.py", "focal_class": null, "focal_method": "reviewers", "tests": "import unittest\n\nclass Test_reviewers(unittest.TestCase):\n def test_reviewers(self):\n \"\"\"Test reviewers.\n \"\"\"\n self.assertEqual(set(self.credibility.reviewers(self.products[2])), set(self.reviewers))\n", "method_code": " def reviewers(self, product):\n \"\"\"Find reviewers who have reviewed a given product.\n \n Args:\n product: An instance of :class:`ria.bipartite.Product`.\n \n Returns:\n A list of reviewers who have reviewed the product.\n \"\"\"\n return self._g.retrieve_reviewers(product)\n ", "context": "class GraphBasedCredibility(object):\n def reviewers(self, product): ...\n def __init__(self, g): ...\n def __call__(self, product): ...\n def review_score(self, reviewer, product): ...\n\n self._g = g\n\n __slots__ = '_g'\n", "repository": "rgmining/ria", "test_name": "test_reviewers", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000823.py"} {"focal_file": "ria/credibility.py", "focal_class": null, "focal_method": "review_score", "tests": "import unittest\n\nclass Test_review_score(unittest.TestCase):\n def test_review_score(self):\n \"\"\"Test review_score.\n \"\"\"\n self.assertEqual(self.credibility.review_score(self.reviewers[0], self.products[1]), 0.3)\n", "method_code": " def review_score(self, reviewer, product):\n \"\"\"Find a review score from a given reviewer to a product.\n \n Args:\n reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`.\n product: Product i.e. an instance of :class:`ria.bipartite.Product`.\n \n Returns:\n A review object representing the review from the reviewer to the product.\n \"\"\"\n return self._g.retrieve_review(reviewer, product).score\n ", "context": "class GraphBasedCredibility(object):\n def review_score(self, reviewer, product): ...\n def __init__(self, g): ...\n def __call__(self, product): ...\n def reviewers(self, product): ...\n\n self._g = g\n\n __slots__ = '_g'\n", "repository": "rgmining/ria", "test_name": "test_review_score", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000824.py"} {"focal_file": "ria/one.py", "focal_class": null, "focal_method": "update", "tests": "import unittest\n\nclass Test_update(unittest.TestCase):\n def test_update(self):\n \"\"\"Test update only works once.\n \"\"\"\n self.graph.update()\n self.assertEqual(self.graph.update(), 0)\n", "method_code": " def update(self):\n \"\"\"Update reviewers' anomalous scores and products' summaries.\n \n Returns:\n maximum absolute difference between old summary and new one, and\n old anomalous score and new one.\n \"\"\"\n if self.updated:\n return 0\n res = super(BipartiteGraph, self).update()\n self.updated = True\n return res\n ", "context": "class BipartiteGraph(bipartite.BipartiteGraph):\n def update(self): ...\n def __init__(self, **kwargs): ...\n\n self.updated = False\n", "repository": "rgmining/ria", "test_name": "test_update", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000825.py"} {"focal_file": "neoCL.extension/neoCL.tab/pyRevit Scripts (non-neoCL).panel/smartalign.stack/Lib/smartalign/core.py", "focal_class": null, "focal_method": "sort_points", "tests": "import unittest\n\nclass Test_sort_points(unittest.TestCase):\n def test_sort_points_x(self):\n points = deepcopy(self.p_col)\n points.sort_points('X')\n x_values = [pt.X for pt in points]\n self.assertEqual(x_values, [2, 4, 6])\n\n def test_sort_points_y(self):\n points = deepcopy(self.p_col)\n points.sort_points('Y')\n y_values = [pt.Y for pt in points]\n self.assertEqual(y_values, [1, 2, 6])\n", "method_code": " def sort_points(self, align_axis):\n sorted_points = self.points\n sorted_points.sort(key=lambda p: getattr(p, align_axis))\n self.points = sorted_points\n ", "context": "class PointCollection(object):\n def sort_points(self, align_axis): ...\n def __init__(self, *points): ...\n def __iter__(self): ...\n def average(self): ...\n def max(self): ...\n def min(self): ...\n def __len__(self): ...\n def __repr__(self): ...\n\n self.points = list(points)\n", "repository": "0neo/pyRevit.neoCL", "test_name": "test_sort_points_x", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000826.py"} {"focal_file": "templatelayer/template_layout.py", "focal_class": null, "focal_method": "_parse_and_validate", "tests": "import unittest\n\nclass Test_parse_and_validate(unittest.TestCase):\n def test_parse_and_validate(self):\n tl = self._get_basic_object()\n lc = json.loads(_TEST_GOOD_LAYOUT_CONFIG)\n actual = tl._parse_and_validate(lc)\n expected = {'bottom-center': templatelayer.template_layout._PLACEHOLDER(name='bottom-center', top=200, left=0, height=100, width=100), 'top-right': templatelayer.template_layout._PLACEHOLDER(name='top-right', top=0, left=50, height=100, width=50), 'top-left': templatelayer.template_layout._PLACEHOLDER(name='top-left', top=0, left=0, height=100, width=50), 'middle-center': templatelayer.template_layout._PLACEHOLDER(name='middle-center', top=100, left=0, height=100, width=100)}\n self.assertEquals(actual, expected)\n", "method_code": " def _parse_and_validate(self, layout):\n \"\"\"Process the whole config.\"\"\"\n placeholders = layout.get('placeholders')\n assert issubclass(placeholders.__class__, dict) is True, \"Layout config must have 'placeholders' dictionary/object.\"\n assert placeholders, 'At least one placeholder must be configured.'\n placeholder_configs = {}\n for name, parameters in placeholders.items():\n ph = self._parse_and_validate_placeholder(name, parameters, placeholder_configs)\n placeholder_configs[name] = ph\n return placeholder_configs\n ", "context": "class SimpleTemplateLayout(object):\n def _parse_and_validate(self, layout): ...\n def __init__(self, template_im, config): ...\n def _parse_and_validate_placeholder(self, name, parameters, placeholder_configs): ...\n def _assert_no_overlap(self, ph, other_ph): ...\n def get_placeholder_config(self, name): ...\n def validate_image_for_placeholder(self, name, im): ...\n def apply_component(self, name, overlay_im): ...\n def apply_components(self, im_mapping): ...\n def supported_placeholder_names(self): ...\n def applied_placeholder_names(self): ...\n def unapplied_placeholder_names(self): ...\n def is_completely_applied(self): ...\n def resource(self): ...\n def placeholder_total_coverage(self): ...\n def is_covered(self): ...\n\n self._placeholder_configs = placeholder_configs\n self._applied_placeholders_s = set()\n self._base_im = template_im\n", "repository": "dsoprea/image_template_overlay_apply", "test_name": "test_parse_and_validate", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000827.py"} {"focal_file": "templatelayer/template_layout.py", "focal_class": null, "focal_method": "_parse_and_validate_placeholder", "tests": "import unittest\n\nclass Test_parse_and_validate_placeholder(unittest.TestCase):\n def test_parse_and_validate_placeholder(self):\n tl = self._get_basic_object()\n parameters = {'left': 0, 'top': 0, 'width': 50, 'height': 100}\n placeholder_configs = {}\n actual = tl._parse_and_validate_placeholder('test-placeholder', parameters, placeholder_configs)\n expected = templatelayer.template_layout._PLACEHOLDER(name='test-placeholder', top=0, left=0, height=100, width=50)\n self.assertEquals(actual, expected)\n", "method_code": " def _parse_and_validate_placeholder(self, name, parameters, placeholder_configs):\n \"\"\"Validates and loads a single placeholder definition from the config.\n \"\"\"\n try:\n ph = _PLACEHOLDER(name=name, top=parameters['top'], left=parameters['left'], height=parameters['height'], width=parameters['width'])\n except KeyError:\n _LOGGER.exception('One or more placeholder parameters are missing for [{}].'.format(name))\n raise\n for other_ph in placeholder_configs.values():\n self._assert_no_overlap(ph, other_ph)\n return ph\n ", "context": "class SimpleTemplateLayout(object):\n def _parse_and_validate_placeholder(self, name, parameters, placeholder_configs): ...\n def __init__(self, template_im, config): ...\n def _parse_and_validate(self, layout): ...\n def _assert_no_overlap(self, ph, other_ph): ...\n def get_placeholder_config(self, name): ...\n def validate_image_for_placeholder(self, name, im): ...\n def apply_component(self, name, overlay_im): ...\n def apply_components(self, im_mapping): ...\n def supported_placeholder_names(self): ...\n def applied_placeholder_names(self): ...\n def unapplied_placeholder_names(self): ...\n def is_completely_applied(self): ...\n def resource(self): ...\n def placeholder_total_coverage(self): ...\n def is_covered(self): ...\n\n self._placeholder_configs = placeholder_configs\n self._applied_placeholders_s = set()\n self._base_im = template_im\n", "repository": "dsoprea/image_template_overlay_apply", "test_name": "test_parse_and_validate_placeholder", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000828.py"} {"focal_file": "templatelayer/template_layout.py", "focal_class": null, "focal_method": "_assert_no_overlap", "tests": "import unittest\n\nclass Test_assert_no_overlap(unittest.TestCase):\n def test_assert_no_overlap__ok(self):\n tl = self._get_basic_object()\n ph = templatelayer.template_layout._PLACEHOLDER(name='top-left', top=0, left=0, height=100, width=50)\n other_ph = templatelayer.template_layout._PLACEHOLDER(name='top-right', top=0, left=50, height=100, width=50)\n tl._assert_no_overlap(ph, other_ph)\n\n def test_assert_no_overlap__leftright_overlap_1(self):\n tl = self._get_basic_object()\n ph = templatelayer.template_layout._PLACEHOLDER(name='top-left', top=0, left=0, height=100, width=50)\n other_ph = templatelayer.template_layout._PLACEHOLDER(name='top-right', top=0, left=49, height=100, width=50)\n try:\n tl._assert_no_overlap(ph, other_ph)\n except templatelayer.template_layout.PlaceholderOverlapError as e:\n expected = 'Placeholder [top-left] overlaps with placeholder [top-right].'\n if str(e) != expected:\n raise\n else:\n raise Exception('Expected overlap.')\n\n def test_assert_no_overlap__leftright_overlap_2(self):\n tl = self._get_basic_object()\n ph = templatelayer.template_layout._PLACEHOLDER(name='top-left', top=0, left=0, height=100, width=51)\n other_ph = templatelayer.template_layout._PLACEHOLDER(name='top-right', top=0, left=50, height=100, width=50)\n try:\n tl._assert_no_overlap(ph, other_ph)\n except templatelayer.template_layout.PlaceholderOverlapError as e:\n expected = 'Placeholder [top-left] overlaps with placeholder [top-right].'\n if str(e) != expected:\n raise\n else:\n raise Exception('Expected overlap.')\n\n def test_assert_no_overlap__topbottom_overlap_1(self):\n tl = self._get_basic_object()\n ph = templatelayer.template_layout._PLACEHOLDER(name='middle-center', top=100, left=0, height=100, width=100)\n other_ph = templatelayer.template_layout._PLACEHOLDER(name='bottom-center', top=199, left=0, height=100, width=100)\n try:\n tl._assert_no_overlap(ph, other_ph)\n except templatelayer.template_layout.PlaceholderOverlapError as e:\n expected = 'Placeholder [middle-center] overlaps with placeholder [bottom-center].'\n if str(e) != expected:\n raise\n else:\n raise Exception('Expected overlap.')\n\n def test_assert_no_overlap__topbottom_overlap_2(self):\n tl = self._get_basic_object()\n ph = templatelayer.template_layout._PLACEHOLDER(name='middle-center', top=100, left=0, height=101, width=100)\n other_ph = templatelayer.template_layout._PLACEHOLDER(name='bottom-center', top=200, left=0, height=100, width=100)\n try:\n tl._assert_no_overlap(ph, other_ph)\n except templatelayer.template_layout.PlaceholderOverlapError as e:\n expected = 'Placeholder [middle-center] overlaps with placeholder [bottom-center].'\n if str(e) != expected:\n raise\n else:\n raise Exception('Expected overlap.')\n\n def test_assert_no_overlap__full_overlap(self):\n tl = self._get_basic_object()\n ph = templatelayer.template_layout._PLACEHOLDER(name='small', top=20, left=20, height=20, width=20)\n other_ph = templatelayer.template_layout._PLACEHOLDER(name='big', top=0, left=0, height=100, width=100)\n try:\n tl._assert_no_overlap(ph, other_ph)\n except templatelayer.template_layout.PlaceholderOverlapError as e:\n expected = 'Placeholder [small] overlaps with placeholder [big].'\n if str(e) != expected:\n raise\n else:\n raise Exception('Expected overlap.')\n", "method_code": " def _assert_no_overlap(self, ph, other_ph):\n \"\"\"Make sure the given placeholder-config doesn't overlap with any\n previous placeholder-configurations.\n \"\"\"\n is_in_left_right_boundaries = False\n other_right = other_ph.left + other_ph.width\n left_is_in_range = ph.left >= other_ph.left and ph.left < other_right\n if left_is_in_range is True:\n is_in_left_right_boundaries = True\n right = ph.left + ph.width\n right_is_in_range = right > other_ph.left and right < other_right\n if right_is_in_range is True:\n is_in_left_right_boundaries = True\n is_in_top_bottom_boundaries = False\n other_bottom = other_ph.top + other_ph.height\n top_is_in_range = ph.top >= other_ph.top and ph.top < other_bottom\n if top_is_in_range is True:\n is_in_top_bottom_boundaries = True\n bottom = ph.top + ph.height\n if bottom > other_ph.top and bottom < other_bottom:\n is_in_top_bottom_boundaries = True\n if is_in_left_right_boundaries is True and is_in_top_bottom_boundaries is True:\n raise PlaceholderOverlapError('Placeholder [{}] overlaps with placeholder [{}].'.format(ph.name, other_ph.name))\n ", "context": "class SimpleTemplateLayout(object):\n def _assert_no_overlap(self, ph, other_ph): ...\n def __init__(self, template_im, config): ...\n def _parse_and_validate(self, layout): ...\n def _parse_and_validate_placeholder(self, name, parameters, placeholder_configs): ...\n def get_placeholder_config(self, name): ...\n def validate_image_for_placeholder(self, name, im): ...\n def apply_component(self, name, overlay_im): ...\n def apply_components(self, im_mapping): ...\n def supported_placeholder_names(self): ...\n def applied_placeholder_names(self): ...\n def unapplied_placeholder_names(self): ...\n def is_completely_applied(self): ...\n def resource(self): ...\n def placeholder_total_coverage(self): ...\n def is_covered(self): ...\n\n self._placeholder_configs = placeholder_configs\n self._applied_placeholders_s = set()\n self._base_im = template_im\n", "repository": "dsoprea/image_template_overlay_apply", "test_name": "test_assert_no_overlap__ok", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000829.py"} {"focal_file": "templatelayer/template_layout.py", "focal_class": null, "focal_method": "get_placeholder_config", "tests": "import unittest\n\nclass Test_get_placeholder_config(unittest.TestCase):\n def test_get_placeholder_config__known(self):\n tl = self._get_basic_object()\n actual = {}\n for name in sorted(tl.supported_placeholder_names):\n ph = tl.get_placeholder_config(name)\n actual[ph.name] = ph\n expected = {'bottom-center': templatelayer.template_layout._PLACEHOLDER(name='bottom-center', top=200, left=0, height=100, width=100), 'top-right': templatelayer.template_layout._PLACEHOLDER(name='top-right', top=0, left=50, height=100, width=50), 'top-left': templatelayer.template_layout._PLACEHOLDER(name='top-left', top=0, left=0, height=100, width=50), 'middle-center': templatelayer.template_layout._PLACEHOLDER(name='middle-center', top=100, left=0, height=100, width=100)}\n self.assertEquals(actual, expected)\n\n def test_get_placeholder_config__unknown(self):\n tl = self._get_basic_object()\n try:\n tl.get_placeholder_config('unknown-placeholder')\n except templatelayer.template_layout.UnknownPlaceholderException:\n pass\n else:\n raise Exception('Expected exception for unknown placeholder.')\n", "method_code": " def get_placeholder_config(self, name):\n \"\"\"Retrieved a single placeholder config.\"\"\"\n try:\n return self._placeholder_configs[name]\n except KeyError:\n pass\n raise UnknownPlaceholderException(name)\n ", "context": "class SimpleTemplateLayout(object):\n def get_placeholder_config(self, name): ...\n def __init__(self, template_im, config): ...\n def _parse_and_validate(self, layout): ...\n def _parse_and_validate_placeholder(self, name, parameters, placeholder_configs): ...\n def _assert_no_overlap(self, ph, other_ph): ...\n def validate_image_for_placeholder(self, name, im): ...\n def apply_component(self, name, overlay_im): ...\n def apply_components(self, im_mapping): ...\n def supported_placeholder_names(self): ...\n def applied_placeholder_names(self): ...\n def unapplied_placeholder_names(self): ...\n def is_completely_applied(self): ...\n def resource(self): ...\n def placeholder_total_coverage(self): ...\n def is_covered(self): ...\n\n self._placeholder_configs = placeholder_configs\n self._applied_placeholders_s = set()\n self._base_im = template_im\n", "repository": "dsoprea/image_template_overlay_apply", "test_name": "test_get_placeholder_config__known", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000830.py"} {"focal_file": "templatelayer/template_layout.py", "focal_class": null, "focal_method": "validate_image_for_placeholder", "tests": "import unittest\n\nclass Test_validate_image_for_placeholder(unittest.TestCase):\n def test_validate_image_for_placeholder(self):\n tl = self._get_basic_object()\n for name in tl.supported_placeholder_names:\n ph = tl.get_placeholder_config(name)\n placeholder_im = templatelayer.testing_common.get_new_image(ph.width, ph.height)\n tl.validate_image_for_placeholder(name, placeholder_im)\n", "method_code": " def validate_image_for_placeholder(self, name, im):\n \"\"\"Check whether the given image is compatible with the given\n placeholder.\n \"\"\"\n config = self.get_placeholder_config(name)\n if config.width != im.width or config.height != im.height:\n raise PlaceholderNotCompatibleException('Image with size ({}, {}) not compatible with placeholder [{}] size ({}, {}).'.format(im.width, im.height, config.width, config.height))\n return config\n ", "context": "class SimpleTemplateLayout(object):\n def validate_image_for_placeholder(self, name, im): ...\n def __init__(self, template_im, config): ...\n def _parse_and_validate(self, layout): ...\n def _parse_and_validate_placeholder(self, name, parameters, placeholder_configs): ...\n def _assert_no_overlap(self, ph, other_ph): ...\n def get_placeholder_config(self, name): ...\n def apply_component(self, name, overlay_im): ...\n def apply_components(self, im_mapping): ...\n def supported_placeholder_names(self): ...\n def applied_placeholder_names(self): ...\n def unapplied_placeholder_names(self): ...\n def is_completely_applied(self): ...\n def resource(self): ...\n def placeholder_total_coverage(self): ...\n def is_covered(self): ...\n\n self._placeholder_configs = placeholder_configs\n self._applied_placeholders_s = set()\n self._base_im = template_im\n", "repository": "dsoprea/image_template_overlay_apply", "test_name": "test_validate_image_for_placeholder", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000831.py"} {"focal_file": "templatelayer/template_layout.py", "focal_class": null, "focal_method": "apply_component", "tests": "import unittest\n\nclass Test_apply_component(unittest.TestCase):\n def test_apply_component__one(self):\n tl = self._get_basic_object()\n ph = tl.get_placeholder_config('bottom-center')\n placeholder_im = templatelayer.testing_common.get_new_image(ph.width, ph.height)\n tl.apply_component(ph.name, placeholder_im)\n self.assertFalse(tl.is_completely_applied)\n expected_supported_placeholder_names = sorted(['bottom-center', 'middle-center', 'top-left', 'top-right'])\n self.assertEquals(sorted(tl.supported_placeholder_names), expected_supported_placeholder_names)\n expected_applied_placeholder_names = sorted(['bottom-center'])\n self.assertEquals(sorted(tl.applied_placeholder_names), expected_applied_placeholder_names)\n expected_unapplied_placeholder_names = sorted(['middle-center', 'top-left', 'top-right'])\n self.assertEquals(sorted(tl.unapplied_placeholder_names), expected_unapplied_placeholder_names)\n\n def test_apply_component__multiple_some(self):\n tl = self._get_basic_object()\n ph = tl.get_placeholder_config('bottom-center')\n placeholder_im = templatelayer.testing_common.get_new_image(ph.width, ph.height)\n tl.apply_component(ph.name, placeholder_im)\n ph = tl.get_placeholder_config('middle-center')\n placeholder_im = templatelayer.testing_common.get_new_image(ph.width, ph.height)\n tl.apply_component(ph.name, placeholder_im)\n self.assertFalse(tl.is_completely_applied)\n expected_supported_placeholder_names = sorted(['bottom-center', 'middle-center', 'top-left', 'top-right'])\n self.assertEquals(sorted(tl.supported_placeholder_names), expected_supported_placeholder_names)\n expected_applied_placeholder_names = sorted(['bottom-center', 'middle-center'])\n self.assertEquals(sorted(tl.applied_placeholder_names), expected_applied_placeholder_names)\n expected_unapplied_placeholder_names = sorted(['top-left', 'top-right'])\n self.assertEquals(sorted(tl.unapplied_placeholder_names), expected_unapplied_placeholder_names)\n\n def test_apply_component__multiple_all(self):\n tl = self._get_basic_object()\n for name in tl.supported_placeholder_names:\n ph = tl.get_placeholder_config(name)\n placeholder_im = templatelayer.testing_common.get_new_image(ph.width, ph.height)\n tl.apply_component(name, placeholder_im)\n self.assertTrue(tl.is_completely_applied)\n expected_supported_placeholder_names = sorted(['bottom-center', 'middle-center', 'top-left', 'top-right'])\n self.assertEquals(sorted(tl.supported_placeholder_names), expected_supported_placeholder_names)\n self.assertEquals(sorted(tl.applied_placeholder_names), expected_supported_placeholder_names)\n self.assertEquals(tl.unapplied_placeholder_names, [])\n\n def test_apply_component__unknown_placeholder(self):\n tl = self._get_basic_object()\n try:\n tl.apply_component('unknown-placehodler', None)\n except templatelayer.template_layout.UnknownPlaceholderException:\n pass\n else:\n raise Exception('Expected exception for unknown placeholder.')\n", "method_code": " def apply_component(self, name, overlay_im):\n \"\"\"Overlay the given image to the specific configured area of the\n placeholder.\n \"\"\"\n assert name not in self._applied_placeholders_s, 'Placeholder name not unique: [{}]'.format(name)\n config = self.validate_image_for_placeholder(name, overlay_im)\n offset = (config.left, config.top)\n self._base_im.paste(overlay_im, offset)\n self._applied_placeholders_s.add(name)\n ", "context": "class SimpleTemplateLayout(object):\n def apply_component(self, name, overlay_im): ...\n def __init__(self, template_im, config): ...\n def _parse_and_validate(self, layout): ...\n def _parse_and_validate_placeholder(self, name, parameters, placeholder_configs): ...\n def _assert_no_overlap(self, ph, other_ph): ...\n def get_placeholder_config(self, name): ...\n def validate_image_for_placeholder(self, name, im): ...\n def apply_components(self, im_mapping): ...\n def supported_placeholder_names(self): ...\n def applied_placeholder_names(self): ...\n def unapplied_placeholder_names(self): ...\n def is_completely_applied(self): ...\n def resource(self): ...\n def placeholder_total_coverage(self): ...\n def is_covered(self): ...\n\n self._placeholder_configs = placeholder_configs\n self._applied_placeholders_s = set()\n self._base_im = template_im\n", "repository": "dsoprea/image_template_overlay_apply", "test_name": "test_apply_component__one", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000832.py"} {"focal_file": "importance_sampling/models.py", "focal_class": null, "focal_method": "wide_resnet", "tests": "import unittest\n\nclass Test_wide_resnet(unittest.TestCase):\n def test_wide_resnet(self):\n self._test_model(wide_resnet(28, 2)((32, 32, 3), 10), (32, 32, 3), (10,))\n self._test_model(wide_resnet(18, 5)((32, 32, 3), 10), (32, 32, 3), (10,))\n", "method_code": "def wide_resnet(L, k, drop_rate=0.0):\n \"\"\"Implement the WRN-L-k from 'Wide Residual Networks' BMVC 2016\"\"\"\n\n def wide_resnet_impl(input_shape, output_size):\n\n def conv(channels, strides, params=dict(padding='same', use_bias=False, kernel_regularizer=l2(0.0005))):\n\n def inner(x):\n x = LayerNormalization()(x)\n x = Activation('relu')(x)\n x = Convolution2D(channels, 3, strides=strides, **params)(x)\n x = Dropout(drop_rate)(x) if drop_rate > 0 else x\n x = LayerNormalization()(x)\n x = Activation('relu')(x)\n x = Convolution2D(channels, 3, **params)(x)\n return x\n return inner\n\n def resize(x, shape):\n if K.int_shape(x) == shape:\n return x\n channels = shape[3 if K.image_data_format() == 'channels_last' else 1]\n strides = K.int_shape(x)[2] // shape[2]\n return Convolution2D(channels, 1, padding='same', use_bias=False, strides=strides)(x)\n\n def block(channels, k, n, strides):\n\n def inner(x):\n for i in range(n):\n x2 = conv(channels * k, strides if i == 0 else 1)(x)\n x = add([resize(x, K.int_shape(x2)), x2])\n return x\n return inner\n n = int((L - 4) / 6)\n group0 = Convolution2D(16, 3, padding='same', use_bias=False, kernel_regularizer=l2(0.0005))\n group1 = block(16, k, n, 1)\n group2 = block(32, k, n, 2)\n group3 = block(64, k, n, 2)\n x_in = x = Input(shape=input_shape)\n x = group0(x)\n x = group1(x)\n x = group2(x)\n x = group3(x)\n x = LayerNormalization()(x)\n x = Activation('relu')(x)\n x = GlobalAveragePooling2D()(x)\n x = Dense(output_size, kernel_regularizer=l2(0.0005))(x)\n y = Activation('softmax')(x)\n model = Model(inputs=x_in, outputs=y)\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n return wide_resnet_impl", "context": "def wide_resnet(L, k, drop_rate=0.0): ...\ndef build_small_nn(input_shape, output_size): ...\ndef build_svrg_nn(input_shape, output_size): ...\ndef build_cnn(input_shape, output_size): ...\ndef build_small_cnn(input_shape, output_size): ...\ndef build_lr(input_shape, output_size): ...\ndef build_all_conv_nn(input_shape, output_size): ...\ndef build_elu_cnn(input_shape, output_size): ...\ndef build_lstm_lm(input_shape, output_size): ...\ndef build_lstm_lm2(input_shape, output_size): ...\ndef build_lstm_lm3(input_shape, output_size): ...\ndef build_lstm_timit(input_shape, output_size): ...\ndef build_lstm_mnist(input_shape, output_size): ...\ndef build_small_cnn_squared(input_shape, output_size): ...\ndef wide_resnet(L, k, drop_rate=0.0): ...\ndef pretrained(Net, weights='imagenet'): ...\ndef face(modelf, embedding): ...\ndef triplet(modelf): ...\ndef get(name): ...\n", "repository": "idiap/importance-sampling", "test_name": "test_wide_resnet", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000833.py"} {"focal_file": "importance_sampling/training.py", "focal_class": "ApproximateImportanceTraining", "focal_method": "fit_generator", "tests": "import unittest\n\nclass Test_ApproximateImportanceTraining_fit_generator(unittest.TestCase):\n def test_generator_training(self):\n\n def gen():\n while True:\n yield (np.random.rand(16, 2), np.random.rand(16, 2))\n\n def gen2():\n while True:\n yield ((np.random.rand(16, 10), np.random.rand(16, 10)), np.random.rand(16, 1))\n x_val1, y_val1 = (np.random.rand(32, 2), np.random.rand(32, 2))\n x_val2, y_val2 = ((np.random.rand(32, 10), np.random.rand(32, 10)), np.random.rand(32, 1))\n for Training in [ImportanceTraining]:\n model = Training(self.model)\n history = model.fit_generator(gen(), validation_data=(x_val1, y_val1), steps_per_epoch=8, epochs=5)\n self.assertTrue('loss' in history.history)\n self.assertEqual(len(history.history['loss']), 5)\n model = Training(self.model2)\n history = model.fit_generator(gen2(), validation_data=(x_val2, y_val2), steps_per_epoch=8, epochs=5)\n self.assertTrue('loss' in history.history)\n self.assertEqual(len(history.history['loss']), 5)\n self.assertFalse(any(np.isnan(history.history['loss'])))\n with self.assertRaises(NotImplementedError):\n ApproximateImportanceTraining(self.model).fit_generator(gen(), validation_data=(x_val1, y_val1), steps_per_epoch=8, epochs=5)\n", "method_code": " def fit_generator(self, train, steps_per_epoch=None, batch_size=32, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, on_sample=None, on_scores=None):\n \"\"\"Create a GeneratorDataset instance and train the model using\n importance sampling for a given number of epochs.\n \n NOTICE: This method may not be supported by all importance training\n classes and may result in NotImplementedError()\n \n Arguments\n ---------\n train: A generator that returns tuples (inputs, targets)\n steps_per_epoch: int, number of gradient updates before considering\n an epoch has passed\n batch_size: int, the number of samples per gradient update (ideally\n set to the number of items returned by the\n generator at each call)\n epochs: int, multiplied by steps_per_epoch denotes the total number\n of gradient updates\n verbose: {0, >0}, whether to use the progress bar Keras callback\n validation_data: generator or tuple (inputs, targets)\n validation_steps: None or int, used only if validation_data is a\n generator\n on_sample: callable that accepts the sampler, idxs, w, scores\n on_scores: callable that accepts the sampler and scores\n \"\"\"\n \n def sequence_gen(seq):\n i = 0\n while True:\n yield seq[i]\n i = (i + 1) % len(seq)\n if validation_data is not None:\n if isinstance(validation_data, (tuple, list)):\n test = validation_data\n test_len = None\n elif isinstance(validation_data, Sequence):\n test = sequence_gen(validation_data)\n test_len = len(validation_data) * batch_size\n else:\n test = validation_data\n test_len = validation_steps * batch_size\n else:\n test = (np.empty(shape=(0, 1)), np.empty(shape=(0, 1)))\n test_len = None\n if isinstance(train, Sequence):\n if steps_per_epoch is None:\n steps_per_epoch = len(train)\n train = sequence_gen(train)\n elif steps_per_epoch is None:\n raise ValueError('steps_per_epoch is not set')\n dataset = GeneratorDataset(train, test, test_len)\n return self.fit_dataset(dataset=dataset, batch_size=batch_size, epochs=epochs, steps_per_epoch=steps_per_epoch, verbose=verbose, callbacks=callbacks, on_sample=on_sample, on_scores=on_scores)\n ", "context": "class _BaseImportanceTraining(object):\n def fit_generator(self, train, steps_per_epoch=None, batch_size=32, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, on_sample=None, on_scores=None): ...\n def __init__(self, model, score='gnorm', layer=None): ...\n def _on_sample(self, event): ...\n def _on_scores(self, scores): ...\n def _check_model(self, model): ...\n def reweighting(self): ...\n def sampler(self, dataset, batch_size, steps_per_epoch, epochs): ...\n def fit(self, x, y, batch_size=32, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, steps_per_epoch=None, on_sample=None, on_scores=None): ...\n def fit_dataset(self, dataset, steps_per_epoch=None, batch_size=32, epochs=1, verbose=1, callbacks=None, on_sample=None, on_scores=None): ...\n def metrics_names(self): ...\n\n self.original_model = model\n self.model = OracleWrapper(model, self.reweighting, score=score, layer=layer)\n", "repository": "idiap/importance-sampling", "test_name": "test_generator_training", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000834.py"} {"focal_file": "runtime/ast.py", "focal_class": "runtime.ast.Conditional", "focal_method": "add", "tests": "import unittest\n\nclass Test_runtime_ast_Conditional_add(unittest.TestCase):\n def test_conditional_node(self):\n \"\"\"Test the conditional node.\"\"\"\n context = env.empty_context()\n bad_conditional = ast.Conditional()\n bad_conditional.add(NULL_LITERAL)\n bad_conditional.add(NULL_LITERAL)\n self.assertRaises(Exception, bad_conditional.eval, context)\n good_conditional = ast.Conditional()\n good_conditional.add(TRUE_LITERAL)\n good_conditional.add(NULL_LITERAL)\n self.assertEqual(good_conditional.eval(context), NULL_LITERAL.value)\n", "method_code": " def add(self, node):\n \"\"\"Adds a leaf to this node.\"\"\"\n self.children.append(node)\n ", "context": "class Node():\n def add(self, node): ...\n def __init__(self): ...\n def tag(self, tag, value=None): ...\n def add_front(self, node): ...\n def describe(self): ...\n def get_str_rep(self, depth): ...\n def __eq__(self, other): ...\n def __str__(self): ...\n def tree_to_string(self, root=0): ...\n\n self.children = []\n self.tags = {}\n\n name = 'base_node'\n", "repository": "lnsp/tea-python", "test_name": "test_conditional_node", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000835.py"} {"focal_file": "runtime/ast.py", "focal_class": "runtime.ast.Conditional", "focal_method": "eval", "tests": "import unittest\n\nclass Test_runtime_ast_Conditional_eval(unittest.TestCase):\n def test_branch_node(self):\n \"\"\"Test the branch node.\"\"\"\n context = env.empty_context()\n true_cond = ast.Conditional()\n true_cond.children = [TRUE_LITERAL, STRING_LITERAL]\n false_cond = ast.Conditional()\n false_cond.children = [FALSE_LITERAL, NULL_LITERAL]\n if_branch = ast.Branch()\n if_branch.children = [true_cond, NULL_LITERAL]\n self.assertEqual(if_branch.eval(context), STRING_LITERAL.value)\n ifelse_branch = ast.Branch()\n ifelse_branch.children = [false_cond, STRING_LITERAL]\n self.assertEqual(ifelse_branch.eval(context), STRING_LITERAL.value)\n ifelifelse_branch = ast.Branch()\n ifelifelse_branch.children = [false_cond, true_cond, NULL_LITERAL]\n self.assertEqual(ifelifelse_branch.eval(context), STRING_LITERAL.value)\n", "method_code": " def eval(self, context):\n \"\"\"Evaluate a sequence of statements.\"\"\"\n parent = None\n try:\n if self.substitute:\n parent = context.substitute()\n except:\n pass\n context.behaviour = DEFAULT_BEHAVIOUR\n value = env.Value(env.NULL)\n for item in self.children:\n value = item.eval(context)\n if context.behaviour is not DEFAULT_BEHAVIOUR:\n break\n if parent is not None:\n context.namespace = parent\n return value\n ", "context": "class Sequence(Node):\n def eval(self, context): ...\n def __init__(self, substitute=False): ...\n def __eq__(self, other): ...\n\n self.substitute = substitute\n\n name = 'sequence'\n", "repository": "lnsp/tea-python", "test_name": "test_branch_node", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000836.py"} {"focal_file": "runtime/ast.py", "focal_class": "runtime.ast.Break", "focal_method": "eval", "tests": "import unittest\n\nclass Test_runtime_ast_Break_eval(unittest.TestCase):\n def test_loop_node(self):\n \"\"\"Test the loop node.\"\"\"\n break_node = ast.Break()\n return_node = ast.Return()\n return_node.children = [TRUE_LITERAL]\n context = env.empty_context()\n bad_loop = ast.Loop()\n bad_loop.children = [NULL_LITERAL, TRUE_LITERAL]\n self.assertRaises(Exception, bad_loop.eval, context)\n break_loop = ast.Loop()\n break_loop.children = [TRUE_LITERAL, break_node]\n self.assertEqual(break_loop.eval(context), NULL_LITERAL.value)\n self.assertEqual(context.behaviour, ast.DEFAULT_BEHAVIOUR)\n return_loop = ast.Loop()\n return_loop.children = [TRUE_LITERAL, return_node]\n self.assertEqual(return_loop.eval(context), TRUE_LITERAL.value)\n self.assertEqual(context.behaviour, ast.RETURN_BEHAVIOUR)\n\n def test_break_node(self):\n \"\"\"Test the break node.\"\"\"\n context = env.empty_context()\n break_node = ast.Break()\n self.assertEqual(break_node.eval(context), NULL_LITERAL.value)\n self.assertEqual(context.behaviour, ast.BREAK_BEHAVIOUR)\n", "method_code": " def eval(self, context):\n \"\"\"Evaluate a sequence of statements.\"\"\"\n parent = None\n try:\n if self.substitute:\n parent = context.substitute()\n except:\n pass\n context.behaviour = DEFAULT_BEHAVIOUR\n value = env.Value(env.NULL)\n for item in self.children:\n value = item.eval(context)\n if context.behaviour is not DEFAULT_BEHAVIOUR:\n break\n if parent is not None:\n context.namespace = parent\n return value\n ", "context": "class Sequence(Node):\n def eval(self, context): ...\n def __init__(self, substitute=False): ...\n def __eq__(self, other): ...\n\n self.substitute = substitute\n\n name = 'sequence'\n", "repository": "lnsp/tea-python", "test_name": "test_loop_node", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000837.py"} {"focal_file": "runtime/ast.py", "focal_class": "runtime.ast.Return", "focal_method": "eval", "tests": "import unittest\n\nclass Test_runtime_ast_Return_eval(unittest.TestCase):\n def test_return_node(self):\n \"\"\"Test the return node.\"\"\"\n context = env.empty_context()\n empty_return = ast.Return()\n self.assertEqual(empty_return.eval(context), NULL_LITERAL.value)\n self.assertEqual(context.behaviour, ast.RETURN_BEHAVIOUR)\n context = env.empty_context()\n value_return = ast.Return()\n value_return.add(TRUE_LITERAL)\n self.assertEqual(value_return.eval(context), TRUE_LITERAL.value)\n self.assertEqual(context.behaviour, ast.RETURN_BEHAVIOUR)\n", "method_code": " def eval(self, context):\n \"\"\"Evaluate a sequence of statements.\"\"\"\n parent = None\n try:\n if self.substitute:\n parent = context.substitute()\n except:\n pass\n context.behaviour = DEFAULT_BEHAVIOUR\n value = env.Value(env.NULL)\n for item in self.children:\n value = item.eval(context)\n if context.behaviour is not DEFAULT_BEHAVIOUR:\n break\n if parent is not None:\n context.namespace = parent\n return value\n ", "context": "class Sequence(Node):\n def eval(self, context): ...\n def __init__(self, substitute=False): ...\n def __eq__(self, other): ...\n\n self.substitute = substitute\n\n name = 'sequence'\n", "repository": "lnsp/tea-python", "test_name": "test_return_node", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000838.py"} {"focal_file": "runtime/ast.py", "focal_class": "runtime.ast.Continue", "focal_method": "eval", "tests": "import unittest\n\nclass Test_runtime_ast_Continue_eval(unittest.TestCase):\n def test_continue_node(self):\n \"\"\"Test the continue node.\"\"\"\n context = env.empty_context()\n continue_node = ast.Continue()\n self.assertEqual(continue_node.eval(context), NULL_LITERAL.value)\n self.assertEqual(context.behaviour, ast.CONTINUE_BEHAVIOUR)\n", "method_code": " def eval(self, context):\n \"\"\"Evaluate a sequence of statements.\"\"\"\n parent = None\n try:\n if self.substitute:\n parent = context.substitute()\n except:\n pass\n context.behaviour = DEFAULT_BEHAVIOUR\n value = env.Value(env.NULL)\n for item in self.children:\n value = item.eval(context)\n if context.behaviour is not DEFAULT_BEHAVIOUR:\n break\n if parent is not None:\n context.namespace = parent\n return value\n ", "context": "class Sequence(Node):\n def eval(self, context): ...\n def __init__(self, substitute=False): ...\n def __eq__(self, other): ...\n\n self.substitute = substitute\n\n name = 'sequence'\n", "repository": "lnsp/tea-python", "test_name": "test_continue_node", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000839.py"} {"focal_file": "runtime/ast.py", "focal_class": "runtime.ast.Literal", "focal_method": "eval", "tests": "import unittest\n\nclass Test_runtime_ast_Literal_eval(unittest.TestCase):\n def test_call_node(self):\n \"\"\"Test the function node.\"\"\"\n sum_function = SumNode()\n sgn1 = env.Value(lib.INTEGER, None, 'a')\n sgn2 = env.Value(lib.INTEGER, None, 'b')\n sum_function.children = [ast.Identifier('a'), ast.Identifier('b')]\n context = env.empty_context()\n func = env.Function([env.Signature([sgn1, sgn2], sum_function)], 'my_func')\n context.store(func)\n arg1 = SumNode()\n arg1.children = [ast.Literal(env.Value(lib.INTEGER, 1)), ast.Literal(env.Value(lib.INTEGER, 2))]\n arg2 = SumNode()\n arg2.children = [ast.Literal(env.Value(lib.INTEGER, 3)), ast.Literal(env.Value(lib.INTEGER, 4))]\n call_node = ast.Call('my_func')\n call_node.children = [arg1, arg2]\n self.assertEqual(call_node.eval(context), env.Value(lib.INTEGER, 10))\n bad_node = ast.Call('missing')\n self.assertRaises(Exception, bad_node.eval, context)\n", "method_code": " def eval(self, context):\n \"\"\"Evaluate a sequence of statements.\"\"\"\n parent = None\n try:\n if self.substitute:\n parent = context.substitute()\n except:\n pass\n context.behaviour = DEFAULT_BEHAVIOUR\n value = env.Value(env.NULL)\n for item in self.children:\n value = item.eval(context)\n if context.behaviour is not DEFAULT_BEHAVIOUR:\n break\n if parent is not None:\n context.namespace = parent\n return value\n ", "context": "class Sequence(Node):\n def eval(self, context): ...\n def __init__(self, substitute=False): ...\n def __eq__(self, other): ...\n\n self.substitute = substitute\n\n name = 'sequence'\n", "repository": "lnsp/tea-python", "test_name": "test_call_node", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000840.py"} {"focal_file": "runtime/ast.py", "focal_class": "runtime.ast.Cast", "focal_method": "eval", "tests": "import unittest\n\nclass Test_runtime_ast_Cast_eval(unittest.TestCase):\n def test_cast_node(self):\n \"\"\"Test the cast node.\"\"\"\n context = env.empty_context()\n context.store(lib.INTEGER)\n cast_node = ast.Cast(lib.INTEGER.name)\n cast_node.children = [NULL_LITERAL]\n self.assertEqual(cast_node.eval(context), INT_LITERAL.value)\n bad_node = ast.Cast('missing')\n self.assertRaises(Exception, bad_node.eval, context)\n", "method_code": " def eval(self, context):\n \"\"\"Evaluate a sequence of statements.\"\"\"\n parent = None\n try:\n if self.substitute:\n parent = context.substitute()\n except:\n pass\n context.behaviour = DEFAULT_BEHAVIOUR\n value = env.Value(env.NULL)\n for item in self.children:\n value = item.eval(context)\n if context.behaviour is not DEFAULT_BEHAVIOUR:\n break\n if parent is not None:\n context.namespace = parent\n return value\n ", "context": "class Sequence(Node):\n def eval(self, context): ...\n def __init__(self, substitute=False): ...\n def __eq__(self, other): ...\n\n self.substitute = substitute\n\n name = 'sequence'\n", "repository": "lnsp/tea-python", "test_name": "test_cast_node", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000841.py"} {"focal_file": "runtime/ast.py", "focal_class": null, "focal_method": "syntax_tree", "tests": "import unittest\n\nclass Test_syntax_tree(unittest.TestCase):\n def test_syntax_tree(self):\n \"\"\"Test the syntax_tree method.\"\"\"\n syntax_tree = ast.syntax_tree()\n self.assertTrue(syntax_tree is not None)\n self.assertEqual(syntax_tree.name, ast.Sequence.name)\n", "method_code": "def syntax_tree():\n \"\"\"Initialize a default syntax tree.\"\"\"\n return Sequence()", "context": "def syntax_tree(): ...\ndef run_in_substitution(node, context): ...\ndef syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_syntax_tree", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000842.py"} {"focal_file": "runtime/ast.py", "focal_class": null, "focal_method": "run_in_substitution", "tests": "import unittest\n\nclass Test_run_in_substitution(unittest.TestCase):\n def test_run_in_substitution(self):\n \"\"\"Test the run_in_substitution method.\"\"\"\n context = env.empty_context()\n access_node = AccessNode()\n result = ast.run_in_substitution(access_node, context)\n self.assertEqual(result, STRING_LITERAL.value)\n self.assertRaises(Exception, context.find, 'id', STRING_LITERAL.value.name)\n", "method_code": "def run_in_substitution(node, context):\n \"\"\"Run the node in a subtituted namespace.\"\"\"\n parent = context.substitute()\n result = node.eval(context)\n context.namespace = parent\n return result", "context": "def run_in_substitution(node, context): ...\ndef run_in_substitution(node, context): ...\ndef syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_run_in_substitution", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000843.py"} {"focal_file": "runtime/env.py", "focal_class": "runtime.env.Namespace", "focal_method": "find", "tests": "import unittest\n\nclass Test_runtime_env_Namespace_find(unittest.TestCase):\n def test_namespace(self):\n \"\"\"Test the Namespace class.\"\"\"\n namespace = env.Namespace(None)\n self.assertEqual(namespace.parent, None)\n self.assertRaises(env.NamespaceException, namespace.find, 'id', 'identifier')\n self.assertRaises(env.NamespaceException, namespace.find, 'op', 'operator')\n namespace.store(STRING_VALUE)\n namespace.store(USELESS_OPERATOR)\n self.assertEqual(namespace.find('id', STRING_VALUE.name), STRING_VALUE)\n self.assertEqual(namespace.find('op', USELESS_OPERATOR.symbol), USELESS_OPERATOR)\n sub = namespace.child()\n self.assertEqual(namespace.find('id', STRING_VALUE.name), STRING_VALUE)\n self.assertEqual(namespace.find('op', USELESS_OPERATOR.symbol), USELESS_OPERATOR)\n sub.store(MISSING_INT_VALUE)\n sub.store(ANOTHER_USELESS_OPERATOR)\n self.assertRaises(env.NamespaceException, namespace.find, 'id', MISSING_INT_VALUE.name)\n self.assertRaises(env.NamespaceException, namespace.find, 'op', ANOTHER_USELESS_OPERATOR.symbol)\n\n def test_context(self):\n \"\"\"Test the Context class.\"\"\"\n namespace = env.Namespace(None)\n context = env.Context(namespace)\n context.store(INT_VALUE)\n self.assertEqual(context.find('id', INT_VALUE.name), INT_VALUE)\n self.assertRaises(env.NamespaceException, context.find, 'id', STRING_VALUE.name)\n custom_library = LIBRARY(EXPORTS=[STRING_VALUE])\n context.load(custom_library)\n self.assertEqual(context.find('id', STRING_VALUE.name), STRING_VALUE)\n self.assertIs(context.substitute(), namespace)\n self.assertIsNot(context.namespace, namespace)\n", "method_code": " def find(self, space, key):\n \"\"\"Search for an element in this and higher order namespaces.\"\"\"\n if key in self.search_spaces[space]:\n return self.search_spaces[space][key]\n if self.parent is not None:\n return self.parent.find(space, key)\n raise NamespaceException(key)\n ", "context": "class Namespace():\n def find(self, space, key): ...\n def __init__(self, parent): ...\n def store(self, item): ...\n def store_all(self, items): ...\n def child(self): ...\n def __str__(self): ...\n\n self.parent = parent\n self.search_spaces = {'id': {}, 'op': {}, 'ty': {}}\n", "repository": "lnsp/tea-python", "test_name": "test_namespace", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000844.py"} {"focal_file": "runtime/env.py", "focal_class": "runtime.env.Operator", "focal_method": "eval", "tests": "import unittest\n\nclass Test_runtime_env_Operator_eval(unittest.TestCase):\n def test_operator(self):\n \"\"\"Test the operator class.\"\"\"\n context = env.empty_context()\n int_literal = ast.Literal(INT_VALUE)\n func = env.Function([env.Signature([], int_literal)])\n operator = env.Operator(func, '+')\n self.assertEqual(str(operator), '')\n self.assertEqual(operator.eval([], context), INT_VALUE)\n", "method_code": " def eval(self, args, context):\n \"\"\"Searches for a matching signature and evaluates the function node.\"\"\"\n for sgn in self.signatures:\n try:\n values, fnc = sgn.match(args)\n original, context.namespace = (context.namespace, Namespace(self.source_ns))\n context.namespace.store_all(values)\n result = fnc.eval(context)\n context.namespace = original\n return result\n except (ArgumentException, ArgumentCastException):\n pass\n raise FunctionException(self)\n ", "context": "class Function(object):\n def eval(self, args, context): ...\n def __init__(self, signatures, name=None, source_ns=None): ...\n def format(self): ...\n def __str__(self): ...\n\n self.signatures = signatures\n self.name = name\n self.source_ns = source_ns\n", "repository": "lnsp/tea-python", "test_name": "test_operator", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000845.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "is_assignment", "tests": "import unittest\n\nclass Test_is_assignment(unittest.TestCase):\n def test_is_assignment(self):\n cases = [(asgn_token, True), (asgnadd_token, True), (asgnsub_token, True), (asgnmul_token, True), (asgndiv_token, True), (asgnmod_token, True), (asgnpow_token, True), (None, False), (number_token, False)]\n for tc in cases:\n self.assertEqual(is_assignment(tc[0]), tc[1], '%s mistakingly reported as assignment' % str(tc[0]))\n", "method_code": "def is_assignment(token):\n return token != None and token.kind is lexer.OPERATOR and (token.value in ['=', '+=', '-=', '*=', '/=', '%=', '^='])", "context": "def is_assignment(token): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_is_assignment", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000846.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "find_matching_block", "tests": "import unittest\n\nclass Test_find_matching_block(unittest.TestCase):\n def test_matching_block(self):\n cases = [(clean_lex('{}'), 1), (clean_lex('{'), -1), (clean_lex('}'), -1), (clean_lex('{{}'), -1), (clean_lex('{{}}'), 3), (clean_lex('{ 123; }'), 3)]\n for tc in cases:\n self.assertEqual(find_matching_block(tc[0], 1), tc[1])\n", "method_code": "def find_matching_block(stream, start):\n level = 1\n max = len(stream)\n for i in range(start, max):\n if stream[i].kind == lexer.LBLOCK:\n level += 1\n elif stream[i].kind == lexer.RBLOCK:\n level -= 1\n if level == 0:\n return i\n return -1", "context": "def find_matching_block(stream, start): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_matching_block", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000847.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "find_matching_prt", "tests": "import unittest\n\nclass Test_find_matching_prt(unittest.TestCase):\n def test_matching_prt(self):\n cases = [(clean_lex('()'), 1), (clean_lex('('), -1), (clean_lex(')'), -1), (clean_lex('(()'), -1), (clean_lex('(123)'), 2), (clean_lex('(12 12)'), 3)]\n for tc in cases:\n self.assertEqual(find_matching_prt(tc[0], 1), tc[1])\n", "method_code": "def find_matching_prt(stream, start):\n level = 1\n max = len(stream)\n for i in range(start, max):\n if flags.debug:\n print('scanned', str(stream[i]), ':', level)\n if stream[i].kind == lexer.LPRT:\n level += 1\n elif stream[i].kind == lexer.RPRT:\n level -= 1\n if level == 0:\n return i\n return -1", "context": "def find_matching_prt(stream, start): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_matching_prt", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000848.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "get_arg_count", "tests": "import unittest\n\nclass Test_get_arg_count(unittest.TestCase):\n def test_arg_count(self):\n cases = [(plus_token, value_tokens, 2), (plus_token, operation_tokens, 1), (minus_token, value_tokens, 2), (minus_token, operation_tokens, 1), (neg_token, value_tokens, 1), (neg_token, operation_tokens, 1), (and_token, all_tokens, 2), (or_token, all_tokens, 2), (xor_token, all_tokens, 2), (equal_token, all_tokens, 2), (unequal_token, all_tokens, 2), (smaller_token, all_tokens, 2), (larger_token, all_tokens, 2), (smequ_token, all_tokens, 2), (lgequ_token, all_tokens, 2), (mod_token, all_tokens, 2), (type_token, all_tokens, 2), (multiply_token, all_tokens, 2), (divide_token, all_tokens, 2), (power_token, all_tokens, 2), (asgn_token, all_tokens, 2), (asgnadd_token, all_tokens, 2), (asgnsub_token, all_tokens, 2), (asgnmul_token, all_tokens, 2), (asgndiv_token, all_tokens, 2), (asgnpow_token, all_tokens, 2), (asgnmod_token, all_tokens, 2)]\n for tc in cases:\n for e in tc[1]:\n self.assertEqual(get_arg_count(tc[0].value, e), tc[2], 'bad operator arg count for %s when tested against %s' % (tc[0].value, e))\n", "method_code": "def get_arg_count(operator, last_token):\n if operator in ['+', '-'] and (last_token == None or last_token.kind not in [lexer.NUMBER, lexer.IDENTIFIER, lexer.STRING, lexer.RPRT]):\n if flags.debug:\n print('unary operator because of', last_token)\n return 1\n elif operator in ['!']:\n return 1\n if flags.debug:\n print('binary because of', last_token)\n return 2", "context": "def get_arg_count(operator, last_token): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_arg_count", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000849.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "get_precedence", "tests": "import unittest\n\nclass Test_get_precedence(unittest.TestCase):\n def test_precedence(self):\n cases = [(neg_token, all_tokens, 7), (plus_token, operation_tokens, 7), (minus_token, operation_tokens, 7), (power_token, all_tokens, 6), (divide_token, all_tokens, 5), (multiply_token, all_tokens, 5), (plus_token, value_tokens, 4), (minus_token, value_tokens, 4), (type_token, all_tokens, 4), (mod_token, all_tokens, 3), (smaller_token, all_tokens, 2), (larger_token, all_tokens, 2), (smequ_token, all_tokens, 2), (lgequ_token, all_tokens, 2), (equal_token, all_tokens, 2), (unequal_token, all_tokens, 2), (and_token, all_tokens, 1), (or_token, all_tokens, 1), (xor_token, all_tokens, 1), (asgn_token, all_tokens, 0), (asgnadd_token, all_tokens, 0), (asgnsub_token, all_tokens, 0), (asgnmul_token, all_tokens, 0), (asgndiv_token, all_tokens, 0), (asgnpow_token, all_tokens, 0), (asgnmod_token, all_tokens, 0)]\n for tc in cases:\n for e in tc[1]:\n self.assertEqual(get_precedence(tc[0].value, e), tc[2], 'bad operator precedence for %s when tested against %s' % (tc[0].value, e))\n", "method_code": "def get_precedence(operator, last_token):\n if operator in ['+', '-'] and (last_token == None or last_token.kind not in [lexer.NUMBER, lexer.IDENTIFIER, lexer.STRING, lexer.RPRT]):\n return 7\n elif operator in ['!']:\n return 7\n elif operator in ['^']:\n return 6\n elif operator in ['*', '/']:\n return 5\n elif operator in ['+', '-', ':']:\n return 4\n elif operator in ['%']:\n return 3\n elif operator in ['<', '>', '<=', '>=', '!=', '==']:\n return 2\n elif operator in ['&&', '||', '^|']:\n return 1\n return 0", "context": "def get_precedence(operator, last_token): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_precedence", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000850.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "is_left_associative", "tests": "import unittest\n\nclass Test_is_left_associative(unittest.TestCase):\n def test_associativity(self):\n cases = [(neg_token, all_tokens, False), (plus_token, operation_tokens, False), (minus_token, operation_tokens, False), (power_token, all_tokens, False), (divide_token, all_tokens, True), (multiply_token, all_tokens, True), (plus_token, value_tokens, True), (minus_token, value_tokens, True), (type_token, all_tokens, True), (mod_token, all_tokens, True), (smaller_token, all_tokens, True), (larger_token, all_tokens, True), (smequ_token, all_tokens, True), (lgequ_token, all_tokens, True), (equal_token, all_tokens, True), (unequal_token, all_tokens, True), (and_token, all_tokens, True), (or_token, all_tokens, True), (xor_token, all_tokens, True), (asgn_token, all_tokens, True), (asgnadd_token, all_tokens, True), (asgnsub_token, all_tokens, True), (asgnmul_token, all_tokens, True), (asgndiv_token, all_tokens, True), (asgnpow_token, all_tokens, True), (asgnmod_token, all_tokens, True)]\n for tc in cases:\n for e in tc[1]:\n self.assertEqual(is_left_associative(tc[0].value, e), tc[2], 'bad operator associativity for %s when tested against %s' % (tc[0].value, e))\n", "method_code": "def is_left_associative(operator, last_token):\n if operator in ['+', '-'] and (last_token == None or last_token.kind not in [lexer.NUMBER, lexer.IDENTIFIER, lexer.STRING, lexer.RPRT]):\n if flags.debug:\n print('right associative because of', last_token)\n return False\n elif operator in ['!', '^']:\n return False\n if flags.debug:\n print('left associative because of', last_token)\n return True", "context": "def is_left_associative(operator, last_token): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_associativity", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000851.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "generate_declaration", "tests": "import unittest\n\nclass Test_generate_declaration(unittest.TestCase):\n def test_declaration(self):\n case1 = ast.Sequence()\n case1.add(ast.Declaration('a', 'int'))\n case2 = ast.Sequence()\n case2.add(ast.Declaration('a', 'null'))\n case2_assgn = ast.Assignment('a', True)\n case2_assgn.add(ast.Literal(env.Value(env.NULL)))\n case2.add(case2_assgn)\n case3 = ast.Sequence()\n case3.add(ast.Declaration('a', 'int'))\n case3_assgn = ast.Assignment('a', False)\n case3_assgn.add(ast.Literal(env.Value(env.NULL)))\n case3.add(case3_assgn)\n case4 = ast.Sequence()\n case4.add(ast.Declaration('a', 'null'))\n case4.add(ast.Declaration('b', 'null'))\n case4_assgn_a = ast.Assignment('a', True)\n case4_assgn_a.add(ast.Literal(env.Value(env.NULL)))\n case4_assgn_b = ast.Assignment('b', True)\n case4_assgn_b.add(case4_assgn_a)\n case4.add(case4_assgn_b)\n case5 = ast.Sequence()\n case5.add(ast.Declaration('a', 'int'))\n case5.add(ast.Declaration('b', 'int'))\n case5.add(ast.Declaration('c', 'int'))\n case5_assgn_a = ast.Assignment('a', False)\n case5_assgn_a.add(ast.Literal(env.Value(env.NULL)))\n case5_assgn_b = ast.Assignment('b', False)\n case5_assgn_b.add(case5_assgn_a)\n case5_assgn_c = ast.Assignment('c', False)\n case5_assgn_c.add(case5_assgn_b)\n case5.add(case5_assgn_c)\n cases = [('var a: int', case1, 3), ('var a = null', case2, 3), ('var a: int = null', case3, 5), ('var a, b = null', case4, 5), ('var a, b, c: int = null', case5, 9)]\n for tc in cases:\n output, offset = generate_declaration(clean_lex(tc[0]))\n self.assertEqual(output, tc[1], '%s is not equal to %s' % (str(output), str(tc[1])))\n self.assertEqual(offset, tc[2], '%s offset %d is not equal to %d' % (str(output), offset, tc[2]))\n error_cases = [('var a', ParseException), ('var a: null, b: null', ParseException), ('var a: null, b', ParseException)]\n for tc in error_cases:\n tokens = clean_lex(tc[0])\n self.assertRaises(tc[1], generate_declaration, tokens)\n", "method_code": "def generate_declaration(stream):\n if flags.debug:\n print('Starting generating declaration')\n end = len(stream)\n for j in range(len(stream)):\n if stream[j].kind is lexer.STATEMENT:\n end = j\n break\n if end < 3:\n raise ParseException('Declaration too short')\n if not (stream[0].kind is lexer.IDENTIFIER and stream[0].value == 'var'):\n raise InvalidDeclaration(stream[0])\n if stream[1].kind != lexer.IDENTIFIER:\n raise InvalidDeclaration(stream[1])\n declared_names = []\n sequ = ast.Sequence()\n expr_begin = 2\n ignore_type = True\n while expr_begin < end and (stream[expr_begin].kind is lexer.SEPARATOR or (stream[expr_begin].kind is lexer.OPERATOR and (stream[expr_begin].value == ':' or (stream[expr_begin].value == '=' and ignore_type)))):\n if stream[expr_begin].kind is lexer.OPERATOR and stream[expr_begin].value == ':':\n ignore_type = False\n if expr_begin > 2 and stream[expr_begin - 2].kind != lexer.SEPARATOR:\n raise InvalidDeclaration(stream[expr_begin - 2])\n if stream[expr_begin - 1].kind is not lexer.IDENTIFIER:\n raise InvalidDeclaration(stream[expr_begin - 1])\n declared_names.append(stream[expr_begin - 1].value)\n expr_begin += 2\n if not ignore_type and stream[expr_begin - 1].kind is not lexer.IDENTIFIER:\n raise InvalidDeclaration(stream[expr_begin - 1])\n datatype = 'null'\n if not ignore_type:\n datatype = stream[expr_begin - 1].value\n else:\n expr_begin -= 2\n expr = None\n if expr_begin < end and is_assignment(stream[expr_begin]):\n expr, _ = generate_expression(stream[expr_begin + 1:])\n for name in declared_names:\n decl = ast.Declaration(name, datatype)\n sequ.add(decl)\n if expr is not None:\n assgn = ast.Assignment(name, ignore_type)\n assgn.add(expr)\n expr = assgn\n if expr is not None:\n sequ.add(expr)\n return (sequ, end - 1)", "context": "def generate_declaration(stream): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_declaration", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000852.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "generate_assignment", "tests": "import unittest\n\nclass Test_generate_assignment(unittest.TestCase):\n def test_assignment(self):\n case1_assgn = ast.Assignment('a')\n case1_assgn.add(ast.Identifier('a'))\n case1 = case1_assgn\n case2_assgn = ast.Assignment('a')\n case2_assgnadd = ast.Operation('+')\n case2_assgnadd.add(ast.Identifier('a'))\n case2_assgnadd.add(ast.Literal(env.Value(env.NULL)))\n case2_assgn.add(case2_assgnadd)\n case2 = case2_assgn\n case3_assgn = ast.Assignment('a')\n case3_assgnsub = ast.Operation('-')\n case3_assgnsub.add(ast.Identifier('a'))\n case3_assgnsub.add(ast.Literal(env.Value(env.NULL)))\n case3_assgn.add(case3_assgnsub)\n case3 = case3_assgn\n case4_assgn = ast.Assignment('a')\n case4_assgnmul = ast.Operation('*')\n case4_assgnmul.add(ast.Identifier('a'))\n case4_assgnmul.add(ast.Literal(env.Value(env.NULL)))\n case4_assgn.add(case4_assgnmul)\n case4 = case4_assgn\n case5_assgn = ast.Assignment('a')\n case5_assgndiv = ast.Operation('/')\n case5_assgndiv.add(ast.Identifier('a'))\n case5_assgndiv.add(ast.Literal(env.Value(env.NULL)))\n case5_assgn.add(case5_assgndiv)\n case5 = case5_assgn\n case6_assgn = ast.Assignment('a')\n case6_assgnpow = ast.Operation('^')\n case6_assgnpow.add(ast.Identifier('a'))\n case6_assgnpow.add(ast.Literal(env.Value(env.NULL)))\n case6_assgn.add(case6_assgnpow)\n case6 = case6_assgn\n case7_assgn = ast.Assignment('a')\n case7_assgnmod = ast.Operation('%')\n case7_assgnmod.add(ast.Identifier('a'))\n case7_assgnmod.add(ast.Literal(env.Value(env.NULL)))\n case7_assgn.add(case7_assgnmod)\n case7 = case7_assgn\n cases = [('a = a', case1, 2), ('a += null', case2, 2), ('a = a + null', case2, 4), ('a -= null', case3, 2), ('a = a - null', case3, 4), ('a *= null', case4, 2), ('a = a * null', case4, 4), ('a /= null', case5, 2), ('a = a / null', case5, 4), ('a ^= null', case6, 2), ('a = a ^ null', case6, 4)]\n for tc in cases:\n output, offset = generate_assignment(clean_lex(tc[0]))\n self.assertEqual(output, tc[1], '%s is not equal to %s' % (output, tc[1]))\n self.assertEqual(offset, tc[2], '%s offset %d is not equal to %d' % (output, offset, tc[2]))\n error_cases = [('a =', ParseException), ('a', ParseException), ('= 2', ParseException), ('a == 2', ParseException), ('a = = 2', ParseException), ('a ; = 2', ParseException)]\n for tc in error_cases:\n self.assertRaises(tc[1], generate_assignment, clean_lex(tc[0]))\n", "method_code": "def generate_assignment(stream):\n if flags.debug:\n print('Starting generating assigment')\n if len(stream) < 3:\n raise InvalidAssignment()\n name_token, equ_token = (stream[0], stream[1])\n if name_token.kind != lexer.IDENTIFIER or not is_assignment(equ_token):\n raise InvalidAssignment()\n expr, offset = generate_expression(stream[2:])\n if flags.debug:\n print('Expression has offset %d' % offset)\n if len(equ_token.value) != 1:\n operation = ast.Operation(equ_token.value[0])\n operation.add(ast.Identifier(name_token.value))\n operation.add(expr)\n expr = operation\n assgn = ast.Assignment(name_token.value)\n assgn.add(expr)\n if flags.debug:\n print('Assignment has offset %d' % (1 + offset))\n return (assgn, 1 + offset)", "context": "def generate_assignment(stream): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_assignment", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000853.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "generate_if", "tests": "import unittest\n\nclass Test_generate_if(unittest.TestCase):\n def test_if(self):\n case1 = ast.Branch()\n case1_cond = ast.Conditional()\n case1_cond.add(ast.Literal(env.Value(env.NULL)))\n case1_cond.add(ast.Sequence())\n case1.add(case1_cond)\n case2 = ast.Branch()\n case2_cond = ast.Conditional()\n case2_cond.add(ast.Literal(env.Value(env.NULL)))\n case2_cond.add(ast.Sequence())\n case2.add(case2_cond)\n case2.add(ast.Sequence())\n case3 = ast.Branch()\n case3_if = ast.Conditional()\n case3_if.add(ast.Literal(env.Value(env.NULL)))\n case3_if.add(ast.Sequence())\n case3_elif = ast.Branch()\n case3_elif_cond = ast.Conditional()\n case3_elif_cond.add(ast.Literal(env.Value(env.NULL)))\n case3_elif_cond.add(ast.Sequence())\n case3_elif.add(case3_elif_cond)\n case3.add(case3_if)\n case3.add(case3_elif)\n case4 = ast.Branch()\n case4_if = ast.Conditional()\n case4_if.add(ast.Literal(env.Value(env.NULL)))\n case4_if.add(ast.Sequence())\n case4_elif = ast.Branch()\n case4_elif_cond = ast.Conditional()\n case4_elif_cond.add(ast.Literal(env.Value(env.NULL)))\n case4_elif_cond.add(ast.Sequence())\n case4_elif.add(case4_elif_cond)\n case4_elif.add(ast.Sequence())\n case4.add(case4_if)\n case4.add(case4_elif)\n cases = [('if (null) {;}', case1, 6), ('if (null) {;} else {;}', case2, 10), ('if (null) {;}\\xa0else if (null) {;}', case3, 14), ('if (null) {;}\\xa0else if (null) {;}\\xa0else {;}', case4, 18)]\n for tc in cases:\n output, offset = generate_if(clean_lex(tc[0]))\n self.assertEqual(output, tc[1], '%s is not equal to %s' % (output, tc[1]))\n self.assertEqual(offset, tc[2], '%s offset %d is not equal to %d' % (output, offset, tc[2]))\n error_cases = [('if () {}', ParseException), ('if {} else ()', ParseException), ('if () else if {}', ParseException)]\n for tc in error_cases:\n tokens = clean_lex(tc[0])\n self.assertRaises(tc[1], generate_if, tokens)\n", "method_code": "def generate_if(stream):\n if flags.debug:\n print('Starting generating if statement')\n cond_head = stream[0]\n if not (cond_head.kind is lexer.IDENTIFIER and cond_head.value == 'if'):\n raise InvalidCondition()\n cond_start_index = 1\n cond_start = stream[cond_start_index]\n if cond_start.kind != lexer.LPRT:\n raise InvalidCondition()\n cond_end_index = find_matching_prt(stream, cond_start_index + 1)\n if cond_end_index == -1:\n raise InvalidCondition()\n cond_block = stream[cond_start_index + 1:cond_end_index]\n if flags.debug:\n print('if-condition: ' + ' '.join((str(e) for e in cond_block)))\n body_start_index = cond_end_index + 1\n body_start = stream[body_start_index]\n if body_start.kind != lexer.LBLOCK:\n raise InvalidBlock()\n body_end_index = find_matching_block(stream, body_start_index)\n body_block = stream[body_start_index + 1:body_end_index]\n condition, cond_len = generate_expression(cond_block)\n body, body_len = generate_sequence(body_block)\n body.substitute = True\n branch_node = ast.Branch()\n cond_node = ast.Conditional()\n cond_node.add(condition)\n cond_node.add(body)\n branch_node.add(cond_node)\n offset = 4 + cond_len + body_len\n if offset + 1 >= len(stream) or not (stream[offset + 1].kind is lexer.IDENTIFIER and stream[offset + 1].value == 'else'):\n return (branch_node, offset)\n if flags.debug:\n print('Possible else (if) at', str(stream[offset + 1]))\n if stream[offset + 2].kind is lexer.IDENTIFIER and stream[offset + 2].value == 'if':\n if flags.debug:\n print('Parsing else-if at token', offset + 2)\n elif_node, elif_len = generate_if(stream[offset + 2:])\n branch_node.add(elif_node)\n offset += elif_len + 2\n else:\n if flags.debug:\n print('Parsing else at token', offset + 2)\n else_body, else_len = generate_sequence(stream[offset + 3:])\n else_body.substitute = True\n branch_node.add(else_body)\n offset += else_len + 3\n return (branch_node, offset)", "context": "def generate_if(stream): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_if", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000854.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "generate_for", "tests": "import unittest\n\nclass Test_generate_for(unittest.TestCase):\n def test_for(self):\n case1 = ast.Sequence()\n case1_init, _ = generate_declaration(clean_lex('var a: int = 0'))\n case1_init_base = ast.Sequence()\n case1_init_base.add(case1_init)\n case1.add(case1_init_base)\n case1_cond, _ = generate_expression(clean_lex('a < 100'))\n case1_iter, _ = generate_sequence(clean_lex('a += 1'))\n case1_body = ast.Sequence()\n case1_body.add(ast.Sequence())\n case1_body.add(case1_iter)\n case1_loop = ast.Loop()\n case1_loop.add(case1_cond)\n case1_loop.add(case1_body)\n case1.add(case1_loop)\n case2 = ast.Sequence()\n case2_init, _ = generate_assignment(clean_lex('a = 0'))\n case2_init_base = ast.Sequence()\n case2_init_base.add(case2_init)\n case2.add(case2_init_base)\n case2_cond, _ = generate_expression(clean_lex('true'))\n case2_iter = ast.Sequence()\n case2_body = ast.Sequence()\n case2_body.add(ast.Sequence())\n case2_body.add(case2_iter)\n case2_loop = ast.Loop()\n case2_loop.add(case2_cond)\n case2_loop.add(case2_body)\n case2.add(case2_loop)\n case3 = ast.Sequence()\n case3_init = ast.Sequence()\n case3.add(case3_init)\n case3_cond, _ = generate_expression(clean_lex('true'))\n case3_body = ast.Sequence()\n case3_body.add(ast.Sequence())\n case3_body.add(ast.Sequence())\n case3_loop = ast.Loop()\n case3_loop.add(case3_cond)\n case3_loop.add(case3_body)\n case3.add(case3_loop)\n cases = [('for (var a: int = 0; a < 100; a += 1) {;}', case1, 19), ('for (a = 0; true; ) {;}', case2, 11), ('for (; true; ) {;}', case3, 8)]\n for tc in cases:\n output, offset = generate_for(clean_lex(tc[0]))\n self.assertEqual(output, tc[1], '%s is not equal to %s' % (output, tc[1]))\n self.assertEqual(offset, tc[2], '%s offset %d is not equal to %d' % (output, offset, tc[2]))\n error_cases = [('for ; true; a < 100; {;}', ParseException), ('for (true) {;}', ParseException), ('true;', ParseException), ('for {true; ; } (false);', ParseException)]\n for tc in error_cases:\n self.assertRaises(tc[1], generate_for, clean_lex(tc[0]))\n", "method_code": "def generate_for(stream):\n if flags.debug:\n print('Starting generating for statement')\n for_ident = stream[0]\n if not (for_ident.kind is lexer.IDENTIFIER and for_ident.value == 'for'):\n raise InvalidCondition()\n cond_start = 2\n head_start = stream[cond_start - 1]\n if head_start.kind is not lexer.LPRT:\n raise InvalidCondition()\n head_end_index = find_matching_prt(stream, cond_start)\n if head_end_index == -1:\n raise InvalidCondition()\n init_end_index = cond_start\n for j in range(len(stream)):\n if stream[j].kind is lexer.STATEMENT:\n init_end_index = j\n break\n init_stmt, init_len = generate_sequence(stream[cond_start:init_end_index + 1])\n cond_expr, cond_len = generate_expression(stream[cond_start + init_len:head_end_index])\n iter_stmt, iter_len = generate_sequence(stream[cond_start + init_len + cond_len:head_end_index])\n body_start_index = head_end_index + 1\n body_start = stream[body_start_index]\n if body_start.kind is not lexer.LBLOCK:\n raise InvalidBlock()\n body_end_index = find_matching_block(stream, body_start_index + 1)\n body, body_len = generate_sequence(stream[body_start_index + 1:])\n inner_sequ = ast.Sequence()\n inner_sequ.add(body)\n inner_sequ.add(iter_stmt)\n loop = ast.Loop()\n loop.add(cond_expr)\n loop.add(inner_sequ)\n sequ = ast.Sequence(True)\n sequ.add(init_stmt)\n sequ.add(loop)\n return (sequ, 4 + init_len + cond_len + iter_len + body_len)", "context": "def generate_for(stream): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_for", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000855.py"} {"focal_file": "runtime/parser.py", "focal_class": null, "focal_method": "generate_while", "tests": "import unittest\n\nclass Test_generate_while(unittest.TestCase):\n def test_while(self):\n case1 = ast.Loop()\n case1.add(ast.Literal(env.Value(env.NULL)))\n case1.add(ast.Sequence())\n cases = [('while (null) {}', case1, 5), ('while (null) {;}', case1, 6)]\n for tc in cases:\n output, offset = generate_while(clean_lex(tc[0]))\n self.assertEqual(output, tc[1], '%s is not equal to %s' % (output, tc[1]))\n self.assertEqual(offset, tc[2], '%s offset %d is not equal to %d' % (output, offset, tc[2]))\n error_cases = [('while () {}', ParseException), ('while ()', ParseException), ('() {}', ParseException), ('while () {}', ParseException), ('while (false) {', ParseException), ('while ) {}}}', ParseException)]\n for tc in error_cases:\n self.assertRaises(tc[1], generate_while, clean_lex(tc[0]))\n", "method_code": "def generate_while(stream):\n if flags.debug:\n print('Starting generating while statement')\n if len(stream) < 6:\n raise InvalidLoop('length %d' % len(stream))\n if not (stream[0].kind is lexer.IDENTIFIER and stream[0].value == 'while'):\n raise InvalidLoop(stream[0])\n cond_start = stream[1]\n if cond_start.kind != lexer.LPRT:\n raise InvalidCondition()\n cond_end_index = find_matching_prt(stream, 2)\n if cond_end_index == -1:\n raise InvalidCondition()\n body_start_index = cond_end_index + 1\n body_start = stream[body_start_index]\n if body_start.kind != lexer.LBLOCK:\n raise InvalidBlock()\n body_end_index = find_matching_block(stream, body_start_index + 1)\n condition, cond_len = generate_expression(stream[2:cond_end_index])\n body, offset = generate_sequence(stream[body_start_index + 1:])\n body.substitute = True\n loop = ast.Loop()\n loop.add(condition)\n loop.add(body)\n return (loop, 4 + cond_len + offset)", "context": "def generate_while(stream): ...\ndef is_assignment(token): ...\ndef find_matching_block(stream, start): ...\ndef find_matching_prt(stream, start): ...\ndef get_arg_count(operator, last_token): ...\ndef is_left_associative(operator, last_token): ...\ndef get_precedence(operator, last_token): ...\ndef generate_expression(stream): ...\ndef generate_declaration(stream): ...\ndef generate_assignment(stream): ...\ndef generate_function(stream): ...\ndef generate_if(stream): ...\ndef generate_for(stream): ...\ndef generate_while(stream): ...\ndef generate_sequence(stream): ...\ndef optimize_ast(root): ...\ndef generate(tokens): ...\ndef demo_syntax_tree(): ...\n", "repository": "lnsp/tea-python", "test_name": "test_while", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000856.py"} {"focal_file": "module.py", "focal_class": null, "focal_method": "get_formatted_users", "tests": "import unittest\n\nclass Test_get_formatted_users(unittest.TestCase):\n @patch('module.Api.get_users_from_db')\n def test_formatted_users(self, get_users_mock):\n get_users_mock.return_value = ['John']\n api = Api()\n formatted_users = api.get_formatted_users()\n expected_formatted_users = '1: John'\n self.assertEqual(formatted_users, expected_formatted_users)\n", "method_code": " def get_formatted_users(self):\n users = self.get_users_from_db()\n formatted_users = '\\n'.join(('{0}: {1}'.format(i + 1, user) for i, user in enumerate(users)))\n return formatted_users\n ", "context": "class Api():\n def get_formatted_users(self): ...\n def create_user(self, user): ...\n def get_users_from_db(self): ...\n\n _users = []\n", "repository": "alazaro/unittests", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000857.py"} {"focal_file": "src/jarabe/util/downloader.py", "focal_class": "Downloader", "focal_method": "download_to_temp", "tests": "import unittest\n\nclass Test_Downloader_download_to_temp(unittest.TestCase):\n def test_download_to_temp(self):\n downloader = Downloader('http://0.0.0.0:%d/data/test.txt' % self._port)\n self._complete = False\n downloader.connect('complete', self.download_complete_cb)\n downloader.download_to_temp()\n while not self._complete:\n Gtk.main_iteration()\n self.assertIsNone(self._result)\n path = downloader.get_local_file_path()\n text = open(path, 'r').read()\n self.assertEqual('hello\\n', text)\n", "method_code": " def download_to_temp(self):\n \"\"\"\n Download the contents of the provided URL to temporary file storage.\n Use .get_local_file_path() to find the location of where the file\n is saved. Upon completion, a successful download is indicated by a\n result of None in the complete signal parameters.\n \"\"\"\n url = self._uri.to_string(False)\n temp_file_path = self._get_temp_file_path(url)\n self._output_file = Gio.File.new_for_path(temp_file_path)\n self._output_stream = self._output_file.create(Gio.FileCreateFlags.PRIVATE, None)\n self.download_chunked()\n ", "context": "class Downloader(GObject.GObject):\n def download_to_temp(self): ...\n def __init__(self, url, session=None, request_headers=None): ...\n def _setup_message(self, method='GET'): ...\n def download_chunked(self): ...\n def download(self, start=None, end=None): ...\n def get_size(self): ...\n def _message_cb(self, session, message, user_data): ...\n def cancel(self): ...\n def _headers_cb(self, message, user_data): ...\n def _got_chunk_cb(self, message, buf): ...\n def __write_async_cb(self, output_stream, result, user_data): ...\n def _complete(self): ...\n def _check_if_finished(self): ...\n def _write_next_buffer(self): ...\n def _get_temp_file_path(self, uri): ...\n def get_local_file_path(self): ...\n\n self._uri = Soup.URI.new(url)\n self._session = session or get_soup_session()\n self._pending_buffers = []\n self._downloaded_size = 0\n self._total_size = 0\n self._cancelling = False\n self._status_code = None\n self._output_file = None\n self._output_stream = None\n self._message = None\n self._request_headers = request_headers\n\n __gsignals__ = {'progress': (GObject.SignalFlags.RUN_FIRST, None, [float]), 'got-chunk': (GObject.SignalFlags.RUN_FIRST, None, (object,)), 'complete': (GObject.SignalFlags.RUN_FIRST, None, (object,))}\n", "repository": "devAbnull/sugar-prototype", "test_name": "test_download_to_temp", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000858.py"} {"focal_file": "src/jarabe/util/downloader.py", "focal_class": "Downloader", "focal_method": "download", "tests": "import unittest\n\nclass Test_Downloader_download(unittest.TestCase):\n def test_download(self):\n downloader = Downloader('http://0.0.0.0:%d/data/test.txt' % self._port)\n self._complete = False\n downloader.connect('complete', self.download_complete_cb)\n downloader.download()\n while not self._complete:\n Gtk.main_iteration()\n self.assertEqual('hello\\n', self._result.get_data())\n", "method_code": " def download(self, start=None, end=None):\n \"\"\"\n Download the contents of the provided URL into memory.\n Upon completion, the downloaded data will be passed as GBytes to the\n result parameter of the complete signal handler.\n The start and end parameters can optionally be set to perform a\n partial read of the remote data.\n \"\"\"\n self._setup_message()\n if start is not None:\n self._message.request_headers.set_range(start, end)\n self._session.queue_message(self._message, self._message_cb, None)\n ", "context": "class Downloader(GObject.GObject):\n def download(self, start=None, end=None): ...\n def __init__(self, url, session=None, request_headers=None): ...\n def _setup_message(self, method='GET'): ...\n def download_to_temp(self): ...\n def download_chunked(self): ...\n def get_size(self): ...\n def _message_cb(self, session, message, user_data): ...\n def cancel(self): ...\n def _headers_cb(self, message, user_data): ...\n def _got_chunk_cb(self, message, buf): ...\n def __write_async_cb(self, output_stream, result, user_data): ...\n def _complete(self): ...\n def _check_if_finished(self): ...\n def _write_next_buffer(self): ...\n def _get_temp_file_path(self, uri): ...\n def get_local_file_path(self): ...\n\n self._uri = Soup.URI.new(url)\n self._session = session or get_soup_session()\n self._pending_buffers = []\n self._downloaded_size = 0\n self._total_size = 0\n self._cancelling = False\n self._status_code = None\n self._output_file = None\n self._output_stream = None\n self._message = None\n self._request_headers = request_headers\n\n __gsignals__ = {'progress': (GObject.SignalFlags.RUN_FIRST, None, [float]), 'got-chunk': (GObject.SignalFlags.RUN_FIRST, None, (object,)), 'complete': (GObject.SignalFlags.RUN_FIRST, None, (object,))}\n", "repository": "devAbnull/sugar-prototype", "test_name": "test_download", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000859.py"} {"focal_file": "src/jarabe/util/downloader.py", "focal_class": "Downloader", "focal_method": "get_size", "tests": "import unittest\n\nclass Test_Downloader_get_size(unittest.TestCase):\n def test_get_size(self):\n downloader = Downloader('http://0.0.0.0:%d/data/test.txt' % self._port)\n self._complete = False\n downloader.connect('complete', self.download_complete_cb)\n downloader.get_size()\n while not self._complete:\n Gtk.main_iteration()\n self.assertEqual(6, self._result)\n", "method_code": " def get_size(self):\n \"\"\"\n Perform a HTTP HEAD request to find the size of the remote content.\n The size is returned in the result parameter of the 'complete' signal.\n \"\"\"\n self._setup_message('HEAD')\n self._session.queue_message(self._message, self._message_cb, None)\n ", "context": "class Downloader(GObject.GObject):\n def get_size(self): ...\n def __init__(self, url, session=None, request_headers=None): ...\n def _setup_message(self, method='GET'): ...\n def download_to_temp(self): ...\n def download_chunked(self): ...\n def download(self, start=None, end=None): ...\n def _message_cb(self, session, message, user_data): ...\n def cancel(self): ...\n def _headers_cb(self, message, user_data): ...\n def _got_chunk_cb(self, message, buf): ...\n def __write_async_cb(self, output_stream, result, user_data): ...\n def _complete(self): ...\n def _check_if_finished(self): ...\n def _write_next_buffer(self): ...\n def _get_temp_file_path(self, uri): ...\n def get_local_file_path(self): ...\n\n self._uri = Soup.URI.new(url)\n self._session = session or get_soup_session()\n self._pending_buffers = []\n self._downloaded_size = 0\n self._total_size = 0\n self._cancelling = False\n self._status_code = None\n self._output_file = None\n self._output_stream = None\n self._message = None\n self._request_headers = request_headers\n\n __gsignals__ = {'progress': (GObject.SignalFlags.RUN_FIRST, None, [float]), 'got-chunk': (GObject.SignalFlags.RUN_FIRST, None, (object,)), 'complete': (GObject.SignalFlags.RUN_FIRST, None, (object,))}\n", "repository": "devAbnull/sugar-prototype", "test_name": "test_get_size", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000860.py"} {"focal_file": "tests/test_modemconfiguration.py", "focal_class": null, "focal_method": "get_providers", "tests": "import unittest\n\nclass Test_get_providers(unittest.TestCase):\n def test_get_providers(self):\n for country_idx, country in enumerate(self.countries_from_class):\n providers = self.db.get_providers(country_idx)\n for provider in providers:\n self.assertEqual(provider.tag, 'provider')\n self.assertIsNotNone(provider.find('.//gsm'))\n", "method_code": " def get_providers(self, country_xml):\n \"\"\"Given a country element find all provider with a gsm tag.\"\"\"\n idx = 0\n for provider in country_xml.findall('provider'):\n if provider.find('.//gsm'):\n yield (idx, provider)\n idx = idx + 1\n ", "context": "class ServiceProvidersParserTest(unittest.TestCase):\n def get_providers(self, country_xml): ...\n def setUp(self): ...\n def test_get_countries(self): ...\n def test_get_country_idx_by_code(self): ...\n def test_get_country_name_by_idx(self): ...\n def test_get_providers(self): ...\n def test_get_plans(self): ...\n def get_plans(self, provider_xml): ...\n def test_get_some_specific_values(self): ...\n", "repository": "devAbnull/sugar-prototype", "test_name": "test_get_providers", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000861.py"} {"focal_file": "tests/test_modemconfiguration.py", "focal_class": null, "focal_method": "get_plans", "tests": "import unittest\n\nclass Test_get_plans(unittest.TestCase):\n def test_get_plans(self):\n for country_idx, country in enumerate(self.countries_from_class):\n providers = self.db.get_providers(country_idx)\n for provider_idx, provider in enumerate(providers):\n plans = self.db.get_plans(country_idx, provider_idx)\n for plan in plans:\n self.assertEqual(plan.tag, 'apn')\n", "method_code": " def get_plans(self, provider_xml):\n \"\"\"Given a provider element find all apn elements.\"\"\"\n for idx, plan in enumerate(provider_xml.findall('.//apn')):\n yield (idx, plan)\n ", "context": "class ServiceProvidersParserTest(unittest.TestCase):\n def get_plans(self, provider_xml): ...\n def setUp(self): ...\n def test_get_countries(self): ...\n def test_get_country_idx_by_code(self): ...\n def test_get_country_name_by_idx(self): ...\n def test_get_providers(self): ...\n def test_get_plans(self): ...\n def get_providers(self, country_xml): ...\n def test_get_some_specific_values(self): ...\n", "repository": "devAbnull/sugar-prototype", "test_name": "test_get_plans", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000862.py"} {"focal_file": "password.py", "focal_class": null, "focal_method": "hasSeries", "tests": "import unittest\n\nclass Test_hasSeries(unittest.TestCase):\n def test_hasSeries(self):\n self.assertTrue(pwd.hasSeries('abc'))\n self.assertFalse(pwd.hasSeries('abd'))\n", "method_code": "def hasSeries(password):\n pwd = list(password)\n i = len(pwd) - 1\n while i >= 0:\n if pwd[i] == chr(ord(pwd[i - 1]) + 1) and pwd[i] == chr(ord(pwd[i - 2]) + 2):\n return True\n else:\n i -= 1\n return False", "context": "def hasSeries(password): ...\ndef getNext(password): ...\ndef hasNoBadChar(password): ...\ndef hasTwoPairs(password): ...\ndef hasSeries(password): ...\n", "repository": "0diekatze1/Chaines", "test_name": "test_hasSeries", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000863.py"} {"focal_file": "password.py", "focal_class": null, "focal_method": "hasTwoPairs", "tests": "import unittest\n\nclass Test_hasTwoPairs(unittest.TestCase):\n def test_hasTwoPairs(self):\n self.assertTrue(pwd.hasTwoPairs('aabb'))\n self.assertFalse(pwd.hasTwoPairs('aaab'))\n self.assertFalse(pwd.hasTwoPairs('abab'))\n self.assertTrue(pwd.hasTwoPairs('aaabcc'))\n", "method_code": "def hasTwoPairs(password):\n pwd = list(password)\n i = len(pwd) - 1\n countpairs = 0\n if i < 3:\n return False\n while i > 0:\n if pwd[i] == pwd[i - 1]:\n countpairs += 1\n i -= 2\n else:\n i -= 1\n return countpairs >= 2", "context": "def hasTwoPairs(password): ...\ndef getNext(password): ...\ndef hasNoBadChar(password): ...\ndef hasTwoPairs(password): ...\ndef hasSeries(password): ...\n", "repository": "0diekatze1/Chaines", "test_name": "test_hasTwoPairs", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000864.py"} {"focal_file": "password.py", "focal_class": null, "focal_method": "hasNoBadChar", "tests": "import unittest\n\nclass Test_hasNoBadChar(unittest.TestCase):\n def test_hasNoBadChar(self):\n self.assertFalse(pwd.hasNoBadChar('aaoaa'))\n self.assertFalse(pwd.hasNoBadChar('oaaaa'))\n self.assertFalse(pwd.hasNoBadChar('aalaa'))\n self.assertFalse(pwd.hasNoBadChar('aaaai'))\n self.assertTrue(pwd.hasNoBadChar('aaaaa'))\n", "method_code": "def hasNoBadChar(password):\n pwd = list(password)\n for i in pwd:\n if i in 'iol':\n return False\n return True", "context": "def hasNoBadChar(password): ...\ndef getNext(password): ...\ndef hasNoBadChar(password): ...\ndef hasTwoPairs(password): ...\ndef hasSeries(password): ...\n", "repository": "0diekatze1/Chaines", "test_name": "test_hasNoBadChar", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000865.py"} {"focal_file": "royal/resource.py", "focal_class": null, "focal_method": "index", "tests": "import unittest\n\nclass Test_index(unittest.TestCase):\n def test_collection(self):\n from royal.resource import Collection, Root\n from royal.exceptions import MethodNotAllowed\n request = DummyRequest()\n root = Root(request)\n collection = self.check_assertions(Collection, 'users', root)\n with self.assertRaises(MethodNotAllowed):\n collection.index()\n with self.assertRaises(MethodNotAllowed):\n collection.create([])\n with self.assertRaises(MethodNotAllowed):\n collection.delete()\n", "method_code": " def index(self):\n self._not_allowed('index')\n ", "context": "class Base(object):\n @property\n def index(self): ...\n def __init__(self, name, parent, request): ...\n def __getitem__(self, key): ...\n def _not_allowed(self, name): ...\n def create(self): ...\n def show(self): ...\n def replace(self): ...\n def update(self): ...\n def delete(self): ...\n def root(self): ...\n def find_interface(self, interface): ...\n def find_collection(self, resource_path): ...\n def find_item(self, resource_path): ...\n def resource_url(self, resource, **query_params): ...\n def url(self, **query_params): ...\n def name(self): ...\n def links(self): ...\n def on_traversing(self, key): ...\n\n self.__name__ = unicode(name)\n self.__parent__ = parent\n self.request = request\n\n __children__ = None\n", "repository": "hadrien/pyramid_royal", "test_name": "test_collection", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000866.py"} {"focal_file": "royal/resource.py", "focal_class": null, "focal_method": "show", "tests": "import unittest\n\nclass Test_show(unittest.TestCase):\n def test_resource(self):\n from royal.resource import Collection, Item, Root\n from royal.exceptions import MethodNotAllowed\n request = DummyRequest()\n root = Root(request)\n c = Collection('users', root, None)\n resource = self.check_assertions(Item, 'hadrien', parent=c)\n with self.assertRaises(MethodNotAllowed):\n resource.show()\n with self.assertRaises(MethodNotAllowed):\n resource.delete()\n with self.assertRaises(MethodNotAllowed):\n resource.replace()\n with self.assertRaises(MethodNotAllowed):\n resource.update()\n", "method_code": " def show(self):\n self._not_allowed('show')\n ", "context": "class Base(object):\n @property\n def show(self): ...\n def __init__(self, name, parent, request): ...\n def __getitem__(self, key): ...\n def _not_allowed(self, name): ...\n def index(self): ...\n def create(self): ...\n def replace(self): ...\n def update(self): ...\n def delete(self): ...\n def root(self): ...\n def find_interface(self, interface): ...\n def find_collection(self, resource_path): ...\n def find_item(self, resource_path): ...\n def resource_url(self, resource, **query_params): ...\n def url(self, **query_params): ...\n def name(self): ...\n def links(self): ...\n def on_traversing(self, key): ...\n\n self.__name__ = unicode(name)\n self.__parent__ = parent\n self.request = request\n\n __children__ = None\n", "repository": "hadrien/pyramid_royal", "test_name": "test_resource", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000867.py"} {"focal_file": "validate_board.py", "focal_class": null, "focal_method": "get_column", "tests": "import unittest\n\nclass Test_get_column(unittest.TestCase):\n def test_get_column_a(self):\n board = u'\\n a b c d e f g h\\n 8 ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼\\n 7 ♛ ◻ ◼ ◻ ◼ ◻ ◼ ◻\\n 6 ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼\\n 5 ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻\\n 4 ♛ ◼ ◻ ◼ ◻ ◼ ◻ ◼\\n 3 ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻\\n 2 ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼\\n 1 ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻\\n '\n column = get_column('a', board)\n expected = u'◻♛◻◼♛◼◻◼'\n self.assertEqual(expected, column)\n", "method_code": "def get_column(column, board):\n board = board.replace(' ', '')\n indexes_of_the_column = get_column_indexes(column, board)\n column_to_validate = ''.join([board[index] for index in indexes_of_the_column])\n return column_to_validate", "context": "def get_column(column, board): ...\ndef validate_board(board): ...\ndef validate_row(row, board): ...\ndef validate_column(column, board): ...\ndef validate_diagonally(position, board): ...\ndef get_column(column, board): ...\ndef get_column_indexes(column, board): ...\ndef get_diagonal_positions(position): ...\ndef is_align_diagonally(position1, position2): ...\n", "repository": "juacompe/eight_queen", "test_name": "test_get_column_a", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000868.py"} {"focal_file": "validate_board.py", "focal_class": null, "focal_method": "get_column_indexes", "tests": "import unittest\n\nclass Test_get_column_indexes(unittest.TestCase):\n def test_get_column_indexes_of_a(self):\n board = u'\\n abcdefgh\\n 8◻◼◻◼◻◼◻◼\\n 7♛◻◼◻◼◻◼◻\\n 6◻◼◻◼◻◼◻◼\\n 5◼◻◼◻◼◻◼◻\\n 4♛◼◻◼◻◼◻◼\\n 3◼◻◼◻◼◻◼◻\\n 2◻◼◻◼◻◼◻◼\\n 1◼◻◼◻◼◻◼◻\\n '\n result = get_column_indexes('a', board)\n expected_indexes = [11, 21, 31, 41, 51, 61, 71, 81]\n self.assertEquals(expected_indexes, result)\n\n def test_get_column_indexes_of_b(self):\n board = u'\\n abcdefgh\\n 8◻◼◻◼◻◼◻◼\\n 7♛◻◼◻◼◻◼◻\\n 6◻◼◻◼◻◼◻◼\\n 5◼◻◼◻◼◻◼◻\\n 4♛◼◻◼◻◼◻◼\\n 3◼◻◼◻◼◻◼◻\\n 2◻◼◻◼◻◼◻◼\\n 1◼◻◼◻◼◻◼◻\\n '\n result = get_column_indexes('b', board)\n expected_indexes = [12, 22, 32, 42, 52, 62, 72, 82]\n self.assertEquals(expected_indexes, result)\n\n def test_get_column_indexes_of_h(self):\n board = u'\\n abcdefgh\\n 8◻◼◻◼◻◼◻◼\\n 7♛◻◼◻◼◻◼◻\\n 6◻◼◻◼◻◼◻◼\\n 5◼◻◼◻◼◻◼◻\\n 4♛◼◻◼◻◼◻◼\\n 3◼◻◼◻◼◻◼◻\\n 2◻◼◻◼◻◼◻◼\\n 1◼◻◼◻◼◻◼◻\\n '\n result = get_column_indexes('h', board)\n expected_indexes = [18, 28, 38, 48, 58, 68, 78, 88]\n self.assertEquals(expected_indexes, result)\n", "method_code": "def get_column_indexes(column, board):\n \"\"\"\n return list of xy while:\n - x depends on row and\n - y depends on column\n \"\"\"\n board = board.replace(' ', '')\n all_y = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}\n y = all_y[column]\n all_x = range(1, 9)\n return [int(str(x) + str(y)) for x in all_x]", "context": "def get_column_indexes(column, board): ...\ndef validate_board(board): ...\ndef validate_row(row, board): ...\ndef validate_column(column, board): ...\ndef validate_diagonally(position, board): ...\ndef get_column(column, board): ...\ndef get_column_indexes(column, board): ...\ndef get_diagonal_positions(position): ...\ndef is_align_diagonally(position1, position2): ...\n", "repository": "juacompe/eight_queen", "test_name": "test_get_column_indexes_of_a", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000869.py"} {"focal_file": "validate_board.py", "focal_class": null, "focal_method": "get_diagonal_positions", "tests": "import unittest\n\nclass Test_get_diagonal_positions(unittest.TestCase):\n def test_diagonal_positions_from_the_corner(self):\n result = get_diagonal_positions('a1')\n expected_indexes = ['b2', 'c3', 'd4', 'e5', 'f6', 'g7', 'h8']\n self.assertEquals(set(expected_indexes), set(result))\n\n def test_diagonal_positions_from_the_middle_of_the_board(self):\n result = get_diagonal_positions('d5')\n expected_indexes = ['c6', 'b7', 'a8', 'c4', 'b3', 'a2', 'e6', 'f7', 'g8', 'e4', 'f3', 'g2', 'h1']\n self.assertEquals(set(expected_indexes), set(result))\n", "method_code": "def get_diagonal_positions(position):\n p1 = position\n diagonal_positions = [p2 for p2 in all_positions if is_align_diagonally(p1, p2)]\n return diagonal_positions", "context": "def get_diagonal_positions(position): ...\ndef validate_board(board): ...\ndef validate_row(row, board): ...\ndef validate_column(column, board): ...\ndef validate_diagonally(position, board): ...\ndef get_column(column, board): ...\ndef get_column_indexes(column, board): ...\ndef get_diagonal_positions(position): ...\ndef is_align_diagonally(position1, position2): ...\n", "repository": "juacompe/eight_queen", "test_name": "test_diagonal_positions_from_the_corner", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000870.py"} {"focal_file": "validate_board.py", "focal_class": null, "focal_method": "is_align_diagonally", "tests": "import unittest\n\nclass Test_is_align_diagonally(unittest.TestCase):\n def test_is_align_diagonally_towards_bottom_left(self):\n position1 = 'g8'\n position2_list = ['f7', 'e6', 'd5', 'c4', 'b3', 'a2']\n for position2 in position2_list:\n result = is_align_diagonally(position1, position2)\n self.assertTrue(result, position2)\n\n def test_is_align_diagonally_towards_top_left(self):\n position1 = 'h2'\n position2_list = ['g3', 'f4', 'e5', 'd6', 'c7', 'b8']\n for position2 in position2_list:\n result = is_align_diagonally(position1, position2)\n self.assertTrue(result, position2)\n\n def test_is_align_diagonally_towards_bottom_right(self):\n position1 = 'c8'\n position2_list = ['d7', 'e6', 'f5', 'g4', 'h3']\n for position2 in position2_list:\n result = is_align_diagonally(position1, position2)\n self.assertTrue(result, position2)\n\n def test_is_align_diagonally_towards_top_right(self):\n position1 = 'a1'\n position2_list = ['b2', 'c3', 'd4', 'e5', 'f6', 'g7', 'h8']\n for position2 in position2_list:\n result = is_align_diagonally(position1, position2)\n self.assertTrue(result, position2)\n\n def test_c4_is_not_align_diagonally_with_itself(self):\n result = is_align_diagonally('c4', 'c4')\n self.assertFalse(result)\n\n def test_c4_is_not_align_diagonally_with_a1(self):\n result = is_align_diagonally('c4', 'a1')\n self.assertFalse(result)\n\n def test_b3_is_not_align_diagonally_with_a1(self):\n result = is_align_diagonally('b3', 'a1')\n", "method_code": "def is_align_diagonally(position1, position2):\n column1, row1 = to_coordinate_pair(position1)\n column2, row2 = to_coordinate_pair(position2)\n all_y = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}\n x1 = int(row1)\n y1 = all_y[column1]\n x2 = int(row2)\n y2 = all_y[column2]\n same_position = x1 == x2 and y1 == y2\n aligned_diagonally = x1 - y1 == x2 - y2 or x1 + y1 == x2 + y2\n return not same_position and aligned_diagonally", "context": "def is_align_diagonally(position1, position2): ...\ndef validate_board(board): ...\ndef validate_row(row, board): ...\ndef validate_column(column, board): ...\ndef validate_diagonally(position, board): ...\ndef get_column(column, board): ...\ndef get_column_indexes(column, board): ...\ndef get_diagonal_positions(position): ...\ndef is_align_diagonally(position1, position2): ...\n", "repository": "juacompe/eight_queen", "test_name": "test_is_align_diagonally_towards_bottom_left", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000871.py"} {"focal_file": "mumbleroni/core/module/datastructure.py", "focal_class": null, "focal_method": "from_dict", "tests": "import unittest\n\nclass Test_from_dict(unittest.TestCase):\n def test_parse_from_empty_dict(self):\n with self.assertRaises(ValueError):\n Settings.from_dict({})\n\n def test_parse_from_dict_port(self):\n settings = {'server': {'host': self._host, 'username': self._user, 'port': self._port}}\n expected = Settings()\n expected.server.host = self._host\n expected.server.username = self._user\n expected.server.port = self._port\n actual = Settings.from_dict(settings)\n assert expected.server.host == actual.server.host\n assert expected.server.username == actual.server.username\n assert expected.server.port == actual.server.port\n\n def test_parse_from_valid_dict_1(self):\n settings = {'server': {'host': self._host, 'username': self._user}}\n expected = Settings()\n expected.server.host = self._host\n expected.server.username = self._user\n actual = Settings.from_dict(settings)\n assert actual.server.host is expected.server.host\n assert actual.server.username is expected.server.username\n", "method_code": " def from_dict(cls, d):\n if not d:\n raise ValueError('The dict was None or empty.')\n result = Manifest()\n result.name = d.get(cls.KEY_NAME)\n result.version = d.get(cls.KEY_VERSION)\n result.summary = d.get(cls.KEY_SUMMARY)\n cls.validate(result)\n return result\n ", "context": "class Manifest(IDictParseable):\n @classmethod\n def from_dict(cls, d): ...\n def __init__(self): ...\n def __repr__(self): ...\n def to_dict(self): ...\n def validate(cls, manifest): ...\n def _validate_name(cls, manifest): ...\n def _validate_version(cls, manifest): ...\n def _validate_summary(cls, manifest): ...\n def is_empty(self): ...\n def name(self): ...\n def name(self, value): ...\n def version(self): ...\n def version(self, value): ...\n def summary(self): ...\n def summary(self, value): ...\n\n self._name = None\n self._version = None\n self._summary = None\n\n KEY_NAME = 'name'\n KEY_VERSION = 'version'\n KEY_SUMMARY = 'summary'\n", "repository": "0xA537FD/MumbleRoni", "test_name": "test_parse_from_empty_dict", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000872.py"} {"focal_file": "livesync/management/commands/runserver.py", "focal_class": null, "focal_method": "_parse_options", "tests": "import unittest\n\nclass Test_parse_options(unittest.TestCase):\n def test_parse_default_options(self):\n options = {'liveport': None, 'addrport': ''}\n self.command._parse_options(**options)\n self.assertEqual(self.command.liveport, 9001)\n self.assertEqual(self.command.livehost, 'localhost')\n", "method_code": " def _parse_options(self, **options):\n if options['liveport']:\n liveport = options['liveport']\n if not isinstance(liveport, int) and (not liveport.isdigit()):\n raise CommandError('LiveSync port must be an integer.')\n self.liveport = int(liveport)\n if options['addrport']:\n matches = re.match(naiveip_re, options['addrport'])\n if matches and matches.groups()[0]:\n self.livehost = matches.groups()[0]\n ", "context": "class Command(RunserverCommand):\n def _parse_options(self, **options): ...\n def __init__(self): ...\n def init_settings(self): ...\n def add_arguments(self, parser): ...\n def liveport(self): ...\n def liveport(self, value): ...\n def livehost(self): ...\n def livehost(self, value): ...\n def _start_async_server(self): ...\n def _stop_async_server(self): ...\n def _start_watchdog(self): ...\n def _stop_watchdog(self): ...\n def stop_liveserver(self): ...\n def start_liveserver(self, **options): ...\n def handle(self, *args, **options): ...\n\n self.server = None\n self.server_process = None\n self.file_watcher = None\n\n help = 'Starts a lightweight Web server for development with Live Sync.'\n", "repository": "fabiogibson/django-livesync", "test_name": "test_parse_default_options", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000873.py"} {"focal_file": "msa2vcf/MSA2VCFImplementation.py", "focal_class": "MSAVCF.MSA2VCFImplementation", "focal_method": "_parseMSASample", "tests": "import unittest\n\nclass Test_MSAVCF_MSA2VCFImplementation_parseMSASample(unittest.TestCase):\n def testParseMSASample_GoodSNP(self):\n self.logger.info('BEGIN')\n ref = 'A*01:01:01:01 CAGGAGCAGA GGGGTCAGGG ATTGGGGAGT CCCAGCCTTG '\n seq1 = 'A*01:01:01:02 T--------- ---------- ---------- ---------- '\n seq2 = 'A*01:01:01:03 -----C---- ---------- ---------- ---------- '\n seq3 = 'A*01:01:01:04 ---------C ---------- ---------- ---------- '\n seq4 = 'A*01:01:01:05 ---------C ---------- -AA------- ---------- '\n msa2vcf = MSAVCF.MSA2VCFImplementation()\n offset = 0\n result1List = msa2vcf._parseMSASample(offset, ref, seq1)\n self.logger.info('result1[0]:\\n{}\\t'.format(result1List[0]))\n r1Expected = 'CHROM:A*01:01:01:01 sample:A*01:01:01:02 POS:1 ID:. REF:C ALT:T QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism'\n self.assertEqual(str(result1List[0]), r1Expected)\n result2List = msa2vcf._parseMSASample(offset, ref, seq2)\n self.logger.info('result2[0]:\\n{}'.format(result2List[0]))\n r2Expected = 'CHROM:A*01:01:01:01 sample:A*01:01:01:03 POS:6 ID:. REF:G ALT:C QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism'\n self.assertEqual(str(result2List[0]), r2Expected)\n result3List = msa2vcf._parseMSASample(offset, ref, seq3)\n self.logger.info('result3[0]:\\n{}'.format(result3List[0]))\n r3Expected = 'CHROM:A*01:01:01:01 sample:A*01:01:01:04 POS:10 ID:. REF:A ALT:C QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism'\n self.assertEqual(str(result3List[0]), r3Expected)\n result4List = msa2vcf._parseMSASample(offset, ref, seq4)\n r4Expected = ['CHROM:A*01:01:01:01 sample:A*01:01:01:05 POS:10 ID:. REF:A ALT:C QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism', 'CHROM:A*01:01:01:01 sample:A*01:01:01:05 POS:22 ID:. REF:T ALT:A QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism', 'CHROM:A*01:01:01:01 sample:A*01:01:01:05 POS:23 ID:. REF:T ALT:A QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism']\n for i in range(len(result4List)):\n msas = result4List[i]\n self.logger.info('msas{}:\\n{}'.format(i, msas))\n self.assertEqual(str(msas), r4Expected[i])\n self.logger.info('END\\n')\n\n def testParseMSASample_DeleteSNP(self):\n self.logger.info('BEGIN')\n ref = 'A*01:01:01:01 CAGGAGCAGA GGGGTCAGGG ATTGGGGAGT CCCAGCCTTG '\n seq1 = 'A*01:01:01:02 .--------- ---------- ---------- ---------- '\n seq2 = 'A*01:01:01:03 -----.---- ---------- ---------- ---------- '\n seq3 = 'A*01:01:01:04 ---------. ---------- ---------- ---------- '\n seq4 = 'A*01:01:01:05 ---------- .--------- ---------- ---------- '\n seq5 = 'A*01:01:01:06 ---------. ---------- -..------- ---------- '\n msa2vcf = MSAVCF.MSA2VCFImplementation()\n offset = 0\n result1List = msa2vcf._parseMSASample(offset, ref, seq1)\n self.logger.info('result1[0]:\\n{}'.format(result1List[0]))\n r1Expected = 'CHROM:A*01:01:01:01 sample:A*01:01:01:02 POS:1 ID:. REF:CA ALT:A QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.deletion'\n self.assertEqual(str(result1List[0]), r1Expected)\n result2List = msa2vcf._parseMSASample(offset, ref, seq2)\n self.logger.info('result2[0]:\\n{}'.format(result2List[0]))\n r2Expected = 'CHROM:A*01:01:01:01 sample:A*01:01:01:03 POS:5 ID:. REF:AG ALT:A QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.deletion'\n self.assertEqual(str(result2List[0]), r2Expected)\n result3List = msa2vcf._parseMSASample(offset, ref, seq3)\n self.logger.info('result3[0]:\\n{}'.format(result3List[0]))\n r3Expected = 'CHROM:A*01:01:01:01 sample:A*01:01:01:04 POS:9 ID:. REF:GA ALT:G QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.deletion'\n self.assertEqual(str(result3List[0]), r3Expected)\n result4List = msa2vcf._parseMSASample(offset, ref, seq4)\n self.logger.info('result4[0]:\\n{}'.format(result4List[0]))\n r4Expected = 'CHROM:A*01:01:01:01 sample:A*01:01:01:05 POS:10 ID:. REF:AG ALT:A QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.deletion'\n self.assertEqual(str(result4List[0]), r4Expected)\n result5List = msa2vcf._parseMSASample(offset, ref, seq5)\n r5Expected = ['CHROM:A*01:01:01:01 sample:A*01:01:01:06 POS:9 ID:. REF:GA ALT:G QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.deletion', 'CHROM:A*01:01:01:01 sample:A*01:01:01:06 POS:21 ID:. REF:ATT ALT:A QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.deletion']\n for i in range(len(result5List)):\n msas = result5List[i]\n self.logger.info('\\nmsas:{}:{}'.format(i, msas))\n self.assertEqual(str(msas), r5Expected[i])\n self.logger.info('END\\n')\n\n def testParseMSASample_DeleteEndSNP(self):\n self.logger.info('BEGIN')\n ref = 'A*01:01:01:01 CAGGAGCAGA'\n seq1 = 'A*01:01:01:04 ---------.'\n msa2vcf = MSAVCF.MSA2VCFImplementation()\n offset = 0\n result1List = msa2vcf._parseMSASample(offset, ref, seq1)\n self.logger.info('result1[0]:\\n{}'.format(result1List[0]))\n r1Expected = 'CHROM:A*01:01:01:01 sample:A*01:01:01:04 POS:9 ID:. REF:GA ALT:G QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.deletion'\n self.assertEqual(str(result1List[0]), r1Expected)\n self.logger.info('END\\n')\n", "method_code": " def _parseMSASample(self, offset, reference, sample):\n \"\"\"\n FIXME: add doc\n \n arguments:\n offset: integer position offset. I.E. position of first base in reference\n \n reference:reference sequence line\n example: \"A*01:01:01:01 CAGGAGCAGA GGGGTCAGGG ATTGGGGAGT CCCAGCCTTG \"\n \n sample: sequence to compare\n example: \"A*01:01:01:02 T--------- ---------- ---------- ---------- \"\n \n returns a list of MSASample object\n \"\"\"\n ret = []\n refList = reference.strip().split()\n refSeq = ''.join(refList[1:])\n sampleList = sample.strip().split()\n sampleSeq = ''.join(sampleList[1:])\n refChromName = refList[0]\n sampleName = sampleList[0]\n if len(refSeq) != len(sampleSeq):\n self.logger.warning('skipping ref len(chrom:{})=={} != len(sampleName:{})=={}'.format(refChromName, len(refSeq), sampleName, len(sampleSeq)))\n return ret\n refList = None\n sampleList = None\n ident = '.'\n qual = '.'\n filterArg = 'PASS'\n info = '.'\n formatArg = 'GT'\n position = offset\n varientType = VariantType.unknown\n bases = set(['A', 'C', 'G', 'T'])\n numBases = len(refSeq)\n i = 0\n while i < numBases:\n try:\n msaRefChar = refSeq[i]\n except IndexError as ie:\n self.logger.error('AEDWIP IndexError:\\n{}'.format(ie))\n if msaRefChar in bases or msaRefChar == '*':\n position += 1\n msfChar = sampleSeq[i]\n alt = 'ERROR'\n varientType = VariantType.unknown\n if msaRefChar == '|' and msfChar == '-':\n i += 1\n elif msfChar == '-':\n i += 1\n elif msfChar in bases and msaRefChar in bases:\n alt = msfChar\n varientType = VariantType.polymorphism\n i += 1\n msfs = MSASample(refChromName, sampleName, position, ident, msaRefChar, alt, qual, filterArg, info, formatArg, varientType)\n ret.append(msfs)\n elif msfChar == '*':\n i += 1\n elif msaRefChar == '*':\n i += 1\n position -= 1\n elif msfChar == '.' and msaRefChar in bases:\n varientType = VariantType.deletion\n startPosition = position - 1\n if startPosition <= 0:\n startPosition = 1\n endOfDeletionPosition = i\n while endOfDeletionPosition + 1 < numBases and sampleSeq[endOfDeletionPosition + 1] == '.':\n endOfDeletionPosition += 1\n if refSeq[endOfDeletionPosition] in bases:\n position += 1\n if i - 1 >= 0:\n msaRefChar = refSeq[i - 1:endOfDeletionPosition + 1]\n msaRefChar = msaRefChar.replace('.', '').replace('|', '')\n alt = msaRefChar[0]\n else:\n msaRefChar = refSeq[i:endOfDeletionPosition + 2]\n msaRefChar = msaRefChar.replace('.', '').replace('|', '')\n alt = msaRefChar[-1]\n if endOfDeletionPosition - i == 0:\n i += 1\n else:\n i += endOfDeletionPosition - i + 1\n msfs = MSASample(refChromName, sampleName, startPosition, ident, msaRefChar, alt, qual, filterArg, info, formatArg, varientType)\n ret.append(msfs)\n elif msaRefChar == '.' and msfChar in bases:\n i, startPosition, msaRefChar, alt = self._parseInsertion(bases, i, numBases, position, refSeq, sampleSeq)\n varientType = VariantType.insertion\n msfs = MSASample(refChromName, sampleName, startPosition, ident, msaRefChar, alt, qual, filterArg, info, formatArg, varientType)\n ret.append(msfs)\n elif msfChar == '|' and msaRefChar == '|':\n i += 1\n elif msaRefChar == '.' and msfChar == '.':\n self.logger.info(\"AEDWIP msaRefChar == msfChar == '.' ignored sampleName:{} offset:{} position:{}\".format(sampleName, offset, position))\n i += 1\n else:\n self.logger.warning(\"unexpected ref char:'{}' msf char:'{}' ignored sampleName:{} offset:{} position:{}\".format(msaRefChar, msfChar, sampleName, offset, position))\n i += 1\n return ret\n ", "context": "class MSA2VCFImplementation(object):\n def _parseMSASample(self, offset, reference, sample): ...\n def parse(self, inputFilePath, outputFilePath): ...\n def _load(self, inputFilePath, numColensInSampleName=3): ...\n def _cleanInputLine(self, line): ...\n def __init__(self): ...\n def _combine(self, numberOfSamples, sampleNameLookUp, variantType, msfsList): ...\n def _createAbstractSyntaxTree(self, msfsList): ...\n def _parseDeletion(self, bases, i, numBases, position, refSeq, sampleSeq): ...\n def _parseInsertion(self, bases, i, numBases, position, refSeq, sampleSeq): ...\n def _parseMSASampleList(self, offset, reference, sampleList): ...\n def _write2VCF(self, outputFilePath, vcfList, sampleNamesList, referenceName, referenceLength): ...\n\n logger = logging.getLogger(__name__)\n", "repository": "aedavids/msa2vcf", "test_name": "testParseMSASample_GoodSNP", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000874.py"} {"focal_file": "msa2vcf/MSA2VCFImplementation.py", "focal_class": "MSAVCF.MSA2VCFImplementation", "focal_method": "_createAbstractSyntaxTree", "tests": "import unittest\n\nclass Test_MSAVCF_MSA2VCFImplementation_createAbstractSyntaxTree(unittest.TestCase):\n def testCreateAbstractSyntaxTree(self):\n self.logger.info('BEGIN')\n ref = 'r1 GAT'\n s1 = 's1 -T-'\n s2 = 's2 -C-'\n s3 = 's3 -T-'\n msa2vcf = MSAVCF.MSA2VCFImplementation()\n offset = 0\n msasList1 = msa2vcf._parseMSASample(offset, ref, s1)\n msasList2 = msa2vcf._parseMSASample(offset, ref, s2)\n msasList3 = msa2vcf._parseMSASample(offset, ref, s3)\n msasList = msasList1 + msasList3 + msasList2\n for msas in msasList:\n self.logger.info('msas:{}'.format(msas))\n sampleNamesList, sampleNameLookUp, AST = msa2vcf._createAbstractSyntaxTree(msasList)\n self.logger.info('sampleNamesList:{}'.format(sampleNamesList))\n self.assertEqual(sampleNamesList, ['s1', 's2', 's3'])\n self.logger.info('sampleNameLookUp:{}'.format(sampleNameLookUp))\n self.assertEqual(sampleNameLookUp, {'s1': 0, 's2': 1, 's3': 2})\n self.logger.info('ast:{}'.format(AST))\n pp = pprint.PrettyPrinter()\n ASTStr = pp.pformat(AST)\n deletionVCF = AST['r1POS:2'][MSAVCF.VariantType.deletion]\n self.logger.info('deletionVCF:\\n{}'.format(deletionVCF))\n self.assertEqual(deletionVCF, {})\n insertionsVCF = AST['r1POS:2'][MSAVCF.VariantType.insertion]\n self.logger.info('insertionsVCF:\\n{}'.format(insertionsVCF))\n self.assertEqual(insertionsVCF, {})\n unknownVCF = AST['r1POS:2'][MSAVCF.VariantType.unknown]\n self.logger.info('unknownVCF:\\n{}'.format(unknownVCF))\n self.assertEqual(unknownVCF, {})\n polymorphismVCF = AST['r1POS:2'][MSAVCF.VariantType.polymorphism]\n self.logger.info('polymorphismVCF:\\n{}'.format(polymorphismVCF))\n expectedP = \"{'T': [CHROM:r1 sample:s1 POS:2 ID:. REF:A ALT:T QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism, CHROM:r1 sample:s3 POS:2 ID:. REF:A ALT:T QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism], 'C': [CHROM:r1 sample:s2 POS:2 ID:. REF:A ALT:C QUAL. FILTER:PASS INFO:. FORMAT:GT VariantType.polymorphism]}\"\n self.assertEqual(str(polymorphismVCF), expectedP)\n self.logger.info('END\\n')\n", "method_code": " def _createAbstractSyntaxTree(self, msfsList):\n \"\"\"\n creates an abstract syntax tree that makes it easy to create a topological ordering and\n productions for generating a vcf version of the original msf file\n \n arguments:\n msfsList: a list of MSASample objects\n \n returns (sampleNamesList, sampleNameLookUp, AST)\n sampleNamesList is a sorted list sample names in the msfsList\n sampleNameLookUp is a dictionary. key = sampleName value = index into sampleNameList\n AST is the abstract syntax tree\n \n Keys can be easily sort so that the final VCF file is ordered by position\n \n inner most dictionary makes it easy to create VCF logical vector\n \n general structure of the AST:\n {key=ref+pos : value= {\n key=VarientType\n value= {\n key=ALT\n value=[MSASample]\n }\n \n example:\n input:\n ref GAT\n N1 -C-\n N2 -T-\n N3 -T-\n \n AST = {ref2 : {\n polymorphism : {\n C : [\"msfc for N1\"],\n T : [\"msfs for N2\", \"msfs for N3\"]\n }\n }\n }\n \"\"\"\n AST = dict()\n sampleNamesSet = set()\n for msfs in msfsList:\n groupingKey = msfs.refChromName + 'POS:' + str(msfs.position)\n variationsDict = None\n if groupingKey in AST:\n variationsDict = AST[groupingKey]\n else:\n variationsDict = {VariantType.unknown: {}, VariantType.polymorphism: {}, VariantType.insertion: {}, VariantType.deletion: {}}\n AST[groupingKey] = variationsDict\n varientDict = variationsDict[msfs.variantType]\n altKey = msfs.alt\n altList = None\n if altKey in varientDict:\n altList = varientDict[altKey]\n else:\n altList = []\n varientDict[altKey] = altList\n altList.append(msfs)\n sampleNamesSet.add(msfs.sampleName)\n sampleNamesList = sorted(list(sampleNamesSet))\n sampleNameLookUp = {sampleNamesList[i]: i for i in range(len(sampleNamesList))}\n return (sampleNamesList, sampleNameLookUp, AST)\n ", "context": "class MSA2VCFImplementation(object):\n def _createAbstractSyntaxTree(self, msfsList): ...\n def parse(self, inputFilePath, outputFilePath): ...\n def _load(self, inputFilePath, numColensInSampleName=3): ...\n def _cleanInputLine(self, line): ...\n def __init__(self): ...\n def _combine(self, numberOfSamples, sampleNameLookUp, variantType, msfsList): ...\n def _parseDeletion(self, bases, i, numBases, position, refSeq, sampleSeq): ...\n def _parseInsertion(self, bases, i, numBases, position, refSeq, sampleSeq): ...\n def _parseMSASample(self, offset, reference, sample): ...\n def _parseMSASampleList(self, offset, reference, sampleList): ...\n def _write2VCF(self, outputFilePath, vcfList, sampleNamesList, referenceName, referenceLength): ...\n\n logger = logging.getLogger(__name__)\n", "repository": "aedavids/msa2vcf", "test_name": "testCreateAbstractSyntaxTree", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000875.py"} {"focal_file": "msa2vcf/MSA2VCFImplementation.py", "focal_class": "MSAVCF.MSA2VCFImplementation", "focal_method": "_parseMSASampleList", "tests": "import unittest\n\nclass Test_MSAVCF_MSA2VCFImplementation_parseMSASampleList(unittest.TestCase):\n def testParsemsaSampleList(self):\n self.logger.info('BEGIN')\n ref = 'r1 GAT'\n s1 = 's1 -T-'\n s2 = 's2 -C-'\n s3 = 's3 -T-'\n s4 = 's4 -.-'\n s5 = 's5 -.-'\n msa2vcf = MSAVCF.MSA2VCFImplementation()\n offset = 0\n vcfList, sampleNamesList = msa2vcf._parseMSASampleList(offset, ref, [s1, s2, s3, s4, s5])\n expected = ['r1 1 . GA G . PASS . GT 0 0 0 1 1', 'r1 2 . A T . PASS . GT 1 0 1 0 0', 'r1 2 . A C . PASS . GT 0 1 0 0 0']\n for i in range(len(vcfList)):\n vcf = vcfList[i]\n self.logger.info('i:{} vcf:{}'.format(i, vcf))\n self.logger.info(' e:{}\\n'.format(expected[i]))\n e = expected[i]\n cleanE = ''.join(e.split())\n cleanV = ''.join(str(vcf).split())\n self.assertEqual(cleanV, cleanE, ' i:{}'.format(i))\n self.logger.info('END\\n')\n", "method_code": " def _parseMSASampleList(self, offset, reference, sampleList):\n \"\"\"\n FIXME: add doc string\n \n arguments\n offset: int. the sample position offset\n reference: string. reference sequence\n sampleList: list of string in https://www.ebi.ac.uk/ipd/imgt/hla/nomenclature/index.html format\n \n returns: (vcfList, sampleNamesList)\n vcfList is a list of VCFSample objects\n sampleNameList are the sample names\n \"\"\"\n ret = []\n msfsList = []\n for i in range(len(sampleList)):\n msfs = self._parseMSASample(offset, reference, sampleList[i])\n msfsList = msfsList + msfs\n sampleNamesList, sampleNameLookUp, AST = self._createAbstractSyntaxTree(msfsList)\n orderedSampleKeys = sorted(list(AST.keys()), key=lambda k: int(k.split('POS:')[1]))\n numberOfSamples = len(sampleNamesList)\n for sampleKey in orderedSampleKeys:\n for vt in VariantType:\n msfsDict = AST[sampleKey][vt]\n for msfsList in msfsDict.values():\n vcf = self._combine(numberOfSamples, sampleNameLookUp, vt, msfsList)\n ret.append(vcf)\n return (ret, sampleNamesList)\n ", "context": "class MSA2VCFImplementation(object):\n def _parseMSASampleList(self, offset, reference, sampleList): ...\n def parse(self, inputFilePath, outputFilePath): ...\n def _load(self, inputFilePath, numColensInSampleName=3): ...\n def _cleanInputLine(self, line): ...\n def __init__(self): ...\n def _combine(self, numberOfSamples, sampleNameLookUp, variantType, msfsList): ...\n def _createAbstractSyntaxTree(self, msfsList): ...\n def _parseDeletion(self, bases, i, numBases, position, refSeq, sampleSeq): ...\n def _parseInsertion(self, bases, i, numBases, position, refSeq, sampleSeq): ...\n def _parseMSASample(self, offset, reference, sample): ...\n def _write2VCF(self, outputFilePath, vcfList, sampleNamesList, referenceName, referenceLength): ...\n\n logger = logging.getLogger(__name__)\n", "repository": "aedavids/msa2vcf", "test_name": "testParsemsaSampleList", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000876.py"} {"focal_file": "server/services/demos.py", "focal_class": null, "focal_method": "create_demo", "tests": "import unittest\n\nclass Test_create_demo(unittest.TestCase):\n def test_demo_create_success(self):\n \"\"\"With correct values, is a valid demo returned?\"\"\"\n demo = demo_service.create_demo()\n demo_json = loads(demo)\n self.assertTrue(demo_json.get('id'))\n self.assertTrue(demo_json.get('guid'))\n self.assertTrue(demo_json.get('createdAt'))\n self.assertTrue(demo_json.get('users'))\n created_user_json = demo_json.get('users')[0]\n self.assertTrue(created_user_json.get('id'))\n self.assertTrue(created_user_json.get('demoId'))\n self.assertTrue(created_user_json.get('username'))\n self.assertTrue(created_user_json.get('email'))\n self.assertTrue(created_user_json.get('roles'))\n scm_role_json = created_user_json.get('roles')[0]\n self.assertTrue(scm_role_json.get('id'))\n self.assertTrue(scm_role_json.get('name') == 'supplychainmanager')\n self.assertTrue(scm_role_json.get('created'))\n self.assertTrue(scm_role_json.get('modified'))\n demo_service.delete_demo_by_guid(demo_json.get('guid'))\n", "method_code": "def create_demo():\n \"\"\"\n Create a new demo session in the ERP system.\n\n :return: The created Demo model.\n \"\"\"\n url = '%s/api/v1/Demos' % get_service_url('lw-erp')\n headers = {'content-type': 'application/json', 'cache-control': 'no-cache'}\n try:\n response = requests.request('POST', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error creating new Demo', internal_details=str(e))\n return response.text", "context": "def create_demo(): ...\ndef demo_to_dict(demo): ...\ndef create_demo(): ...\ndef get_demo_by_guid(guid): ...\ndef delete_demo_by_guid(guid): ...\ndef get_demo_retailers(guid): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_demo_create_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000877.py"} {"focal_file": "server/services/demos.py", "focal_class": null, "focal_method": "get_demo_retailers", "tests": "import unittest\n\nclass Test_get_demo_retailers(unittest.TestCase):\n def test_demo_retrieve_retailers_success(self):\n \"\"\"With correct values, are valid demo retailers returned?\"\"\"\n demo_guid = loads(self.demo).get('guid')\n retailers = demo_service.get_demo_retailers(demo_guid)\n retailers_json = loads(retailers)\n for retailer_json in retailers_json:\n self.assertTrue(retailer_json.get('id'))\n self.assertTrue(retailer_json.get('address'))\n address_json = retailer_json.get('address')\n self.assertTrue(address_json.get('city'))\n self.assertTrue(address_json.get('state'))\n self.assertTrue(address_json.get('country'))\n self.assertTrue(address_json.get('latitude'))\n self.assertTrue(address_json.get('longitude'))\n", "method_code": "def get_demo_retailers(guid):\n \"\"\"\n Retrieve retailers for a demo in the ERP system by guid.\n\n :param guid: The demo's guid.\n :return: An instance of the Demo.\n \"\"\"\n url = '%s/api/v1/Demos/%s/retailers' % (get_service_url('lw-erp'), guid)\n headers = {'cache-control': 'no-cache'}\n try:\n response = requests.request('GET', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error retrieving retailers for demo', internal_details=str(e))\n if response.status_code == 404:\n raise ResourceDoesNotExistException('Demo does not exist', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def get_demo_retailers(guid): ...\ndef demo_to_dict(demo): ...\ndef create_demo(): ...\ndef get_demo_by_guid(guid): ...\ndef delete_demo_by_guid(guid): ...\ndef get_demo_retailers(guid): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_demo_retrieve_retailers_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000878.py"} {"focal_file": "server/services/distribution_centers.py", "focal_class": null, "focal_method": "get_distribution_centers", "tests": "import unittest\n\nclass Test_get_distribution_centers(unittest.TestCase):\n def test_get_distribution_centers_success(self):\n \"\"\"With correct values, are valid distribution centers returned?\"\"\"\n distribution_centers = distribution_center_service.get_distribution_centers(self.loopback_token)\n distribution_centers_json = loads(distribution_centers)\n for distribution_center_json in distribution_centers_json:\n self.assertTrue(distribution_center_json.get('id'))\n if distribution_center_json.get('address'):\n self.assertTrue(distribution_center_json.get('address').get('city'))\n self.assertTrue(distribution_center_json.get('address').get('state'))\n self.assertTrue(distribution_center_json.get('address').get('country'))\n self.assertTrue(distribution_center_json.get('address').get('latitude'))\n self.assertTrue(distribution_center_json.get('address').get('longitude'))\n if distribution_center_json.get('contact'):\n self.assertTrue(distribution_center_json.get('contact').get('name'))\n\n def test_get_distribution_center_success(self):\n \"\"\"With correct values, is a valid distribution center returned?\"\"\"\n distribution_centers = distribution_center_service.get_distribution_centers(self.loopback_token)\n dc_id = loads(distribution_centers)[0].get('id')\n distribution_center = distribution_center_service.get_distribution_center(self.loopback_token, dc_id)\n distribution_center_json = loads(distribution_center)\n self.assertTrue(distribution_center_json.get('id'))\n if distribution_center_json.get('address'):\n self.assertTrue(distribution_center_json.get('address').get('city'))\n self.assertTrue(distribution_center_json.get('address').get('state'))\n self.assertTrue(distribution_center_json.get('address').get('country'))\n self.assertTrue(distribution_center_json.get('address').get('latitude'))\n self.assertTrue(distribution_center_json.get('address').get('longitude'))\n if distribution_center_json.get('contact'):\n self.assertTrue(distribution_center_json.get('contact').get('name'))\n\n def test_get_distribution_center_invalid_token(self):\n \"\"\"With an invalid token, are correct errors thrown?\"\"\"\n distribution_centers = distribution_center_service.get_distribution_centers(self.loopback_token)\n dc_id = loads(distribution_centers)[0].get('id')\n self.assertRaises(AuthenticationException, distribution_center_service.get_distribution_center, utils.get_bad_token(), dc_id)\n\n def test_get_distribution_center_inventory_invalid_token(self):\n \"\"\"With an invalid token, are correct errors thrown?\"\"\"\n distribution_centers = distribution_center_service.get_distribution_centers(self.loopback_token)\n dc_id = loads(distribution_centers)[0].get('id')\n self.assertRaises(AuthenticationException, distribution_center_service.get_distribution_center_inventory, utils.get_bad_token(), dc_id)\n", "method_code": "def get_distribution_centers(token):\n \"\"\"\n Get a list of distribution centers from the ERP system.\n\n :param token: The ERP Loopback session token.\n\n :return: The list of existing distribution centers.\n \"\"\"\n url = '%s/api/v1/DistributionCenters' % get_service_url('lw-erp')\n headers = {'cache-control': 'no-cache', 'Authorization': token}\n try:\n response = requests.request('GET', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error retrieving distribution centers', internal_details=str(e))\n if response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def get_distribution_centers(token): ...\ndef distribution_center_to_dict(distribution_center): ...\ndef get_distribution_centers(token): ...\ndef get_distribution_center(token, dc_id): ...\ndef get_distribution_center_inventory(token, dc_id): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_get_distribution_centers_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000879.py"} {"focal_file": "server/services/distribution_centers.py", "focal_class": null, "focal_method": "get_distribution_center_inventory", "tests": "import unittest\n\nclass Test_get_distribution_center_inventory(unittest.TestCase):\n def test_get_distribution_center_inventory_success(self):\n \"\"\"With correct values, is valid inventory returned?\"\"\"\n distribution_centers = distribution_center_service.get_distribution_centers(self.loopback_token)\n dc_id = loads(distribution_centers)[0].get('id')\n inventory = distribution_center_service.get_distribution_center_inventory(self.loopback_token, dc_id)\n inventories_json = loads(inventory)\n for inventory_json in inventories_json:\n self.assertTrue(inventory_json.get('id'))\n self.assertIsInstance(inventory_json.get('quantity'), IntType)\n self.assertTrue(inventory_json.get('productId'))\n self.assertTrue(inventory_json.get('locationId'))\n self.assertTrue(inventory_json.get('locationType'))\n", "method_code": "def get_distribution_center_inventory(token, dc_id):\n \"\"\"\n Get a distribution center from the ERP system.\n\n :param token: The ERP Loopback session token.\n :param dc_id: The ID of the distribution center for which inventory is to be be retrieved.\n\n :return: The retrieved distribution center's inventory.\n \"\"\"\n url = '%s/api/v1/DistributionCenters/%s/inventories' % (get_service_url('lw-erp'), str(dc_id))\n headers = {'cache-control': 'no-cache', 'Authorization': token}\n try:\n response = requests.request('GET', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error retrieving distribution center inventory', internal_details=str(e))\n if response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n elif response.status_code == 404:\n raise ResourceDoesNotExistException('Distribution center does not exist', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def get_distribution_center_inventory(token, dc_id): ...\ndef distribution_center_to_dict(distribution_center): ...\ndef get_distribution_centers(token): ...\ndef get_distribution_center(token, dc_id): ...\ndef get_distribution_center_inventory(token, dc_id): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_get_distribution_center_inventory_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000880.py"} {"focal_file": "server/services/products.py", "focal_class": null, "focal_method": "get_products", "tests": "import unittest\n\nclass Test_get_products(unittest.TestCase):\n def test_get_products_success(self):\n \"\"\"With correct values, are valid products returned?\"\"\"\n products = product_service.get_products(self.loopback_token)\n products_json = loads(products)\n for product_json in products_json:\n self.assertTrue(product_json.get('id'))\n self.assertTrue(product_json.get('name'))\n self.assertTrue(product_json.get('supplierId'))\n", "method_code": "def get_products(token):\n \"\"\"\n Get a list of products from the ERP system.\n\n :param token: The ERP Loopback session token.\n\n :return: The list of existing products.\n \"\"\"\n url = '%s/api/v1/Products' % get_service_url('lw-erp')\n headers = {'cache-control': 'no-cache', 'Authorization': token}\n try:\n response = requests.request('GET', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error retrieving products', internal_details=str(e))\n if response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def get_products(token): ...\ndef product_to_dict(product): ...\ndef get_products(token): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_get_products_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000881.py"} {"focal_file": "server/services/retailers.py", "focal_class": null, "focal_method": "get_retailers", "tests": "import unittest\n\nclass Test_get_retailers(unittest.TestCase):\n def test_retailers_success(self):\n \"\"\"With correct values, are valid retailers returned?\"\"\"\n retailers = retailer_service.get_retailers(self.loopback_token)\n retailers_json = loads(retailers)\n for retailer_json in retailers_json:\n self.assertTrue(retailer_json.get('id'))\n if retailer_json.get('address'):\n self.assertTrue(retailer_json.get('address').get('city'))\n self.assertTrue(retailer_json.get('address').get('state'))\n self.assertTrue(retailer_json.get('address').get('country'))\n self.assertTrue(retailer_json.get('address').get('latitude'))\n self.assertTrue(retailer_json.get('address').get('longitude'))\n\n def test_get_retailer_success(self):\n \"\"\"With correct values, is a valid distribution center returned?\"\"\"\n retailers = retailer_service.get_retailers(self.loopback_token)\n retailer_id = loads(retailers)[0].get('id')\n retailer = retailer_service.get_retailer(self.loopback_token, retailer_id)\n retailer_json = loads(retailer)\n self.assertTrue(retailer_json.get('id'))\n if retailer_json.get('address'):\n self.assertTrue(retailer_json.get('address').get('city'))\n self.assertTrue(retailer_json.get('address').get('state'))\n self.assertTrue(retailer_json.get('address').get('country'))\n self.assertTrue(retailer_json.get('address').get('latitude'))\n self.assertTrue(retailer_json.get('address').get('longitude'))\n", "method_code": "def get_retailers(token):\n \"\"\"\n Get a list of retailers from the ERP system.\n\n :param token: The ERP Loopback session token.\n\n :return: The list of existing retailers.\n \"\"\"\n url = '%s/api/v1/Retailers' % get_service_url('lw-erp')\n headers = {'cache-control': 'no-cache', 'Authorization': token}\n try:\n response = requests.request('GET', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error retrieving retailers', internal_details=str(e))\n if response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def get_retailers(token): ...\ndef retailer_to_dict(retailer): ...\ndef get_retailers(token): ...\ndef get_retailer(token, retailer_id): ...\ndef get_retailer_inventory(token, retailer_id): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_retailers_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000882.py"} {"focal_file": "server/services/retailers.py", "focal_class": null, "focal_method": "get_retailer_inventory", "tests": "import unittest\n\nclass Test_get_retailer_inventory(unittest.TestCase):\n def test_get_retailer_inventory_success(self):\n \"\"\"With correct values, is valid inventory returned?\"\"\"\n retailers = retailer_service.get_retailers(self.loopback_token)\n retailer_id = loads(retailers)[0].get('id')\n inventory = retailer_service.get_retailer_inventory(self.loopback_token, retailer_id)\n inventories_json = loads(inventory)\n for inventory_json in inventories_json:\n self.assertTrue(inventory_json.get('id'))\n self.assertIsInstance(inventory_json.get('quantity'), IntType)\n self.assertTrue(inventory_json.get('productId'))\n self.assertTrue(inventory_json.get('locationId'))\n self.assertTrue(inventory_json.get('locationType'))\n", "method_code": "def get_retailer_inventory(token, retailer_id):\n \"\"\"\n Get a retailer from the ERP system.\n\n :param token: The ERP Loopback session token.\n :param retailer_id: The ID of the retailer for which inventory is to be be retrieved.\n\n :return: The retrieved retailer's inventory.\n \"\"\"\n url = '%s/api/v1/Retailers/%s/inventories' % (get_service_url('lw-erp'), str(retailer_id))\n headers = {'cache-control': 'no-cache', 'Authorization': token}\n try:\n response = requests.request('GET', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error retrieving retailer inventory', internal_details=str(e))\n if response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n elif response.status_code == 404:\n raise ResourceDoesNotExistException('Retailer does not exist', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def get_retailer_inventory(token, retailer_id): ...\ndef retailer_to_dict(retailer): ...\ndef get_retailers(token): ...\ndef get_retailer(token, retailer_id): ...\ndef get_retailer_inventory(token, retailer_id): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_get_retailer_inventory_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000883.py"} {"focal_file": "server/services/shipments.py", "focal_class": null, "focal_method": "get_shipments", "tests": "import unittest\n\nclass Test_get_shipments(unittest.TestCase):\n def test_get_shipments_success(self):\n \"\"\"With correct values, are valid shipments returned?\"\"\"\n shipments = shipment_service.get_shipments(self.loopback_token)\n shipments_json = loads(shipments)\n for shipment_json in shipments_json:\n self.assertTrue(shipment_json.get('id'))\n self.assertTrue(shipment_json.get('status'))\n self.assertTrue(shipment_json.get('createdAt'))\n self.assertTrue(shipment_json.get('estimatedTimeOfArrival'))\n self.assertTrue(shipment_json.get('fromId'))\n self.assertTrue(shipment_json.get('toId'))\n if shipment_json.get('currentLocation'):\n self.assertTrue(shipment_json.get('currentLocation').get('city'))\n self.assertTrue(shipment_json.get('currentLocation').get('state'))\n self.assertTrue(shipment_json.get('currentLocation').get('country'))\n self.assertTrue(shipment_json.get('currentLocation').get('latitude'))\n self.assertTrue(shipment_json.get('currentLocation').get('longitude'))\n\n def test_get_shipment_success(self):\n \"\"\"With correct values, is a valid shipment returned?\"\"\"\n shipments = shipment_service.get_shipments(self.loopback_token)\n shipment_id = loads(shipments)[0].get('id')\n shipment = shipment_service.get_shipment(self.loopback_token, shipment_id)\n shipment_json = loads(shipment)\n self.assertTrue(shipment_json.get('id'))\n self.assertTrue(shipment_json.get('status'))\n self.assertTrue(shipment_json.get('createdAt'))\n self.assertTrue(shipment_json.get('estimatedTimeOfArrival'))\n self.assertTrue(shipment_json.get('fromId'))\n self.assertTrue(shipment_json.get('toId'))\n if shipment_json.get('currentLocation'):\n self.assertTrue(shipment_json.get('currentLocation').get('city'))\n self.assertTrue(shipment_json.get('currentLocation').get('state'))\n self.assertTrue(shipment_json.get('currentLocation').get('country'))\n self.assertTrue(shipment_json.get('currentLocation').get('latitude'))\n self.assertTrue(shipment_json.get('currentLocation').get('longitude'))\n for item_json in shipment_json.get('items'):\n self.assertTrue(item_json.get('id'))\n self.assertTrue(item_json.get('shipmentId'))\n self.assertTrue(item_json.get('productId'))\n self.assertTrue(item_json.get('quantity'))\n", "method_code": "def get_shipments(token, retailer_id=None, dc_id=None, status=None):\n \"\"\"\n Get a list of shipments from the ERP system.\n\n :param token: The ERP Loopback session token.\n :param status: Status of the shipments to be retrieved.\n :param retailer_id: Retailer of the shipments to be retrieved.\n :param dc_id: Distribution center of the shipments to be retrieved.\n\n :return: The list of existing shipments.\n \"\"\"\n status_query = ''\n if status is not None:\n status_query = add_query_filter(status_query, 'where', '=', status, property_name='status')\n if retailer_id is not None:\n status_query = add_query_filter(status_query, 'where', '=', retailer_id, property_name='toId')\n if dc_id is not None:\n status_query = add_query_filter(status_query, 'where', '=', dc_id, property_name='fromId')\n url = '%s/api/v1/Shipments%s' % (get_service_url('lw-erp'), status_query)\n headers = {'cache-control': 'no-cache', 'Authorization': token}\n try:\n response = requests.request('GET', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error retrieving shipments', internal_details=str(e))\n if response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def get_shipments(token, retailer_id=None, dc_id=None, status=None): ...\ndef shipment_to_dict(shipment): ...\ndef add_query_filter(cur_query, filter_type, op, value, property_name=None): ...\ndef get_shipments(token, retailer_id=None, dc_id=None, status=None): ...\ndef get_shipment(token, shipment_id, include_items=None): ...\ndef create_shipment(token, shipment): ...\ndef delete_shipment(token, shipment_id): ...\ndef update_shipment(token, shipment_id, shipment): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_get_shipments_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000884.py"} {"focal_file": "server/services/shipments.py", "focal_class": null, "focal_method": "create_shipment", "tests": "import unittest\n\nclass Test_create_shipment(unittest.TestCase):\n def test_create_shipment_success(self):\n \"\"\"With correct values, is a valid shipment created?\"\"\"\n retailers = retailer_service.get_retailers(self.loopback_token)\n distribution_centers = distribution_center_service.get_distribution_centers(self.loopback_token)\n shipment = dict()\n shipment['fromId'] = loads(distribution_centers)[0].get('id')\n shipment['toId'] = loads(retailers)[0].get('id')\n shipment['estimatedTimeOfArrival'] = '2016-07-14'\n created_shipment = shipment_service.create_shipment(self.loopback_token, shipment)\n shipment_json = loads(created_shipment)\n self.assertTrue(shipment_json.get('id'))\n self.assertTrue(shipment_json.get('status'))\n self.assertTrue(shipment_json.get('createdAt'))\n self.assertTrue(shipment_json.get('fromId'))\n self.assertTrue(shipment_json.get('toId'))\n\n def test_create_shipment_invalid_token(self):\n \"\"\"With an invalid token, are correct errors thrown?\"\"\"\n retailers = retailer_service.get_retailers(self.loopback_token)\n distribution_centers = distribution_center_service.get_distribution_centers(self.loopback_token)\n shipment = dict()\n shipment['fromId'] = loads(distribution_centers)[0].get('id')\n shipment['toId'] = loads(retailers)[0].get('id')\n shipment['estimatedTimeOfArrival'] = '2016-07-14'\n created_shipment = shipment_service.create_shipment(self.loopback_token, shipment)\n self.assertRaises(AuthenticationException, shipment_service.create_shipment, utils.get_bad_token(), shipment)\n", "method_code": "def create_shipment(token, shipment):\n \"\"\"\n Create a shipment in the ERP system.\n\n :param token: The ERP Loopback session token.\n :param shipment: The shipment object to be created.\n\n :return: The created shipment.\n \"\"\"\n url = '%s/api/v1/Shipments' % get_service_url('lw-erp')\n headers = {'content-type': 'application/json', 'cache-control': 'no-cache', 'Authorization': token}\n shipment_json = json.dumps(shipment)\n try:\n response = requests.request('POST', url, data=shipment_json, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error creating shipment', internal_details=str(e))\n if response.status_code == 400:\n raise ValidationException('Bad shipment data', internal_details=json.loads(response.text).get('error').get('message'))\n elif response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n elif response.status_code == 422:\n raise UnprocessableEntityException('Required data for shipment is either absent or invalid', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def create_shipment(token, shipment): ...\ndef shipment_to_dict(shipment): ...\ndef add_query_filter(cur_query, filter_type, op, value, property_name=None): ...\ndef get_shipments(token, retailer_id=None, dc_id=None, status=None): ...\ndef get_shipment(token, shipment_id, include_items=None): ...\ndef create_shipment(token, shipment): ...\ndef delete_shipment(token, shipment_id): ...\ndef update_shipment(token, shipment_id, shipment): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_create_shipment_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000885.py"} {"focal_file": "server/services/shipments.py", "focal_class": null, "focal_method": "delete_shipment", "tests": "import unittest\n\nclass Test_delete_shipment(unittest.TestCase):\n def test_delete_shipment_success(self):\n \"\"\"With correct values, is the shipment deleted?\"\"\"\n shipments = shipment_service.get_shipments(self.loopback_token)\n shipment_id = loads(shipments)[0].get('id')\n self.assertTrue(shipment_service.delete_shipment(self.loopback_token, shipment_id) is None)\n", "method_code": "def delete_shipment(token, shipment_id):\n \"\"\"\n Delete a shipment from the ERP system.\n\n :param token: The ERP Loopback session token.\n :param shipment_id: The ID of the shipment to be deleted.\n \"\"\"\n url = '%s/api/v1/Shipments/%s' % (get_service_url('lw-erp'), str(shipment_id))\n headers = {'cache-control': 'no-cache', 'Authorization': token}\n try:\n response = requests.request('DELETE', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error deleting shipment', internal_details=str(e))\n if response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n elif response.status_code == 404:\n raise ResourceDoesNotExistException('Shipment does not exist', internal_details=json.loads(response.text).get('error').get('message'))\n return", "context": "def delete_shipment(token, shipment_id): ...\ndef shipment_to_dict(shipment): ...\ndef add_query_filter(cur_query, filter_type, op, value, property_name=None): ...\ndef get_shipments(token, retailer_id=None, dc_id=None, status=None): ...\ndef get_shipment(token, shipment_id, include_items=None): ...\ndef create_shipment(token, shipment): ...\ndef delete_shipment(token, shipment_id): ...\ndef update_shipment(token, shipment_id, shipment): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_delete_shipment_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000886.py"} {"focal_file": "server/services/shipments.py", "focal_class": null, "focal_method": "update_shipment", "tests": "import unittest\n\nclass Test_update_shipment(unittest.TestCase):\n def test_update_shipment_success(self):\n \"\"\"With correct values, is the shipment updated?\"\"\"\n shipments = shipment_service.get_shipments(self.loopback_token, status=statuses.pop(0))\n shipment_id = loads(shipments)[0].get('id')\n shipment = dict()\n for status in statuses:\n if isinstance(shipment, unicode):\n shipment = loads(shipment)\n shipment['status'] = status\n shipment = shipment_service.update_shipment(self.loopback_token, shipment_id, shipment)\n shipment_json = loads(shipment)\n self.assertTrue(shipment_json.get('id'))\n self.assertTrue(shipment_json.get('status') == status)\n self.assertTrue(shipment_json.get('createdAt'))\n self.assertTrue(shipment_json.get('estimatedTimeOfArrival'))\n self.assertTrue(shipment_json.get('fromId'))\n self.assertTrue(shipment_json.get('toId'))\n if shipment_json.get('currentLocation'):\n self.assertTrue(shipment_json.get('currentLocation').get('city'))\n self.assertTrue(shipment_json.get('currentLocation').get('state'))\n self.assertTrue(shipment_json.get('currentLocation').get('country'))\n self.assertTrue(shipment_json.get('currentLocation').get('latitude'))\n self.assertTrue(shipment_json.get('currentLocation').get('longitude'))\n", "method_code": "def update_shipment(token, shipment_id, shipment):\n \"\"\"\n Update a shipment from the ERP system.\n\n :param token: The ERP Loopback session token.\n :param shipment_id: The ID of the shipment to be retrieved.\n :param shipment: The shipment object with values to update.\n\n :return: The updated shipment.\n \"\"\"\n url = '%s/api/v1/Shipments/%s' % (get_service_url('lw-erp'), str(shipment_id))\n headers = {'cache-control': 'no-cache', 'Authorization': token}\n try:\n response = requests.request('PUT', url, data=shipment, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error updating shipment', internal_details=str(e))\n if response.status_code == 400:\n raise ValidationException('Invalid update to shipment', internal_details=json.loads(response.text).get('error').get('message'))\n elif response.status_code == 401:\n raise AuthenticationException('ERP access denied', internal_details=json.loads(response.text).get('error').get('message'))\n elif response.status_code == 404:\n raise ResourceDoesNotExistException('Shipment does not exist', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def update_shipment(token, shipment_id, shipment): ...\ndef shipment_to_dict(shipment): ...\ndef add_query_filter(cur_query, filter_type, op, value, property_name=None): ...\ndef get_shipments(token, retailer_id=None, dc_id=None, status=None): ...\ndef get_shipment(token, shipment_id, include_items=None): ...\ndef create_shipment(token, shipment): ...\ndef delete_shipment(token, shipment_id): ...\ndef update_shipment(token, shipment_id, shipment): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_update_shipment_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000887.py"} {"focal_file": "server/services/users.py", "focal_class": null, "focal_method": "create_user", "tests": "import unittest\n\nclass Test_create_user(unittest.TestCase):\n def test_user_create_success(self):\n \"\"\"With correct values, is a valid user returned?\"\"\"\n user = user_service.create_user(loads(self.demo).get('guid'), loads(self.retailers)[0].get('id'))\n user_json = loads(user)\n self.assertTrue(user_json.get('id'))\n self.assertTrue(user_json.get('demoId'))\n self.assertTrue(user_json.get('email'))\n self.assertTrue(user_json.get('username'))\n", "method_code": "def create_user(guid, retailer_id):\n \"\"\"\n Create a new user in the ERP system.\n\n :param guid: The demo's guid\n :param retailer_id: Retailer the user will be associated with.\n\n :return: The created User model.\n \"\"\"\n url = '%s/api/v1/Demos/%s/createUser' % (get_service_url('lw-erp'), guid)\n headers = {'content-type': 'application/json', 'cache-control': 'no-cache'}\n payload = dict()\n payload['retailerId'] = int(retailer_id)\n payload_json = json.dumps(payload)\n try:\n response = requests.request('POST', url, data=payload_json, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error creating new user for demo', internal_details=str(e))\n if response.status_code == 404:\n raise ResourceDoesNotExistException('Demo or retailer does not exist', internal_details=json.loads(response.text).get('error').get('message'))\n return response.text", "context": "def create_user(guid, retailer_id): ...\ndef user_to_dict(user): ...\ndef create_user(guid, retailer_id): ...\ndef login(guid, user_id): ...\ndef logout(token): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_user_create_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000888.py"} {"focal_file": "server/services/users.py", "focal_class": null, "focal_method": "logout", "tests": "import unittest\n\nclass Test_logout(unittest.TestCase):\n def test_user_logout_success(self):\n \"\"\"With correct values, is a valid user logged out?\"\"\"\n self.assertTrue(user_service.logout(self.loopback_token) is None)\n", "method_code": "def logout(token):\n \"\"\"\n Log a user out of the system.\n\n :param token: The ERP Loopback session token\n \"\"\"\n url = '%s/api/v1/Users/logout' % get_service_url('lw-erp')\n headers = {'content-type': 'application/json', 'Authorization': token}\n try:\n response = requests.request('POST', url, headers=headers)\n except Exception as e:\n raise APIException('ERP threw error creating new user for demo', internal_details=str(e))\n if response.status_code == 500:\n raise ResourceDoesNotExistException('Session does not exist', internal_details=json.loads(response.text).get('error').get('message'))\n return", "context": "def logout(token): ...\ndef user_to_dict(user): ...\ndef create_user(guid, retailer_id): ...\ndef login(guid, user_id): ...\ndef logout(token): ...\n", "repository": "arnoldst/logistics-wizard-controller1", "test_name": "test_user_logout_success", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000889.py"} {"focal_file": "tests/unittest_modbus.py", "focal_class": null, "focal_method": "_read_out_of_blocks", "tests": "import unittest\n\nclass Test_read_out_of_blocks(unittest.TestCase):\n def testHandleReadCoilsOutOfBlocks(self):\n \"\"\"test that an error response pdu is sent when receiving a pdu for reading coils at an unknown addresses\"\"\"\n self._read_out_of_blocks(modbus_tk.defines.READ_COILS, modbus_tk.defines.COILS)\n", "method_code": " def _read_out_of_blocks(self, function, block_type):\n self._slave.add_block(self._name, block_type, 20, 80)\n list_of_ranges = ((200, 10), (0, 1), (100, 1), (100, 5), (60, 50), (10, 30))\n response = struct.pack('>BB', 128 + function, modbus_tk.defines.ILLEGAL_DATA_ADDRESS)\n for r in list_of_ranges:\n self.assertEqual(response, self._slave.handle_request(struct.pack('>BHH', function, r[0], r[1])))\n ", "context": "class TestSlaveRequestHandler(unittest.TestCase):\n def _read_out_of_blocks(self, function, block_type): ...\n def setUp(self): ...\n def tearDown(self): ...\n def testUnhandledFunction(self): ...\n def _read_digital_data(self, function, block_type): ...\n def _read_continuous_blocks(self, function, block_type): ...\n def testHandleReadCoils(self): ...\n def testHandleReadDigitalInputs(self): ...\n def testHandleReadCoilsOutOfBlocks(self): ...\n def testHandleReadDiscreteInputsOutOfBlocks(self): ...\n def testHandleReadCoilsOnContinuousBlocks(self): ...\n def testHandleReadDiscreteInputsOnContinuousBlocks(self): ...\n def _make_response(self, function, regs): ...\n def _read_registers(self, function, block_type): ...\n def testHandleReadHoldingRegisters(self): ...\n def testHandleReadAnalogInputs(self): ...\n def _read_too_many_registers(self, function, block_type): ...\n def testHandleReadTooManyHoldingRegisters(self): ...\n def testHandleReadTooManyAnalogInputs(self): ...\n def testHandleReadHoldingRegistersOutOfBlocks(self): ...\n def testHandleReadInputRegistersOutOfBlocks(self): ...\n def testHandleReadHoldingRegistersOnContinuousBlocks(self): ...\n def testHandleReadInputregistersOnContinuousBlocks(self): ...\n", "repository": "deathwish88/modbus-tk", "test_name": "testHandleReadCoilsOutOfBlocks", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000890.py"} {"focal_file": "tests/unittest_modbus.py", "focal_class": null, "focal_method": "_read_continuous_blocks", "tests": "import unittest\n\nclass Test_read_continuous_blocks(unittest.TestCase):\n def testHandleReadCoilsOnContinuousBlocks(self):\n \"\"\"test that an error response pdu is sent when receiving a pdu for reading coils at an address shared on distinct blocks\"\"\"\n self._read_continuous_blocks(modbus_tk.defines.READ_COILS, modbus_tk.defines.COILS)\n\n def testHandleReadDiscreteInputsOnContinuousBlocks(self):\n \"\"\"test that an error response pdu is sent when receiving a pdu for reading discrete inputs at an address shared on distinct blocks\"\"\"\n self._read_continuous_blocks(modbus_tk.defines.READ_DISCRETE_INPUTS, modbus_tk.defines.DISCRETE_INPUTS)\n\n def testHandleReadInputregistersOnContinuousBlocks(self):\n \"\"\"test that an error response pdu is sent when receiving a pdu for reading discrete inputs at an address shared on distinct blocks\"\"\"\n self._read_continuous_blocks(modbus_tk.defines.READ_INPUT_REGISTERS, modbus_tk.defines.ANALOG_INPUTS)\n", "method_code": " def _read_continuous_blocks(self, function, block_type):\n self._slave.add_block(self._name + '1', block_type, 0, 20)\n self._slave.add_block(self._name + '2', block_type, 20, 80)\n self._slave.add_block(self._name + '3', block_type, 100, 20)\n list_of_ranges = ((0, 30), (10, 20), (0, 120), (80, 30))\n response = struct.pack('>BB', 128 + function, modbus_tk.defines.ILLEGAL_DATA_ADDRESS)\n for r in list_of_ranges:\n self.assertEqual(response, self._slave.handle_request(struct.pack('>BHH', function, r[0], r[1])))\n ", "context": "class TestSlaveRequestHandler(unittest.TestCase):\n def _read_continuous_blocks(self, function, block_type): ...\n def setUp(self): ...\n def tearDown(self): ...\n def testUnhandledFunction(self): ...\n def _read_digital_data(self, function, block_type): ...\n def _read_out_of_blocks(self, function, block_type): ...\n def testHandleReadCoils(self): ...\n def testHandleReadDigitalInputs(self): ...\n def testHandleReadCoilsOutOfBlocks(self): ...\n def testHandleReadDiscreteInputsOutOfBlocks(self): ...\n def testHandleReadCoilsOnContinuousBlocks(self): ...\n def testHandleReadDiscreteInputsOnContinuousBlocks(self): ...\n def _make_response(self, function, regs): ...\n def _read_registers(self, function, block_type): ...\n def testHandleReadHoldingRegisters(self): ...\n def testHandleReadAnalogInputs(self): ...\n def _read_too_many_registers(self, function, block_type): ...\n def testHandleReadTooManyHoldingRegisters(self): ...\n def testHandleReadTooManyAnalogInputs(self): ...\n def testHandleReadHoldingRegistersOutOfBlocks(self): ...\n def testHandleReadInputRegistersOutOfBlocks(self): ...\n def testHandleReadHoldingRegistersOnContinuousBlocks(self): ...\n def testHandleReadInputregistersOnContinuousBlocks(self): ...\n", "repository": "deathwish88/modbus-tk", "test_name": "testHandleReadCoilsOnContinuousBlocks", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000891.py"} {"focal_file": "tests/unittest_modbus.py", "focal_class": null, "focal_method": "_read_registers", "tests": "import unittest\n\nclass Test_read_registers(unittest.TestCase):\n def testHandleReadHoldingRegisters(self):\n \"\"\"test that the correct response pdu is sent when receiving a pdu for reading holding registers\"\"\"\n self._read_registers(modbus_tk.defines.READ_HOLDING_REGISTERS, modbus_tk.defines.HOLDING_REGISTERS)\n", "method_code": " def _read_registers(self, function, block_type):\n self._slave.add_block(self._name, block_type, 0, 128)\n list_of_regs = ((20, 2, 19, 75, 42), (15,), [11, 12] * 20, range(125), (27,), (1, 2, 3, 4), range(10))\n starting_addresses = (0, 0, 0, 0, 127, 123, 82)\n for i in xrange(len(list_of_regs)):\n self._slave.set_values(self._name, starting_addresses[i], list_of_regs[i])\n self.assertEqual(self._make_response(function, list_of_regs[i]), self._slave.handle_request(struct.pack('>BHH', function, starting_addresses[i], len(list_of_regs[i]))))\n ", "context": "class TestSlaveRequestHandler(unittest.TestCase):\n def _read_registers(self, function, block_type): ...\n def setUp(self): ...\n def tearDown(self): ...\n def testUnhandledFunction(self): ...\n def _read_digital_data(self, function, block_type): ...\n def _read_out_of_blocks(self, function, block_type): ...\n def _read_continuous_blocks(self, function, block_type): ...\n def testHandleReadCoils(self): ...\n def testHandleReadDigitalInputs(self): ...\n def testHandleReadCoilsOutOfBlocks(self): ...\n def testHandleReadDiscreteInputsOutOfBlocks(self): ...\n def testHandleReadCoilsOnContinuousBlocks(self): ...\n def testHandleReadDiscreteInputsOnContinuousBlocks(self): ...\n def _make_response(self, function, regs): ...\n def testHandleReadHoldingRegisters(self): ...\n def testHandleReadAnalogInputs(self): ...\n def _read_too_many_registers(self, function, block_type): ...\n def testHandleReadTooManyHoldingRegisters(self): ...\n def testHandleReadTooManyAnalogInputs(self): ...\n def testHandleReadHoldingRegistersOutOfBlocks(self): ...\n def testHandleReadInputRegistersOutOfBlocks(self): ...\n def testHandleReadHoldingRegistersOnContinuousBlocks(self): ...\n def testHandleReadInputregistersOnContinuousBlocks(self): ...\n", "repository": "deathwish88/modbus-tk", "test_name": "testHandleReadHoldingRegisters", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000892.py"} {"focal_file": "tests/unittest_modbus.py", "focal_class": null, "focal_method": "_read_too_many_registers", "tests": "import unittest\n\nclass Test_read_too_many_registers(unittest.TestCase):\n def testHandleReadTooManyHoldingRegisters(self):\n \"\"\"test that an error is returned when handling a pdu for reading more than 125 holding registers\"\"\"\n self._read_too_many_registers(modbus_tk.defines.READ_HOLDING_REGISTERS, modbus_tk.defines.HOLDING_REGISTERS)\n", "method_code": " def _read_too_many_registers(self, function, block_type):\n self._slave.add_block(self._name, block_type, 0, 128)\n self._slave.set_values(self._name, 0, range(128))\n response = struct.pack('>BB', function + 128, modbus_tk.defines.ILLEGAL_DATA_VALUE)\n self.assertEqual(response, self._slave.handle_request(struct.pack('>BHH', function, 0, 126)))\n ", "context": "class TestSlaveRequestHandler(unittest.TestCase):\n def _read_too_many_registers(self, function, block_type): ...\n def setUp(self): ...\n def tearDown(self): ...\n def testUnhandledFunction(self): ...\n def _read_digital_data(self, function, block_type): ...\n def _read_out_of_blocks(self, function, block_type): ...\n def _read_continuous_blocks(self, function, block_type): ...\n def testHandleReadCoils(self): ...\n def testHandleReadDigitalInputs(self): ...\n def testHandleReadCoilsOutOfBlocks(self): ...\n def testHandleReadDiscreteInputsOutOfBlocks(self): ...\n def testHandleReadCoilsOnContinuousBlocks(self): ...\n def testHandleReadDiscreteInputsOnContinuousBlocks(self): ...\n def _make_response(self, function, regs): ...\n def _read_registers(self, function, block_type): ...\n def testHandleReadHoldingRegisters(self): ...\n def testHandleReadAnalogInputs(self): ...\n def testHandleReadTooManyHoldingRegisters(self): ...\n def testHandleReadTooManyAnalogInputs(self): ...\n def testHandleReadHoldingRegistersOutOfBlocks(self): ...\n def testHandleReadInputRegistersOutOfBlocks(self): ...\n def testHandleReadHoldingRegistersOnContinuousBlocks(self): ...\n def testHandleReadInputregistersOnContinuousBlocks(self): ...\n", "repository": "deathwish88/modbus-tk", "test_name": "testHandleReadTooManyHoldingRegisters", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000893.py"} {"focal_file": "gopher/eventprocessor.py", "focal_class": "EventConsumer", "focal_method": "consume", "tests": "import unittest\n\nclass Test_EventConsumer_consume(unittest.TestCase):\n def test_get_data_after_consume(self):\n ec = EventConsumer()\n input_value = random.random()\n ec.consume(input_value)\n output_value = ec.get_data()\n self.assertEqual(input_value, output_value)\n", "method_code": " def consume(self, data):\n self.queue.put(data)\n ", "context": "class EventConsumer(object):\n def consume(self, data): ...\n def __init__(self): ...\n def get_data(self): ...\n\n self.queue = queue.Queue()\n", "repository": "lfalvarez/ratadns-gopher", "test_name": "test_get_data_after_consume", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000894.py"} {"focal_file": "lambda_dd_metrics.py", "focal_class": null, "focal_method": "incr", "tests": "import unittest\n\nclass Test_incr(unittest.TestCase):\n def test_incr(self):\n mock_time.return_value = float(1234)\n dd = DataDogMetrics('test')\n actual = dd.incr('test_metric')\n expected = 'MONITORING|1234|1|count|test.test_metric'\n self.assertEqual(expected, actual)\n", "method_code": " def incr(self, metric_name, count=1, tags=None):\n \"\"\"\n Incr - Increment a counter metric, providing a count of occurrences per\n second.\n \"\"\"\n full_metric_name = self._build_metric_name(metric_name)\n all_tags = self._build_tags(tags)\n return self._print_metric('count', full_metric_name, count, all_tags)\n ", "context": "class DataDogMetrics(object):\n def incr(self, metric_name, count=1, tags=None): ...\n def __init__(self, service_prefix, stats_group=None): ...\n def gauge(self, metric_name, value, tags=None): ...\n def histogram(self, metric_name, value, tags=None): ...\n def timer(self, metric_name, tags=None): ...\n def timing(self, metric_name, delta, tags=None): ...\n def set(self, metric_name, value, tags=None): ...\n def _build_tags(self, tags=None): ...\n def _build_metric_name(self, metric_name): ...\n def _print_metric(self, metric_type, metric_name, value, tags): ...\n\n self.service_prefix = service_prefix\n self.default_tags = ['group:%s' % stats_group] if stats_group is not None else []\n", "repository": "500px/lambda_dd_metrics", "test_name": "test_incr", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000895.py"} {"focal_file": "lambda_dd_metrics.py", "focal_class": null, "focal_method": "gauge", "tests": "import unittest\n\nclass Test_gauge(unittest.TestCase):\n def test_gauge(self):\n mock_time.return_value = float(1234)\n dd = DataDogMetrics('test')\n actual = dd.gauge('test_metric', 1)\n expected = 'MONITORING|1234|1|gauge|test.test_metric'\n self.assertEqual(expected, actual)\n", "method_code": " def gauge(self, metric_name, value, tags=None):\n \"\"\"\n Gauge - Gauges are a constant data type. They are not subject to\n averaging, and they don't change unless you change them. That is, once\n you set a gauge value, it will be a flat line on the graph until you\n change it again.\n \"\"\"\n full_metric_name = self._build_metric_name(metric_name)\n all_tags = self._build_tags(tags)\n return self._print_metric('gauge', full_metric_name, value, all_tags)\n ", "context": "class DataDogMetrics(object):\n def gauge(self, metric_name, value, tags=None): ...\n def __init__(self, service_prefix, stats_group=None): ...\n def incr(self, metric_name, count=1, tags=None): ...\n def histogram(self, metric_name, value, tags=None): ...\n def timer(self, metric_name, tags=None): ...\n def timing(self, metric_name, delta, tags=None): ...\n def set(self, metric_name, value, tags=None): ...\n def _build_tags(self, tags=None): ...\n def _build_metric_name(self, metric_name): ...\n def _print_metric(self, metric_type, metric_name, value, tags): ...\n\n self.service_prefix = service_prefix\n self.default_tags = ['group:%s' % stats_group] if stats_group is not None else []\n", "repository": "500px/lambda_dd_metrics", "test_name": "test_gauge", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000896.py"} {"focal_file": "lambda_dd_metrics.py", "focal_class": null, "focal_method": "histogram", "tests": "import unittest\n\nclass Test_histogram(unittest.TestCase):\n def test_histogram(self):\n mock_time.return_value = float(1234)\n dd = DataDogMetrics('test')\n actual = dd.histogram('test_metric', 1)\n expected = 'MONITORING|1234|1|histogram|test.test_metric'\n self.assertEqual(expected, actual)\n", "method_code": " def histogram(self, metric_name, value, tags=None):\n \"\"\"\n Histogram - Send a histogram, tracking multiple samples of a metric\n \"\"\"\n full_metric_name = self._build_metric_name(metric_name)\n all_tags = self._build_tags(tags)\n return self._print_metric('histogram', full_metric_name, value, all_tags)\n ", "context": "class DataDogMetrics(object):\n def histogram(self, metric_name, value, tags=None): ...\n def __init__(self, service_prefix, stats_group=None): ...\n def incr(self, metric_name, count=1, tags=None): ...\n def gauge(self, metric_name, value, tags=None): ...\n def timer(self, metric_name, tags=None): ...\n def timing(self, metric_name, delta, tags=None): ...\n def set(self, metric_name, value, tags=None): ...\n def _build_tags(self, tags=None): ...\n def _build_metric_name(self, metric_name): ...\n def _print_metric(self, metric_type, metric_name, value, tags): ...\n\n self.service_prefix = service_prefix\n self.default_tags = ['group:%s' % stats_group] if stats_group is not None else []\n", "repository": "500px/lambda_dd_metrics", "test_name": "test_histogram", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000897.py"} {"focal_file": "lambda_dd_metrics.py", "focal_class": null, "focal_method": "timer", "tests": "import unittest\n\nclass Test_timer(unittest.TestCase):\n def test_timer(self):\n mock_time.side_effect = [float(100), float(200), float(1234)]\n dd = DataDogMetrics('test')\n mock_histogram = dd.histogram = MagicMock(wraps=dd.histogram)\n dd.timer('test_metric')(lambda x: x)('echo')\n actual_call = mock_histogram.call_args\n expected_call = call('test_metric', float(100), None)\n self.assertEqual(expected_call, actual_call)\n", "method_code": " def timer(self, metric_name, tags=None):\n \"\"\"\n Timer - A convenient decorator that automatically records the runtime\n of your function and reports it as a histogram.\n \"\"\"\n \n def decorator(function):\n \n @wraps(function)\n def wrapper(*args, **kwargs):\n start_time = time.time()\n ret_val = function(*args, **kwargs)\n duration = time.time() - start_time\n self.histogram(metric_name, duration, tags)\n return ret_val\n return wrapper\n return decorator\n ", "context": "class DataDogMetrics(object):\n def timer(self, metric_name, tags=None): ...\n def __init__(self, service_prefix, stats_group=None): ...\n def incr(self, metric_name, count=1, tags=None): ...\n def gauge(self, metric_name, value, tags=None): ...\n def histogram(self, metric_name, value, tags=None): ...\n def timing(self, metric_name, delta, tags=None): ...\n def set(self, metric_name, value, tags=None): ...\n def _build_tags(self, tags=None): ...\n def _build_metric_name(self, metric_name): ...\n def _print_metric(self, metric_type, metric_name, value, tags): ...\n\n self.service_prefix = service_prefix\n self.default_tags = ['group:%s' % stats_group] if stats_group is not None else []\n", "repository": "500px/lambda_dd_metrics", "test_name": "test_timer", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000898.py"} {"focal_file": "minigalaxy/api.py", "focal_class": "Api", "focal_method": "get_login_url", "tests": "import unittest\n\nclass Test_Api_get_login_url(unittest.TestCase):\n def test_get_login_url(self):\n api = Api()\n exp = 'https://auth.gog.com/auth?client_id=46899977096215655&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&response_type=code&layout=client2'\n obs = api.get_login_url()\n self.assertEqual(exp, obs)\n", "method_code": " def get_login_url(self) -> str:\n params = {'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'response_type': 'code', 'layout': 'client2'}\n return 'https://auth.gog.com/auth?' + urlencode(params)\n ", "context": "class Api():\n def get_login_url(self) -> str: ...\n def __init__(self): ...\n def authenticate(self, login_code: str=None, refresh_token: str=None) -> str: ...\n def __refresh_token(self, refresh_token: str) -> str: ...\n def __get_token(self, login_code: str) -> str: ...\n def __get_refresh_token(self, params: dict) -> str: ...\n def get_library(self): ...\n def get_owned_products_ids(self): ...\n def get_redirect_url(self) -> str: ...\n def get_info(self, game: Game) -> dict: ...\n def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict: ...\n def get_real_download_link(self, url): ...\n def get_download_file_md5(self, url): ...\n def get_file_size(self, url): ...\n def get_user_info(self) -> str: ...\n def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str: ...\n def can_connect() -> bool: ...\n def __request(self, url: str=None, params: dict=None) -> dict: ...\n def __request_gamesdb(game: Game): ...\n def get_gamesdb_info(self, game: Game) -> dict: ...\n\n self.login_success_url = 'https://embed.gog.com/on_login_success'\n self.redirect_uri = 'https://embed.gog.com/on_login_success?origin=client'\n self.client_id = '46899977096215655'\n self.client_secret = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'\n self.debug = os.environ.get('MG_DEBUG')\n self.active_token = False\n self.active_token_expiration_time = time.time()\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_get_login_url", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000899.py"} {"focal_file": "minigalaxy/api.py", "focal_class": "Api", "focal_method": "get_redirect_url", "tests": "import unittest\n\nclass Test_Api_get_redirect_url(unittest.TestCase):\n def test_get_redirect_url(self):\n api = Api()\n exp = 'https://embed.gog.com/on_login_success?origin=client'\n obs = api.get_redirect_url()\n self.assertEqual(exp, obs)\n", "method_code": " def get_redirect_url(self) -> str:\n return self.redirect_uri\n ", "context": "class Api():\n def get_redirect_url(self) -> str: ...\n def __init__(self): ...\n def authenticate(self, login_code: str=None, refresh_token: str=None) -> str: ...\n def __refresh_token(self, refresh_token: str) -> str: ...\n def __get_token(self, login_code: str) -> str: ...\n def __get_refresh_token(self, params: dict) -> str: ...\n def get_library(self): ...\n def get_owned_products_ids(self): ...\n def get_login_url(self) -> str: ...\n def get_info(self, game: Game) -> dict: ...\n def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict: ...\n def get_real_download_link(self, url): ...\n def get_download_file_md5(self, url): ...\n def get_file_size(self, url): ...\n def get_user_info(self) -> str: ...\n def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str: ...\n def can_connect() -> bool: ...\n def __request(self, url: str=None, params: dict=None) -> dict: ...\n def __request_gamesdb(game: Game): ...\n def get_gamesdb_info(self, game: Game) -> dict: ...\n\n self.login_success_url = 'https://embed.gog.com/on_login_success'\n self.redirect_uri = 'https://embed.gog.com/on_login_success?origin=client'\n self.client_id = '46899977096215655'\n self.client_secret = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'\n self.debug = os.environ.get('MG_DEBUG')\n self.active_token = False\n self.active_token_expiration_time = time.time()\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_get_redirect_url", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000900.py"} {"focal_file": "minigalaxy/api.py", "focal_class": "Api", "focal_method": "can_connect", "tests": "import unittest\n\nclass Test_Api_can_connect(unittest.TestCase):\n def test1_can_connect(self):\n api = Api()\n m_constants.return_value = True\n exp = True\n obs = api.can_connect()\n self.assertEqual(exp, obs)\n\n def test2_can_connect(self):\n api = Api()\n m_constants.SESSION.get.side_effect = requests.exceptions.ConnectionError(mock.Mock(status='Connection Error'))\n exp = False\n obs = api.can_connect()\n self.assertEqual(exp, obs)\n", "method_code": " def can_connect() -> bool:\n url = 'https://embed.gog.com'\n try:\n SESSION.get(url, timeout=5)\n except requests.exceptions.ConnectionError:\n return False\n return True\n ", "context": "class Api():\n @staticmethod\n def can_connect() -> bool: ...\n def __init__(self): ...\n def authenticate(self, login_code: str=None, refresh_token: str=None) -> str: ...\n def __refresh_token(self, refresh_token: str) -> str: ...\n def __get_token(self, login_code: str) -> str: ...\n def __get_refresh_token(self, params: dict) -> str: ...\n def get_library(self): ...\n def get_owned_products_ids(self): ...\n def get_login_url(self) -> str: ...\n def get_redirect_url(self) -> str: ...\n def get_info(self, game: Game) -> dict: ...\n def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict: ...\n def get_real_download_link(self, url): ...\n def get_download_file_md5(self, url): ...\n def get_file_size(self, url): ...\n def get_user_info(self) -> str: ...\n def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str: ...\n def __request(self, url: str=None, params: dict=None) -> dict: ...\n def __request_gamesdb(game: Game): ...\n def get_gamesdb_info(self, game: Game) -> dict: ...\n\n self.login_success_url = 'https://embed.gog.com/on_login_success'\n self.redirect_uri = 'https://embed.gog.com/on_login_success?origin=client'\n self.client_id = '46899977096215655'\n self.client_secret = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'\n self.debug = os.environ.get('MG_DEBUG')\n self.active_token = False\n self.active_token_expiration_time = time.time()\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_can_connect", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000901.py"} {"focal_file": "minigalaxy/api.py", "focal_class": "Api", "focal_method": "get_download_info", "tests": "import unittest\n\nclass Test_Api_get_download_info(unittest.TestCase):\n def test1_get_download_info(self):\n api = Api()\n api.get_info = MagicMock()\n api.get_info.return_value = API_GET_INFO_TOONSTRUCK\n m_config.Config.get.return_value = 'pl'\n test_game = Game('Test Game')\n exp = {'id': 'installer_linux_en', 'name': 'Toonstruck', 'os': 'linux', 'language': 'en', 'language_full': 'English', 'version': 'gog-2', 'total_size': 963641344, 'files': [{'id': 'en3installer0', 'size': 963641344, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/en3installer0'}]}\n obs = api.get_download_info(test_game)\n self.assertEqual(exp, obs)\n\n def test2_get_download_info(self):\n api = Api()\n api.get_info = MagicMock()\n api.get_info.return_value = API_GET_INFO_TOONSTRUCK\n m_config.Config.get.return_value = 'fr'\n test_game = Game('Test Game')\n exp = {'id': 'installer_linux_fr', 'name': 'Toonstruck', 'os': 'linux', 'language': 'fr', 'language_full': 'français', 'version': 'gog-2', 'total_size': 1011875840, 'files': [{'id': 'fr3installer0', 'size': 1011875840, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/fr3installer0'}]}\n obs = api.get_download_info(test_game)\n self.assertEqual(exp, obs)\n\n def test3_get_download_info(self):\n api = Api()\n api.get_info = MagicMock()\n api.get_info.return_value = {'downloads': {'installers': [{'id': 'installer_windows_en', 'name': 'Toonstruck', 'os': 'windows', 'language': 'en', 'language_full': 'English', 'version': '1.0', 'total_size': 939524096, 'files': [{'id': 'en1installer0', 'size': 1048576, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/en1installer0'}, {'id': 'en1installer1', 'size': 938475520, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/en1installer1'}]}, {'id': 'installer_mac_en', 'name': 'Toonstruck', 'os': 'mac', 'language': 'en', 'language_full': 'English', 'version': 'gog-3', 'total_size': 975175680, 'files': [{'id': 'en2installer0', 'size': 975175680, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/en2installer0'}]}, {'id': 'installer_windows_fr', 'name': 'Toonstruck', 'os': 'windows', 'language': 'fr', 'language_full': 'français', 'version': '1.0', 'total_size': 985661440, 'files': [{'id': 'fr1installer0', 'size': 1048576, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/fr1installer0'}, {'id': 'fr1installer1', 'size': 984612864, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/fr1installer1'}]}, {'id': 'installer_mac_fr', 'name': 'Toonstruck', 'os': 'mac', 'language': 'fr', 'language_full': 'français', 'version': 'gog-3', 'total_size': 1023410176, 'files': [{'id': 'fr2installer0', 'size': 1023410176, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/fr2installer0'}]}]}}\n m_config.Config.get.return_value = 'en'\n test_game = Game('Test Game')\n exp = {'id': 'installer_windows_en', 'name': 'Toonstruck', 'os': 'windows', 'language': 'en', 'language_full': 'English', 'version': '1.0', 'total_size': 939524096, 'files': [{'id': 'en1installer0', 'size': 1048576, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/en1installer0'}, {'id': 'en1installer1', 'size': 938475520, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/en1installer1'}]}\n obs = api.get_download_info(test_game)\n self.assertEqual(exp, obs)\n\n def test4_get_download_info(self):\n api = Api()\n dlc_test_installer = API_GET_INFO_TOONSTRUCK['downloads']['installers']\n m_config.Config.get.return_value = 'en'\n test_game = Game('Test Game')\n exp = {'id': 'installer_linux_en', 'name': 'Toonstruck', 'os': 'linux', 'language': 'en', 'language_full': 'English', 'version': 'gog-2', 'total_size': 963641344, 'files': [{'id': 'en3installer0', 'size': 963641344, 'downlink': 'https://api.gog.com/products/1207666633/downlink/installer/en3installer0'}]}\n obs = api.get_download_info(test_game, dlc_installers=dlc_test_installer)\n self.assertEqual(exp, obs)\n", "method_code": " def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict:\n if dlc_installers:\n installers = dlc_installers\n else:\n response = self.get_info(game)\n installers = response['downloads']['installers']\n possible_downloads = []\n for installer in installers:\n if installer['os'] == operating_system:\n possible_downloads.append(installer)\n if not possible_downloads:\n if operating_system == 'linux':\n return self.get_download_info(game, 'windows')\n else:\n raise NoDownloadLinkFound(\"Error: {} with id {} couldn't be installed\".format(game.name, game.id))\n download_info = possible_downloads[0]\n for installer in possible_downloads:\n if installer['language'] == Config.get('lang'):\n download_info = installer\n break\n if installer['language'] == 'en':\n download_info = installer\n return download_info\n ", "context": "class Api():\n def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict: ...\n def __init__(self): ...\n def authenticate(self, login_code: str=None, refresh_token: str=None) -> str: ...\n def __refresh_token(self, refresh_token: str) -> str: ...\n def __get_token(self, login_code: str) -> str: ...\n def __get_refresh_token(self, params: dict) -> str: ...\n def get_library(self): ...\n def get_owned_products_ids(self): ...\n def get_login_url(self) -> str: ...\n def get_redirect_url(self) -> str: ...\n def get_info(self, game: Game) -> dict: ...\n def get_real_download_link(self, url): ...\n def get_download_file_md5(self, url): ...\n def get_file_size(self, url): ...\n def get_user_info(self) -> str: ...\n def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str: ...\n def can_connect() -> bool: ...\n def __request(self, url: str=None, params: dict=None) -> dict: ...\n def __request_gamesdb(game: Game): ...\n def get_gamesdb_info(self, game: Game) -> dict: ...\n\n self.login_success_url = 'https://embed.gog.com/on_login_success'\n self.redirect_uri = 'https://embed.gog.com/on_login_success?origin=client'\n self.client_id = '46899977096215655'\n self.client_secret = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'\n self.debug = os.environ.get('MG_DEBUG')\n self.active_token = False\n self.active_token_expiration_time = time.time()\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_get_download_info", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000902.py"} {"focal_file": "minigalaxy/api.py", "focal_class": "Api", "focal_method": "get_library", "tests": "import unittest\n\nclass Test_Api_get_library(unittest.TestCase):\n def test1_get_library(self):\n api = Api()\n api.active_token = True\n response_dict = {'totalPages': 1, 'products': [{'id': 1097893768, 'title': 'Neverwinter Nights: Enhanced Edition', 'image': '//images-2.gog-statics.com/8706f7fb87a4a41bc34254f3b49f59f96cf13d067b2c8bbfd8d41c327392052a', 'url': '/game/neverwinter_nights_enhanced_edition_pack', 'worksOn': {'Windows': True, 'Mac': True, 'Linux': True}}]}\n api.active_token_expiration_time = time.time() + 10.0\n response_mock = MagicMock()\n response_mock.json.return_value = response_dict\n m_constants.SESSION.get.return_value = response_mock\n exp = 'Neverwinter Nights: Enhanced Edition'\n retrieved_games, err_msg = api.get_library()\n obs = retrieved_games[0].name\n self.assertEqual(exp, obs)\n\n def test2_get_library(self):\n api = Api()\n api.active_token = False\n api.active_token_expiration_time = time.time() + 10.0\n response_mock = MagicMock()\n response_mock.json.return_value = {}\n m_constants.SESSION.get.return_value = response_mock\n exp = \"Couldn't connect to GOG servers\"\n retrieved_games, obs = api.get_library()\n self.assertEqual(exp, obs)\n", "method_code": " def get_library(self):\n err_msg = ''\n games = []\n if self.active_token:\n current_page = 1\n all_pages_processed = False\n url = 'https://embed.gog.com/account/getFilteredProducts'\n while not all_pages_processed:\n params = {'mediaType': 1, 'page': current_page}\n response = self.__request(url, params=params)\n total_pages = response['totalPages']\n for product in response['products']:\n if product['id'] not in IGNORE_GAME_IDS:\n if product['worksOn']['Linux']:\n platform = 'linux'\n elif Config.get('show_windows_games'):\n platform = 'windows'\n else:\n continue\n if not product['url']:\n print('{} ({}) has no store page url'.format(product['title'], product['id']))\n game = Game(name=product['title'], url=product['url'], game_id=product['id'], image_url=product['image'], platform=platform)\n games.append(game)\n if current_page == total_pages:\n all_pages_processed = True\n current_page += 1\n else:\n err_msg = \"Couldn't connect to GOG servers\"\n return (games, err_msg)\n ", "context": "class Api():\n def get_library(self): ...\n def __init__(self): ...\n def authenticate(self, login_code: str=None, refresh_token: str=None) -> str: ...\n def __refresh_token(self, refresh_token: str) -> str: ...\n def __get_token(self, login_code: str) -> str: ...\n def __get_refresh_token(self, params: dict) -> str: ...\n def get_owned_products_ids(self): ...\n def get_login_url(self) -> str: ...\n def get_redirect_url(self) -> str: ...\n def get_info(self, game: Game) -> dict: ...\n def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict: ...\n def get_real_download_link(self, url): ...\n def get_download_file_md5(self, url): ...\n def get_file_size(self, url): ...\n def get_user_info(self) -> str: ...\n def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str: ...\n def can_connect() -> bool: ...\n def __request(self, url: str=None, params: dict=None) -> dict: ...\n def __request_gamesdb(game: Game): ...\n def get_gamesdb_info(self, game: Game) -> dict: ...\n\n self.login_success_url = 'https://embed.gog.com/on_login_success'\n self.redirect_uri = 'https://embed.gog.com/on_login_success?origin=client'\n self.client_id = '46899977096215655'\n self.client_secret = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'\n self.debug = os.environ.get('MG_DEBUG')\n self.active_token = False\n self.active_token_expiration_time = time.time()\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_get_library", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000903.py"} {"focal_file": "minigalaxy/api.py", "focal_class": "Api", "focal_method": "get_version", "tests": "import unittest\n\nclass Test_Api_get_version(unittest.TestCase):\n def test1_get_version(self):\n api = Api()\n test_game = Game('Test Game', platform='linux')\n exp = 'gog-2'\n obs = api.get_version(test_game, gameinfo=API_GET_INFO_TOONSTRUCK)\n self.assertEqual(exp, obs)\n\n def test2_get_version(self):\n api = Api()\n test_game = Game('Test Game', platform='linux')\n dlc_name = 'Test DLC'\n game_info = API_GET_INFO_TOONSTRUCK\n game_info['expanded_dlcs'] = [{'title': dlc_name, 'downloads': {'installers': [{'os': 'linux', 'version': '1.2.3.4'}]}}]\n exp = '1.2.3.4'\n obs = api.get_version(test_game, gameinfo=API_GET_INFO_TOONSTRUCK, dlc_name=dlc_name)\n self.assertEqual(exp, obs)\n", "method_code": " def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str:\n if gameinfo is None:\n gameinfo = self.get_info(game)\n version = '0'\n if dlc_name:\n installers = {}\n for dlc in gameinfo['expanded_dlcs']:\n if dlc['title'] == dlc_name:\n installers = dlc['downloads']['installers']\n break\n else:\n installers = gameinfo['downloads']['installers']\n for installer in installers:\n if installer['os'] == game.platform:\n version = installer['version']\n break\n return version\n ", "context": "class Api():\n def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str: ...\n def __init__(self): ...\n def authenticate(self, login_code: str=None, refresh_token: str=None) -> str: ...\n def __refresh_token(self, refresh_token: str) -> str: ...\n def __get_token(self, login_code: str) -> str: ...\n def __get_refresh_token(self, params: dict) -> str: ...\n def get_library(self): ...\n def get_owned_products_ids(self): ...\n def get_login_url(self) -> str: ...\n def get_redirect_url(self) -> str: ...\n def get_info(self, game: Game) -> dict: ...\n def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict: ...\n def get_real_download_link(self, url): ...\n def get_download_file_md5(self, url): ...\n def get_file_size(self, url): ...\n def get_user_info(self) -> str: ...\n def can_connect() -> bool: ...\n def __request(self, url: str=None, params: dict=None) -> dict: ...\n def __request_gamesdb(game: Game): ...\n def get_gamesdb_info(self, game: Game) -> dict: ...\n\n self.login_success_url = 'https://embed.gog.com/on_login_success'\n self.redirect_uri = 'https://embed.gog.com/on_login_success?origin=client'\n self.client_id = '46899977096215655'\n self.client_secret = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'\n self.debug = os.environ.get('MG_DEBUG')\n self.active_token = False\n self.active_token_expiration_time = time.time()\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_get_version", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000904.py"} {"focal_file": "minigalaxy/api.py", "focal_class": "Api", "focal_method": "get_download_file_md5", "tests": "import unittest\n\nclass Test_Api_get_download_file_md5(unittest.TestCase):\n def test_get_download_file_md5(self):\n api = Api()\n api._Api__request = MagicMock()\n m_constants.SESSION.get.side_effect = MagicMock()\n m_constants.SESSION.get().text = '\\n 7e62ce101221ccdae2e9bff5c16ed9e0\\n b80960a2546ce647bffea87f85385535\\n 5464b4499cd4368bb83ea35f895d3560\\n 0261b9225fc10c407df083f6d254c47b\\n'\n exp = '8acedf66c0d2986e7dee9af912b7df4f'\n obs = api.get_download_file_md5('url')\n self.assertEqual(exp, obs)\n", "method_code": " def get_download_file_md5(self, url):\n xml_link = self.__request(url)['checksum']\n xml_string = SESSION.get(xml_link).text\n root = ET.fromstring(xml_string)\n return root.attrib['md5']\n ", "context": "class Api():\n def get_download_file_md5(self, url): ...\n def __init__(self): ...\n def authenticate(self, login_code: str=None, refresh_token: str=None) -> str: ...\n def __refresh_token(self, refresh_token: str) -> str: ...\n def __get_token(self, login_code: str) -> str: ...\n def __get_refresh_token(self, params: dict) -> str: ...\n def get_library(self): ...\n def get_owned_products_ids(self): ...\n def get_login_url(self) -> str: ...\n def get_redirect_url(self) -> str: ...\n def get_info(self, game: Game) -> dict: ...\n def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict: ...\n def get_real_download_link(self, url): ...\n def get_file_size(self, url): ...\n def get_user_info(self) -> str: ...\n def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str: ...\n def can_connect() -> bool: ...\n def __request(self, url: str=None, params: dict=None) -> dict: ...\n def __request_gamesdb(game: Game): ...\n def get_gamesdb_info(self, game: Game) -> dict: ...\n\n self.login_success_url = 'https://embed.gog.com/on_login_success'\n self.redirect_uri = 'https://embed.gog.com/on_login_success?origin=client'\n self.client_id = '46899977096215655'\n self.client_secret = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'\n self.debug = os.environ.get('MG_DEBUG')\n self.active_token = False\n self.active_token_expiration_time = time.time()\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_get_download_file_md5", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000905.py"} {"focal_file": "minigalaxy/api.py", "focal_class": "Api", "focal_method": "get_gamesdb_info", "tests": "import unittest\n\nclass Test_Api_get_gamesdb_info(unittest.TestCase):\n def test1_get_gamesdb_info(self):\n api = Api()\n api._Api__request_gamesdb = MagicMock()\n api._Api__request_gamesdb.side_effect = [{}]\n test_game = Game('Test Game')\n exp = {'cover': '', 'vertical_cover': '', 'background': '', 'genre': {}, 'summary': {}}\n obs = api.get_gamesdb_info(test_game)\n self.assertEqual(exp, obs)\n\n def test2_get_gamesdb_info(self):\n api = Api()\n api._Api__request_gamesdb = MagicMock()\n api._Api__request_gamesdb.side_effect = [{'id': '51622789000874509', 'game_id': '51154268886064420', 'platform_id': 'gog', 'external_id': '1508702879', 'game': {'genres': [{'id': '51071904337940794', 'name': {'*': 'Strategy', 'en-US': 'Strategy'}, 'slug': 'strategy'}], 'summary': {'*': 'Stellaris description'}, 'visible_in_library': True, 'aggregated_rating': 78.5455, 'game_modes': [{'id': '53051895165351137', 'name': 'Single player', 'slug': 'single-player'}, {'id': '53051908711988230', 'name': 'Multiplayer', 'slug': 'multiplayer'}], 'horizontal_artwork': {'url_format': 'https://images.gog.com/742acfb77ec51ca48c9f96947bf1fc0ad8f0551c9c9f338021e8baa4f08e449f{formatter}.{ext}?namespace=gamesdb'}, 'background': {'url_format': 'https://images.gog.com/742acfb77ec51ca48c9f96947bf1fc0ad8f0551c9c9f338021e8baa4f08e449f{formatter}.{ext}?namespace=gamesdb'}, 'vertical_cover': {'url_format': 'https://images.gog.com/8d822a05746670fb2540e9c136f0efaed6a2d5ab698a9f8bd7f899d21f2022d2{formatter}.{ext}?namespace=gamesdb'}, 'cover': {'url_format': 'https://images.gog.com/8d822a05746670fb2540e9c136f0efaed6a2d5ab698a9f8bd7f899d21f2022d2{formatter}.{ext}?namespace=gamesdb'}, 'logo': {'url_format': 'https://images.gog.com/c50a5d26c42d84b4b884976fb89d10bb3e97ebda0c0450285d92b8c50844d788{formatter}.{ext}?namespace=gamesdb'}, 'icon': {'url_format': 'https://images.gog.com/c85cf82e6019dd52fcdf1c81d17687dd52807835f16aa938abd2a34e5d9b99d0{formatter}.{ext}?namespace=gamesdb'}, 'square_icon': {'url_format': 'https://images.gog.com/c3adc81bf37f1dd89c9da74c13967a08b9fd031af4331750dbc65ab0243493c8{formatter}.{ext}?namespace=gamesdb'}}}]\n test_game = Game('Stellaris')\n exp = {'cover': 'https://images.gog.com/8d822a05746670fb2540e9c136f0efaed6a2d5ab698a9f8bd7f899d21f2022d2.png?namespace=gamesdb', 'vertical_cover': 'https://images.gog.com/8d822a05746670fb2540e9c136f0efaed6a2d5ab698a9f8bd7f899d21f2022d2.png?namespace=gamesdb', 'background': 'https://images.gog.com/742acfb77ec51ca48c9f96947bf1fc0ad8f0551c9c9f338021e8baa4f08e449f.png?namespace=gamesdb', 'summary': {'*': 'Stellaris description'}, 'genre': {'*': 'Strategy', 'en-US': 'Strategy'}}\n obs = api.get_gamesdb_info(test_game)\n self.assertEqual(exp, obs)\n", "method_code": " def get_gamesdb_info(self, game: Game) -> dict:\n gamesdb_dict = {'cover': '', 'vertical_cover': '', 'background': ''}\n response_json = self.__request_gamesdb(game)\n if 'game' in response_json:\n for gamesdb_key in gamesdb_dict:\n if gamesdb_key in response_json['game']:\n gamesdb_dict[gamesdb_key] = response_json['game'][gamesdb_key]['url_format'].replace('{formatter}.{ext}', '.png')\n gamesdb_dict['summary'] = {}\n for summary_key in response_json['game']['summary']:\n gamesdb_dict['summary'][summary_key] = response_json['game']['summary'][summary_key]\n gamesdb_dict['genre'] = {}\n for genre_key in response_json['game']['genres'][0]['name']:\n gamesdb_dict['genre'][genre_key] = response_json['game']['genres'][0]['name'][genre_key]\n else:\n gamesdb_dict['summary'] = {}\n gamesdb_dict['genre'] = {}\n return gamesdb_dict\n ", "context": "class Api():\n def get_gamesdb_info(self, game: Game) -> dict: ...\n def __init__(self): ...\n def authenticate(self, login_code: str=None, refresh_token: str=None) -> str: ...\n def __refresh_token(self, refresh_token: str) -> str: ...\n def __get_token(self, login_code: str) -> str: ...\n def __get_refresh_token(self, params: dict) -> str: ...\n def get_library(self): ...\n def get_owned_products_ids(self): ...\n def get_login_url(self) -> str: ...\n def get_redirect_url(self) -> str: ...\n def get_info(self, game: Game) -> dict: ...\n def get_download_info(self, game: Game, operating_system='linux', dlc_installers='') -> dict: ...\n def get_real_download_link(self, url): ...\n def get_download_file_md5(self, url): ...\n def get_file_size(self, url): ...\n def get_user_info(self) -> str: ...\n def get_version(self, game: Game, gameinfo=None, dlc_name='') -> str: ...\n def can_connect() -> bool: ...\n def __request(self, url: str=None, params: dict=None) -> dict: ...\n def __request_gamesdb(game: Game): ...\n\n self.login_success_url = 'https://embed.gog.com/on_login_success'\n self.redirect_uri = 'https://embed.gog.com/on_login_success?origin=client'\n self.client_id = '46899977096215655'\n self.client_secret = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'\n self.debug = os.environ.get('MG_DEBUG')\n self.active_token = False\n self.active_token_expiration_time = time.time()\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_get_gamesdb_info", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000906.py"} {"focal_file": "minigalaxy/download.py", "focal_class": "Download", "focal_method": "set_progress", "tests": "import unittest\n\nclass Test_Download_set_progress(unittest.TestCase):\n def test1_set_progress(self):\n mock_progress_function = MagicMock()\n download = Download('test_url', 'test_save_location', progress_func=mock_progress_function)\n download.set_progress(50)\n kall = mock_progress_function.mock_calls[-1]\n name, args, kwargs = kall\n exp = 50\n obs = args[0]\n self.assertEqual(exp, obs)\n\n def test2_set_progress(self):\n mock_progress_function = MagicMock()\n download = Download('test_url', 'test_save_location', progress_func=mock_progress_function, out_of_amount=2)\n download.set_progress(32)\n kall = mock_progress_function.mock_calls[-1]\n name, args, kwargs = kall\n exp = 16\n obs = args[0]\n self.assertEqual(exp, obs)\n", "method_code": " def set_progress(self, percentage: int) -> None:\n if self.__progress_func:\n if self.out_of_amount > 1:\n progress_start = 100 / self.out_of_amount * (self.number - 1)\n percentage = progress_start + percentage / self.out_of_amount\n percentage = int(percentage)\n self.__progress_func(percentage)\n ", "context": "class Download():\n def set_progress(self, percentage: int) -> None: ...\n def __init__(self, url, save_location, finish_func=None, progress_func=None, cancel_func=None, number=1, out_of_amount=1): ...\n def finish(self): ...\n def cancel(self): ...\n\n self.url = url\n self.save_location = save_location\n self.__finish_func = finish_func\n self.__progress_func = progress_func\n self.__cancel_func = cancel_func\n self.number = number\n self.out_of_amount = out_of_amount\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_set_progress", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000907.py"} {"focal_file": "minigalaxy/download.py", "focal_class": "Download", "focal_method": "finish", "tests": "import unittest\n\nclass Test_Download_finish(unittest.TestCase):\n def test1_finish(self):\n mock_finish_function = MagicMock()\n download = Download('test_url', 'test_save_location', finish_func=mock_finish_function)\n download.finish()\n exp = 2\n obs = len(mock_finish_function.mock_calls)\n self.assertEqual(exp, obs)\n\n def test2_finish(self):\n mock_finish_function = MagicMock()\n mock_finish_function.side_effect = FileNotFoundError(Mock(status='Connection Error'))\n mock_cancel_function = MagicMock()\n download = Download('test_url', 'test_save_location', finish_func=mock_finish_function, cancel_func=mock_cancel_function)\n download.finish()\n exp = 2\n obs = len(mock_cancel_function.mock_calls)\n self.assertEqual(exp, obs)\n", "method_code": " def finish(self):\n if self.__finish_func:\n try:\n self.__finish_func()\n except (FileNotFoundError, BadZipFile):\n self.cancel()\n ", "context": "class Download():\n def finish(self): ...\n def __init__(self, url, save_location, finish_func=None, progress_func=None, cancel_func=None, number=1, out_of_amount=1): ...\n def set_progress(self, percentage: int) -> None: ...\n def cancel(self): ...\n\n self.url = url\n self.save_location = save_location\n self.__finish_func = finish_func\n self.__progress_func = progress_func\n self.__cancel_func = cancel_func\n self.number = number\n self.out_of_amount = out_of_amount\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_finish", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000908.py"} {"focal_file": "minigalaxy/download.py", "focal_class": "Download", "focal_method": "cancel", "tests": "import unittest\n\nclass Test_Download_cancel(unittest.TestCase):\n def test_cancel(self):\n mock_cancel_function = MagicMock()\n download = Download('test_url', 'test_save_location', cancel_func=mock_cancel_function)\n download.cancel()\n exp = 2\n obs = len(mock_cancel_function.mock_calls)\n self.assertEqual(exp, obs)\n", "method_code": " def cancel(self):\n if self.__cancel_func:\n self.__cancel_func()\n ", "context": "class Download():\n def cancel(self): ...\n def __init__(self, url, save_location, finish_func=None, progress_func=None, cancel_func=None, number=1, out_of_amount=1): ...\n def set_progress(self, percentage: int) -> None: ...\n def finish(self): ...\n\n self.url = url\n self.save_location = save_location\n self.__finish_func = finish_func\n self.__progress_func = progress_func\n self.__cancel_func = cancel_func\n self.number = number\n self.out_of_amount = out_of_amount\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_cancel", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000909.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "is_update_available", "tests": "import unittest\n\nclass Test_Game_is_update_available(unittest.TestCase):\n def test1_is_update_available(self):\n game = Game('Version Test game')\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {'version': 'gog-2'}\n expected = True\n observed = game.is_update_available('gog-3')\n self.assertEqual(expected, observed)\n\n def test2_is_update_available(self):\n game = Game('Version Test game')\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {'version': '91.8193.16'}\n expected = False\n observed = game.is_update_available('91.8193.16')\n self.assertEqual(expected, observed)\n\n def test3_is_update_available(self):\n game = Game('Version Test game')\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {'version': '91.8193.16', 'dlcs': {'Neverwinter Nights: Wyvern Crown of Cormyr': {'version': '82.8193.20.1'}}}\n expected = True\n observed = game.is_update_available('91.8193.16', dlc_title='Neverwinter Nights: Wyvern Crown of Cormyr')\n self.assertEqual(expected, observed)\n\n def test4_is_update_available(self):\n game = Game('Version Test game')\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {'version': '91.8193.16', 'dlcs': {'Neverwinter Nights: Wyvern Crown of Cormyr': {'version': '82.8193.20.1'}}}\n expected = False\n observed = game.is_update_available('82.8193.20.1', dlc_title='Neverwinter Nights: Wyvern Crown of Cormyr')\n self.assertEqual(expected, observed)\n", "method_code": " def is_update_available(self, version_from_api, dlc_title='') -> bool:\n update_available = False\n if dlc_title:\n installed_version = self.get_dlc_info('version', dlc_title)\n else:\n installed_version = self.get_info('version')\n if not installed_version:\n installed_version = self.fallback_read_installed_version()\n self.set_info('version', installed_version)\n if installed_version and version_from_api and (version_from_api != installed_version):\n update_available = True\n return update_available\n ", "context": "class Game():\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_is_update_available", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000910.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "get_install_directory_name", "tests": "import unittest\n\nclass Test_Game_get_install_directory_name(unittest.TestCase):\n def test1_get_install_directory_name(self):\n game = Game('Get Install Directory Test1')\n expected = 'Get Install Directory Test1'\n observed = game.get_install_directory_name()\n self.assertEqual(expected, observed)\n\n def test2_get_install_directory_name(self):\n game = Game('Get\\r Install\\n Directory Test2!@#$%')\n expected = 'Get Install Directory Test2'\n observed = game.get_install_directory_name()\n self.assertEqual(expected, observed)\n", "method_code": " def get_install_directory_name(self):\n return re.sub('[^A-Za-z0-9 ]+', '', self.name)\n ", "context": "class Game():\n def get_install_directory_name(self): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_get_install_directory_name", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000911.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "fallback_read_installed_version", "tests": "import unittest\n\nclass Test_Game_fallback_read_installed_version(unittest.TestCase):\n @unittest.mock.patch('os.path.isfile')\n def test1_fallback_read_installed_version(self, mock_isfile):\n mock_isfile.return_value = True\n gameinfo = 'Beneath A Steel Sky\\ngog-2\\n20150\\nen-US\\n1207658695\\n1207658695\\n664777434'\n game = Game('Game Name test1')\n expected = 'gog-2'\n with patch('builtins.open', mock_open(read_data=gameinfo)):\n observed = game.fallback_read_installed_version()\n self.assertEqual(expected, observed)\n\n @unittest.mock.patch('os.path.isfile')\n def test2_fallback_read_installed_version(self, mock_isfile):\n mock_isfile.return_value = False\n gameinfo = 'Beneath A Steel Sky\\n gog-2\\n 20150\\n en-US\\n 1207658695\\n 1207658695\\n 664777434'\n game = Game('Game Name test2')\n expected = '0'\n with patch('builtins.open', mock_open(read_data=gameinfo)):\n observed = game.fallback_read_installed_version()\n self.assertEqual(expected, observed)\n", "method_code": " def fallback_read_installed_version(self):\n gameinfo = os.path.join(self.install_dir, 'gameinfo')\n gameinfo_list = []\n if os.path.isfile(gameinfo):\n with open(gameinfo, 'r') as file:\n gameinfo_list = file.readlines()\n if len(gameinfo_list) > 1:\n version = gameinfo_list[1].strip()\n else:\n version = '0'\n return version\n ", "context": "class Game():\n def fallback_read_installed_version(self): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000912.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "set_info", "tests": "import unittest\n\nclass Test_Game_set_info(unittest.TestCase):\n @unittest.mock.patch('os.path.isfile')\n def test1_set_info(self, mock_isfile):\n mock_isfile.return_value = True\n json_content = '{\"version\": \"gog-2\"}'\n with patch('builtins.open', mock_open(read_data=json_content)) as m:\n game = Game('Game Name test2')\n game.set_info('version', 'gog-3')\n mock_c = m.mock_calls\n write_string = ''\n for kall in mock_c:\n name, args, kwargs = kall\n if name == '().write':\n write_string = '{}{}'.format(write_string, args[0])\n expected = '{\"version\": \"gog-3\"}'\n observed = write_string\n self.assertEqual(expected, observed)\n", "method_code": " def set_info(self, key, value):\n json_dict = self.load_minigalaxy_info_json()\n json_dict[key] = value\n self.save_minigalaxy_info_json(json_dict)\n ", "context": "class Game():\n def set_info(self, key, value): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000913.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "set_dlc_info", "tests": "import unittest\n\nclass Test_Game_set_dlc_info(unittest.TestCase):\n @unittest.mock.patch('os.path.isfile')\n def test2_set_dlc_info(self, mock_isfile):\n mock_isfile.return_value = False\n dlc_name = 'Neverwinter Nights: Wyvern Crown of Cormyr'\n with patch('builtins.open', mock_open()) as m:\n game = Game('Neverwinter Nights')\n game.set_dlc_info('version', '82.8193.20.1', dlc_name)\n mock_c = m.mock_calls\n write_string = ''\n for kall in mock_c:\n name, args, kwargs = kall\n if name == '().write':\n write_string = '{}{}'.format(write_string, args[0])\n expected = '{\"dlcs\": {\"Neverwinter Nights: Wyvern Crown of Cormyr\": {\"version\": \"82.8193.20.1\"}}}'\n observed = write_string\n self.assertEqual(expected, observed)\n", "method_code": " def set_dlc_info(self, key, value, dlc_title):\n json_dict = self.load_minigalaxy_info_json()\n if 'dlcs' not in json_dict:\n json_dict['dlcs'] = {}\n if dlc_title not in json_dict['dlcs']:\n json_dict['dlcs'][dlc_title] = {}\n json_dict['dlcs'][dlc_title][key] = value\n self.save_minigalaxy_info_json(json_dict)\n ", "context": "class Game():\n def set_dlc_info(self, key, value, dlc_title): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000914.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "get_stripped_name", "tests": "import unittest\n\nclass Test_Game_get_stripped_name(unittest.TestCase):\n def test_get_stripped_name(self):\n name_string = 'Beneath A Steel Sky'\n game = Game(name_string)\n expected = 'BeneathASteelSky'\n observed = game.get_stripped_name()\n self.assertEqual(expected, observed)\n", "method_code": " def get_stripped_name(self):\n return self.__strip_string(self.name)\n ", "context": "class Game():\n def get_stripped_name(self): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_get_stripped_name", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000915.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "load_minigalaxy_info_json", "tests": "import unittest\n\nclass Test_Game_load_minigalaxy_info_json(unittest.TestCase):\n @unittest.mock.patch('os.path.isfile')\n def test1_load_minigalaxy_info_json(self, mock_isfile):\n mock_isfile.side_effect = [True]\n json_content = '{\"version\": \"gog-2\"}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test2')\n jscon_dict = game.load_minigalaxy_info_json()\n expected = {'version': 'gog-2'}\n observed = jscon_dict\n self.assertEqual(expected, observed)\n\n @unittest.mock.patch('os.path.isfile')\n def test2_load_minigalaxy_info_json(self, mock_isfile):\n mock_isfile.side_effect = [False]\n json_content = '{\"version\": \"gog-2\"}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test2')\n jscon_dict = game.load_minigalaxy_info_json()\n expected = {}\n observed = jscon_dict\n self.assertEqual(expected, observed)\n", "method_code": " def load_minigalaxy_info_json(self):\n json_dict = {}\n if os.path.isfile(self.status_file_path):\n with open(self.status_file_path, 'r') as status_file:\n json_dict = json.load(status_file)\n return json_dict\n ", "context": "class Game():\n def load_minigalaxy_info_json(self): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000916.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "save_minigalaxy_info_json", "tests": "import unittest\n\nclass Test_Game_save_minigalaxy_info_json(unittest.TestCase):\n @unittest.mock.patch('minigalaxy.config.Config')\n def test_save_minigalaxy_info_json(self, mock_config):\n json_dict = {'version': 'gog-2'}\n with patch('builtins.open', mock_open()) as m:\n game = Game('Neverwinter Nights')\n game.save_minigalaxy_info_json(json_dict)\n mock_c = m.mock_calls\n write_string = ''\n for kall in mock_c:\n name, args, kwargs = kall\n if name == '().write':\n write_string = '{}{}'.format(write_string, args[0])\n expected = '{\"version\": \"gog-2\"}'\n observed = write_string\n self.assertEqual(expected, observed)\n", "method_code": " def save_minigalaxy_info_json(self, json_dict):\n if not os.path.exists(CONFIG_GAMES_DIR):\n os.makedirs(CONFIG_GAMES_DIR, mode=493)\n with open(self.status_file_path, 'w') as status_file:\n json.dump(json_dict, status_file)\n ", "context": "class Game():\n def save_minigalaxy_info_json(self, json_dict): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000917.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "is_installed", "tests": "import unittest\n\nclass Test_Game_is_installed(unittest.TestCase):\n @unittest.mock.patch('os.path.exists')\n def test1_is_installed(self, mock_isfile):\n mock_isfile.side_effect = [False]\n game = Game('Game Name Test')\n game.load_minigalaxy_info_json = MagicMock()\n exp = False\n obs = game.is_installed()\n self.assertEqual(exp, obs)\n\n @unittest.mock.patch('os.path.exists')\n def test2_is_installed(self, mock_isfile):\n mock_isfile.side_effect = [True]\n game = Game('Game Name Test', install_dir='Test Install Dir')\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {'dlcs': {'Neverwinter Nights: Wyvern Crown of Cormyr': {'version': '82.8193.20.1'}}}\n exp = True\n obs = game.is_installed(dlc_title='Neverwinter Nights: Wyvern Crown of Cormyr')\n self.assertEqual(exp, obs)\n\n @unittest.mock.patch('os.path.exists')\n def test3_is_installed(self, mock_isfile):\n mock_isfile.side_effect = [True]\n game = Game('Game Name Test', install_dir='Test Install Dir')\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {'dlcs': {'Neverwinter Nights: Wyvern Crown of Cormyr': {'version': '82.8193.20.1'}}}\n game.legacy_get_dlc_status = MagicMock()\n game.legacy_get_dlc_status.return_value = 'not-installed'\n exp = False\n obs = game.is_installed(dlc_title='Not Present DLC')\n self.assertEqual(exp, obs)\n", "method_code": " def is_installed(self, dlc_title='') -> bool:\n installed = False\n if dlc_title:\n dlc_version = self.get_dlc_info('version', dlc_title)\n installed = bool(dlc_version)\n elif self.install_dir and os.path.exists(self.install_dir):\n installed = True\n return installed\n ", "context": "class Game():\n def is_installed(self, dlc_title='') -> bool: ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000918.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "get_info", "tests": "import unittest\n\nclass Test_Game_get_info(unittest.TestCase):\n @unittest.mock.patch('os.path.isfile')\n def test_get_info(self, mock_isfile):\n mock_isfile.side_effect = [True]\n json_content = '{\"example_key\": \"example_value\"}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test')\n game_get_status = game.get_info('example_key')\n expected = 'example_value'\n observed = game_get_status\n self.assertEqual(expected, observed)\n\n @unittest.mock.patch('os.path.isfile')\n def test1_get_info_legacy(self, mock_isfile):\n mock_isfile.side_effect = [False, True]\n json_content = '{\"example_key\": \"example_value\"}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test')\n game.set_info = MagicMock()\n game_get_status = game.get_info('example_key')\n expected = 'example_value'\n observed = game_get_status\n self.assertEqual(expected, observed)\n\n @unittest.mock.patch('os.path.isfile')\n def test2_get_info_legacy(self, mock_isfile):\n mock_isfile.side_effect = [True, True]\n json_content = '{\"example_key\": \"example_value\"}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test')\n game.set_info = MagicMock()\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {}\n game_get_status = game.get_info('example_key')\n expected = 'example_value'\n observed = game_get_status\n self.assertEqual(expected, observed)\n\n @unittest.mock.patch('os.path.isfile')\n def test3_get_info_legacy(self, mock_isfile):\n mock_isfile.side_effect = [True, True]\n json_content = '{\"example_key\": \"example_value_legacy\"}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test')\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {'example_key': 'example_value'}\n game_get_status = game.get_info('example_key')\n expected = 'example_value'\n observed = game_get_status\n self.assertEqual(expected, observed)\n", "method_code": " def get_info(self, key):\n value = ''\n json_dict = self.load_minigalaxy_info_json()\n if key in json_dict:\n value = json_dict[key]\n elif os.path.isfile(os.path.join(self.install_dir, 'minigalaxy-info.json')):\n with open(os.path.join(self.install_dir, 'minigalaxy-info.json'), 'r') as status_file:\n json_dict = json.load(status_file)\n if key in json_dict:\n value = json_dict[key]\n self.set_info(key, value)\n return value\n ", "context": "class Game():\n def get_info(self, key): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_dlc_info(self, key, dlc_title): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000919.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "get_dlc_info", "tests": "import unittest\n\nclass Test_Game_get_dlc_info(unittest.TestCase):\n @unittest.mock.patch('os.path.isfile')\n def test_get_dlc_info(self, mock_isfile):\n mock_isfile.side_effect = [True, False]\n json_content = '{\"dlcs\": {\"example_dlc\" : {\"example_key\": \"example_value\"}}}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test')\n game_get_status = game.get_dlc_info('example_key', 'example_dlc')\n expected = 'example_value'\n observed = game_get_status\n self.assertEqual(expected, observed)\n\n @unittest.mock.patch('os.path.isfile')\n def test1_get_dlc_info_legacy(self, mock_isfile):\n mock_isfile.side_effect = [False, True]\n json_content = '{\"dlcs\": {\"example_dlc\" : {\"example_key\": \"example_value\"}}}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test')\n game.set_dlc_info = MagicMock()\n game_get_status = game.get_dlc_info('example_key', 'example_dlc')\n expected = 'example_value'\n observed = game_get_status\n self.assertEqual(expected, observed)\n\n @unittest.mock.patch('os.path.isfile')\n def test2_get_dlc_info_legacy(self, mock_isfile):\n mock_isfile.side_effect = [True, True]\n json_content = '{\"dlcs\": {\"example_dlc\" : {\"example_key\": \"example_value\"}}}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test')\n game.set_dlc_info = MagicMock()\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {}\n game_get_status = game.get_dlc_info('example_key', 'example_dlc')\n expected = 'example_value'\n observed = game_get_status\n self.assertEqual(expected, observed)\n\n @unittest.mock.patch('os.path.isfile')\n def test3_get_dlc_info_legacy(self, mock_isfile):\n mock_isfile.side_effect = [True, True]\n json_content = '{\"dlcs\": {\"example_dlc\" : {\"example_key\": \"example_value_legacy\"}}}'\n with patch('builtins.open', mock_open(read_data=json_content)):\n game = Game('Game Name test')\n game.load_minigalaxy_info_json = MagicMock()\n game.load_minigalaxy_info_json.return_value = {'dlcs': {'example_dlc': {'example_key': 'example_value'}}}\n game_get_status = game.get_dlc_info('example_key', 'example_dlc')\n expected = 'example_value'\n observed = game_get_status\n self.assertEqual(expected, observed)\n", "method_code": " def get_dlc_info(self, key, dlc_title):\n value = ''\n json_dict = self.load_minigalaxy_info_json()\n if 'dlcs' in json_dict:\n if dlc_title in json_dict['dlcs']:\n if key in json_dict['dlcs'][dlc_title]:\n value = json_dict['dlcs'][dlc_title][key]\n if os.path.isfile(os.path.join(self.install_dir, 'minigalaxy-info.json')) and (not value):\n with open(os.path.join(self.install_dir, 'minigalaxy-info.json'), 'r') as status_file:\n json_dict = json.load(status_file)\n if 'dlcs' in json_dict:\n if dlc_title in json_dict['dlcs']:\n if key in json_dict['dlcs'][dlc_title]:\n value = json_dict['dlcs'][dlc_title][key]\n self.set_dlc_info(key, value, dlc_title)\n return value\n ", "context": "class Game():\n def get_dlc_info(self, key, dlc_title): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def set_install_dir(self): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000920.py"} {"focal_file": "minigalaxy/game.py", "focal_class": "Game", "focal_method": "set_install_dir", "tests": "import unittest\n\nclass Test_Game_set_install_dir(unittest.TestCase):\n def test_set_install_dir(self):\n install_directory = '/home/user/GOG Games'\n install_game_name = 'Neverwinter Nights'\n m_config.Config.get.return_value = install_directory\n game = Game(install_game_name)\n game.set_install_dir()\n exp = os.path.join(install_directory, install_game_name)\n obs = game.install_dir\n self.assertEqual(exp, obs)\n", "method_code": " def set_install_dir(self):\n if not self.install_dir:\n self.install_dir = os.path.join(Config.get('install_dir'), self.get_install_directory_name())\n ", "context": "class Game():\n def set_install_dir(self): ...\n def __init__(self, name: str, url: str='', md5sum=None, game_id: int=0, install_dir: str='', image_url='', platform='linux', dlcs=None): ...\n def get_stripped_name(self): ...\n def get_install_directory_name(self): ...\n def load_minigalaxy_info_json(self): ...\n def save_minigalaxy_info_json(self, json_dict): ...\n def __strip_string(string): ...\n def is_installed(self, dlc_title='') -> bool: ...\n def is_update_available(self, version_from_api, dlc_title='') -> bool: ...\n def fallback_read_installed_version(self): ...\n def set_info(self, key, value): ...\n def set_dlc_info(self, key, value, dlc_title): ...\n def get_info(self, key): ...\n def get_dlc_info(self, key, dlc_title): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n\n self.name = name\n self.url = url\n self.md5sum = {} if md5sum is None else md5sum\n self.id = game_id\n self.install_dir = install_dir\n self.image_url = image_url\n self.platform = platform\n self.dlcs = [] if dlcs is None else dlcs\n self.status_file_name = '{}.json'.format(self.get_install_directory_name())\n self.status_file_path = os.path.join(CONFIG_GAMES_DIR, self.status_file_name)\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_set_install_dir", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000921.py"} {"focal_file": "minigalaxy/config.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n @mock.patch('os.path.exists')\n def test_get(self, mock_isfile):\n mock_isfile.return_value = True\n config = JSON_DEFAULT_CONFIGURATION\n with patch('builtins.open', mock_open(read_data=config)):\n from minigalaxy.config import Config\n Config.first_run = True\n Config._Config__config = DEFAULT_CONFIGURATION\n lang = Config.get('lang')\n exp = 'en'\n obs = lang\n self.assertEqual(exp, obs)\n", "method_code": " def get(self, key):\n self.first_run_init()\n try:\n return self.__config[key]\n except KeyError:\n return None\n ", "context": "class __Config():\n def get(self, key): ...\n def __init__(self): ...\n def first_run_init(self): ...\n def __keep_config_synced(self): ...\n def __load_config_file(self) -> dict: ...\n def __create_config_file(self) -> dict: ...\n def __update_config_file(self): ...\n def __add_missing_config_entries(self): ...\n def set(self, key, value): ...\n def unset(self, key): ...\n\n self.first_run = False\n self.__config = {}\n self.__config_file = CONFIG_FILE_PATH\n self.__update_required = False\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000922.py"} {"focal_file": "minigalaxy/config.py", "focal_class": null, "focal_method": "set", "tests": "import unittest\n\nclass Test_set(unittest.TestCase):\n @mock.patch('os.path.exists')\n def test_set(self, mock_isfile):\n mock_isfile.return_value = True\n config = JSON_DEFAULT_CONFIGURATION\n with patch('builtins.open', mock_open(read_data=config)):\n from minigalaxy.config import Config\n Config.first_run = True\n Config.set('lang', 'pl')\n lang = Config.get('lang')\n exp = 'pl'\n obs = lang\n self.assertEqual(exp, obs)\n", "method_code": " def set(self, key, value):\n self.first_run_init()\n self.__config[key] = value\n self.__update_required = True\n ", "context": "class __Config():\n def set(self, key, value): ...\n def __init__(self): ...\n def first_run_init(self): ...\n def __keep_config_synced(self): ...\n def __load_config_file(self) -> dict: ...\n def __create_config_file(self) -> dict: ...\n def __update_config_file(self): ...\n def __add_missing_config_entries(self): ...\n def get(self, key): ...\n def unset(self, key): ...\n\n self.first_run = False\n self.__config = {}\n self.__config_file = CONFIG_FILE_PATH\n self.__update_required = False\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000923.py"} {"focal_file": "minigalaxy/config.py", "focal_class": null, "focal_method": "unset", "tests": "import unittest\n\nclass Test_unset(unittest.TestCase):\n @mock.patch('os.path.exists')\n def test_unset(self, mock_isfile):\n mock_isfile.return_value = True\n config = JSON_DEFAULT_CONFIGURATION\n with patch('builtins.open', mock_open(read_data=config)):\n from minigalaxy.config import Config\n Config.first_run = True\n Config.unset('lang')\n lang = Config.get('lang')\n exp = None\n obs = lang\n self.assertEqual(exp, obs)\n", "method_code": " def unset(self, key):\n self.first_run_init()\n try:\n del self.__config[key]\n self.__update_required = True\n except KeyError:\n pass\n ", "context": "class __Config():\n def unset(self, key): ...\n def __init__(self): ...\n def first_run_init(self): ...\n def __keep_config_synced(self): ...\n def __load_config_file(self) -> dict: ...\n def __create_config_file(self) -> dict: ...\n def __update_config_file(self): ...\n def __add_missing_config_entries(self): ...\n def set(self, key, value): ...\n def get(self, key): ...\n\n self.first_run = False\n self.__config = {}\n self.__config_file = CONFIG_FILE_PATH\n self.__update_required = False\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000924.py"} {"focal_file": "minigalaxy/installer.py", "focal_class": null, "focal_method": "verify_installer_integrity", "tests": "import unittest\n\nclass Test_verify_installer_integrity(unittest.TestCase):\n @mock.patch('os.path.exists')\n @mock.patch('hashlib.md5')\n @mock.patch('os.listdir')\n def test1_verify_installer_integrity(self, mock_listdir, mock_hash, mock_is_file):\n md5_sum = '5cc68247b61ba31e37e842fd04409d98'\n installer_name = 'beneath_a_steel_sky_en_gog_2_20150.sh'\n mock_is_file.return_value = True\n mock_hash().hexdigest.return_value = md5_sum\n mock_listdir.return_value = [installer_name]\n game = Game('Beneath A Steel Sky', install_dir='/home/makson/GOG Games/Beneath a Steel Sky', md5sum={installer_name: md5_sum})\n installer_path = '/home/user/.cache/minigalaxy/download/Beneath a Steel Sky/{}'.format(installer_name)\n exp = ''\n with patch('builtins.open', mock_open(read_data=b'')):\n obs = installer.verify_installer_integrity(game, installer_path)\n self.assertEqual(exp, obs)\n\n @mock.patch('os.path.exists')\n @mock.patch('hashlib.md5')\n @mock.patch('os.listdir')\n def test2_verify_installer_integrity(self, mock_listdir, mock_hash, mock_is_file):\n md5_sum = '5cc68247b61ba31e37e842fd04409d98'\n installer_name = 'beneath_a_steel_sky_en_gog_2_20150.sh'\n corrupted_md5_sum = '99999947b61ba31e37e842fd04409d98'\n mock_is_file.return_value = True\n mock_hash().hexdigest.return_value = corrupted_md5_sum\n mock_listdir.return_value = [installer_name]\n game = Game('Beneath A Steel Sky', install_dir='/home/makson/GOG Games/Beneath a Steel Sky', md5sum={installer_name: md5_sum})\n installer_path = '/home/user/.cache/minigalaxy/download/Beneath a Steel Sky/{}'.format(installer_name)\n exp = _('{} was corrupted. Please download it again.').format(installer_name)\n with patch('builtins.open', mock_open(read_data=b'aaaa')):\n obs = installer.verify_installer_integrity(game, installer_path)\n self.assertEqual(exp, obs)\n", "method_code": "def verify_installer_integrity(game, installer):\n error_message = ''\n if not os.path.exists(installer):\n error_message = _('{} failed to download.').format(installer)\n if not error_message:\n for installer_file_name in os.listdir(os.path.dirname(installer)):\n hash_md5 = hashlib.md5()\n with open(os.path.join(os.path.dirname(installer), installer_file_name), 'rb') as installer_file:\n for chunk in iter(lambda: installer_file.read(4096), b''):\n hash_md5.update(chunk)\n calculated_checksum = hash_md5.hexdigest()\n if installer_file_name in game.md5sum:\n if game.md5sum[installer_file_name] == calculated_checksum:\n print('{} integrity is preserved. MD5 is: {}'.format(installer_file_name, calculated_checksum))\n else:\n error_message = _('{} was corrupted. Please download it again.').format(installer_file_name)\n break\n else:\n print('Warning. No info about correct {} MD5 checksum'.format(installer_file_name))\n return error_message", "context": "def verify_installer_integrity(game, installer): ...\ndef get_available_disk_space(location): ...\ndef get_game_size_from_unzip(installer): ...\ndef check_diskspace(required_size, location): ...\ndef install_game(game, installer): ...\ndef verify_installer_integrity(game, installer): ...\ndef verify_disk_space(game, installer): ...\ndef make_tmp_dir(game): ...\ndef extract_installer(game, installer, temp_dir): ...\ndef move_and_overwrite(game, temp_dir, target_dir): ...\ndef copy_thumbnail(game): ...\ndef remove_installer(installer): ...\ndef uninstall_game(game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000925.py"} {"focal_file": "minigalaxy/installer.py", "focal_class": null, "focal_method": "extract_installer", "tests": "import unittest\n\nclass Test_extract_installer(unittest.TestCase):\n @mock.patch('os.path.exists')\n @mock.patch('os.listdir')\n @mock.patch('subprocess.Popen')\n def test1_extract_installer(self, mock_subprocess, mock_listdir, mock_is_file):\n mock_is_file.return_value = True\n mock_subprocess().returncode = 0\n mock_subprocess().communicate.return_value = [b'stdout', b'stderr']\n mock_listdir.return_value = ['object1', 'object2']\n game = Game('Beneath A Steel Sky', install_dir='/home/makson/GOG Games/Beneath a Steel Sky')\n installer_path = '/home/makson/.cache/minigalaxy/download/Beneath a Steel Sky/beneath_a_steel_sky_en_gog_2_20150.sh'\n temp_dir = '/home/makson/.cache/minigalaxy/extract/1207658695'\n exp = ''\n obs = installer.extract_installer(game, installer_path, temp_dir)\n self.assertEqual(exp, obs)\n\n @mock.patch('os.path.exists')\n @mock.patch('os.listdir')\n @mock.patch('subprocess.Popen')\n def test2_extract_installer(self, mock_subprocess, mock_listdir, mock_is_file):\n mock_is_file.return_value = True\n mock_subprocess().returncode = 2\n mock_subprocess().communicate.return_value = [b'stdout', b'stderr']\n mock_listdir.return_value = ['object1', 'object2']\n game = Game('Beneath A Steel Sky', install_dir='/home/makson/GOG Games/Beneath a Steel Sky')\n installer_path = '/home/makson/.cache/minigalaxy/download/Beneath a Steel Sky/beneath_a_steel_sky_en_gog_2_20150.sh'\n temp_dir = '/home/makson/.cache/minigalaxy/extract/1207658695'\n exp = 'The installation of /home/makson/.cache/minigalaxy/download/Beneath a Steel Sky/beneath_a_steel_sky_en_gog_2_20150.sh failed. Please try again.'\n obs = installer.extract_installer(game, installer_path, temp_dir)\n self.assertEqual(exp, obs)\n", "method_code": "def extract_installer(game, installer, temp_dir):\n error_message = ''\n if game.platform == 'linux':\n command = ['unzip', '-qq', installer, '-d', temp_dir]\n else:\n prefix_dir = os.path.join(game.install_dir, 'prefix')\n if not os.path.exists(prefix_dir):\n os.makedirs(prefix_dir, mode=493)\n command = ['env', 'WINEPREFIX={}'.format(prefix_dir), 'wine', installer, '/dir={}'.format(temp_dir), '/VERYSILENT']\n process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n process.wait()\n stdout, stderr = process.communicate()\n stdout = stdout.decode('utf-8')\n stderr = stderr.decode('utf-8')\n if process.returncode not in [0, 1] or (process.returncode in [1] and '(attempting to process anyway)' not in stderr):\n error_message = _('The installation of {} failed. Please try again.').format(installer)\n elif len(os.listdir(temp_dir)) == 0:\n error_message = _('{} could not be unzipped.'.format(installer))\n return error_message", "context": "def extract_installer(game, installer, temp_dir): ...\ndef get_available_disk_space(location): ...\ndef get_game_size_from_unzip(installer): ...\ndef check_diskspace(required_size, location): ...\ndef install_game(game, installer): ...\ndef verify_installer_integrity(game, installer): ...\ndef verify_disk_space(game, installer): ...\ndef make_tmp_dir(game): ...\ndef extract_installer(game, installer, temp_dir): ...\ndef move_and_overwrite(game, temp_dir, target_dir): ...\ndef copy_thumbnail(game): ...\ndef remove_installer(installer): ...\ndef uninstall_game(game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000926.py"} {"focal_file": "minigalaxy/installer.py", "focal_class": null, "focal_method": "get_available_disk_space", "tests": "import unittest\n\nclass Test_get_available_disk_space(unittest.TestCase):\n @mock.patch('os.statvfs')\n def test_get_availablediskspace(self, mock_os_statvfs):\n frsize = 4096\n bavail = 29699296\n mock_os_statvfs().f_frsize = frsize\n mock_os_statvfs().f_bavail = bavail\n exp = frsize * bavail\n obs = installer.get_available_disk_space('/')\n self.assertEqual(exp, obs)\n", "method_code": "def get_available_disk_space(location):\n \"\"\"Check disk space available to the user. This method uses the absolute path so\n symlinks to disks with sufficient space are correctly measured. Note this is\n a linux-specific command.\"\"\"\n absolute_location = os.path.realpath(location)\n disk_status = os.statvfs(os.path.dirname(absolute_location))\n available_diskspace = disk_status.f_frsize * disk_status.f_bavail\n return available_diskspace", "context": "def get_available_disk_space(location): ...\ndef get_available_disk_space(location): ...\ndef get_game_size_from_unzip(installer): ...\ndef check_diskspace(required_size, location): ...\ndef install_game(game, installer): ...\ndef verify_installer_integrity(game, installer): ...\ndef verify_disk_space(game, installer): ...\ndef make_tmp_dir(game): ...\ndef extract_installer(game, installer, temp_dir): ...\ndef move_and_overwrite(game, temp_dir, target_dir): ...\ndef copy_thumbnail(game): ...\ndef remove_installer(installer): ...\ndef uninstall_game(game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000927.py"} {"focal_file": "minigalaxy/installer.py", "focal_class": null, "focal_method": "check_diskspace", "tests": "import unittest\n\nclass Test_check_diskspace(unittest.TestCase):\n @mock.patch('os.statvfs')\n def test1_check_diskspace(self, mock_os_statvfs):\n frsize = 4096\n bavail = 29699296\n mock_os_statvfs().f_frsize = frsize\n mock_os_statvfs().f_bavail = bavail\n exp = True\n obs = installer.check_diskspace(524288000, '/')\n self.assertEqual(exp, obs)\n\n @mock.patch('os.statvfs')\n def test2_check_diskspace(self, mock_os_statvfs):\n frsize = 4096\n bavail = 29699\n mock_os_statvfs().f_frsize = frsize\n mock_os_statvfs().f_bavail = bavail\n exp = False\n obs = installer.check_diskspace(524288000, '/')\n self.assertEqual(exp, obs)\n", "method_code": "def check_diskspace(required_size, location):\n \"\"\"This method will return True when the disk space available is sufficient\n for the Download and Install. If not sufficient, it returns False.\"\"\"\n installed_game_size = int(required_size)\n diskspace_available = get_available_disk_space(location)\n return diskspace_available >= installed_game_size", "context": "def check_diskspace(required_size, location): ...\ndef get_available_disk_space(location): ...\ndef get_game_size_from_unzip(installer): ...\ndef check_diskspace(required_size, location): ...\ndef install_game(game, installer): ...\ndef verify_installer_integrity(game, installer): ...\ndef verify_disk_space(game, installer): ...\ndef make_tmp_dir(game): ...\ndef extract_installer(game, installer, temp_dir): ...\ndef move_and_overwrite(game, temp_dir, target_dir): ...\ndef copy_thumbnail(game): ...\ndef remove_installer(installer): ...\ndef uninstall_game(game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000928.py"} {"focal_file": "minigalaxy/installer.py", "focal_class": null, "focal_method": "verify_disk_space", "tests": "import unittest\n\nclass Test_verify_disk_space(unittest.TestCase):\n @mock.patch('os.statvfs')\n def test1_verify_disk_space(self, mock_os_statvfs):\n frsize = 4096\n bavail = 29699\n mock_os_statvfs().f_frsize = frsize\n mock_os_statvfs().f_bavail = bavail\n backup_installer = copy.deepcopy(installer.get_game_size_from_unzip)\n installer.get_game_size_from_unzip = MagicMock()\n installer.get_game_size_from_unzip.return_value = 524288000\n game = Game('Beneath A Steel Sky', install_dir='/home/makson/GOG Games/Beneath a Steel Sky', platform='linux')\n installer_file = '/beneath_a_steel_sky_en_gog_2_20150.sh'\n exp = 'Not enough space to extract game. Required: 524288000 Available: 121647104'\n obs = installer.verify_disk_space(game, installer_file)\n installer.get_game_size_from_unzip = backup_installer\n self.assertEqual(exp, obs)\n", "method_code": "def verify_disk_space(game, installer):\n err_msg = ''\n if game.platform == 'linux':\n required_space = get_game_size_from_unzip(installer)\n if not check_diskspace(required_space, game.install_dir):\n err_msg = _('Not enough space to extract game. Required: {} Available: {}').format(required_space, get_available_disk_space(game.install_dir))\n return err_msg", "context": "def verify_disk_space(game, installer): ...\ndef get_available_disk_space(location): ...\ndef get_game_size_from_unzip(installer): ...\ndef check_diskspace(required_size, location): ...\ndef install_game(game, installer): ...\ndef verify_installer_integrity(game, installer): ...\ndef verify_disk_space(game, installer): ...\ndef make_tmp_dir(game): ...\ndef extract_installer(game, installer, temp_dir): ...\ndef move_and_overwrite(game, temp_dir, target_dir): ...\ndef copy_thumbnail(game): ...\ndef remove_installer(installer): ...\ndef uninstall_game(game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000929.py"} {"focal_file": "minigalaxy/installer.py", "focal_class": null, "focal_method": "get_game_size_from_unzip", "tests": "import unittest\n\nclass Test_get_game_size_from_unzip(unittest.TestCase):\n @mock.patch('subprocess.Popen')\n def test_get_game_size_from_unzip(self, mock_subprocess):\n stdout = b' 550557 Defl:N 492111 11% 2018-04-19 15:01 48d4ab3f meta/gtk-2.0/pixmaps/background.png\\n 0 Stored 0 0% 2018-04-19 15:01 00000000 scripts/\\n 212070 Defl:N 63210 70% 2017-10-25 11:07 a05c1728 scripts/localization.lua\\n 21572 Defl:N 5592 74% 2017-06-27 13:02 e47c0968 scripts/mojosetup_init.lua\\n 9171 Defl:N 3374 63% 2017-10-25 11:07 14ac8da7 scripts/app_localization.lua\\n 4411 Defl:N 1247 72% 2018-04-19 15:01 2405a519 scripts/config.lua\\n 76365 Defl:N 17317 77% 2017-10-25 11:07 27d8bdb2 scripts/mojosetup_mainline.lua\\n-------- ------- --- -------\\n159236636 104883200 34% 189 files\\n'\n mock_subprocess().communicate.return_value = [stdout, b'stderr']\n installer_path = '/home/i/.cache/minigalaxy/download/Beneath a Steel Sky/beneath_a_steel_sky_en_gog_2_20150.sh'\n exp = 159236636\n obs = installer.get_game_size_from_unzip(installer_path)\n self.assertEqual(exp, obs)\n", "method_code": "def get_game_size_from_unzip(installer):\n var = subprocess.Popen(['unzip', '-v', installer], stdout=subprocess.PIPE)\n output = var.communicate()[0].decode('utf-8')\n lines_list = output.split('\\n')\n if len(lines_list) > 2 and (not lines_list[-1].strip()):\n last_line = lines_list[-2].strip()\n else:\n last_line = lines_list[-1].strip()\n size_value = int(last_line.split()[0])\n return size_value", "context": "def get_game_size_from_unzip(installer): ...\ndef get_available_disk_space(location): ...\ndef get_game_size_from_unzip(installer): ...\ndef check_diskspace(required_size, location): ...\ndef install_game(game, installer): ...\ndef verify_installer_integrity(game, installer): ...\ndef verify_disk_space(game, installer): ...\ndef make_tmp_dir(game): ...\ndef extract_installer(game, installer, temp_dir): ...\ndef move_and_overwrite(game, temp_dir, target_dir): ...\ndef copy_thumbnail(game): ...\ndef remove_installer(installer): ...\ndef uninstall_game(game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000930.py"} {"focal_file": "minigalaxy/launcher.py", "focal_class": null, "focal_method": "determine_launcher_type", "tests": "import unittest\n\nclass Test_determine_launcher_type(unittest.TestCase):\n def test1_determine_launcher_type(self):\n files = ['thumbnail.jpg', 'docs', 'support', 'game', 'start.sh', 'minigalaxy-dlc.json', 'gameinfo']\n exp = 'start_script'\n obs = launcher.determine_launcher_type(files)\n self.assertEqual(exp, obs)\n\n @mock.patch('shutil.which')\n def test2_determine_launcher_type(self, mock_shutil_which):\n mock_shutil_which.return_value = True\n files = ['thumbnail.jpg', 'data', 'docs', 'support', 'beneath.ini', 'scummvm', 'start.sh', 'gameinfo']\n exp = 'scummvm'\n obs = launcher.determine_launcher_type(files)\n self.assertEqual(exp, obs)\n\n def test3_determine_launcher_type(self):\n files = ['thumbnail.jpg', 'docs', 'support', 'unins000.exe', 'minigalaxy-dlc.json', 'gameinfo']\n exp = 'windows'\n obs = launcher.determine_launcher_type(files)\n self.assertEqual(exp, obs)\n\n @mock.patch('shutil.which')\n def test4_determine_launcher_type(self, mock_shutil_which):\n mock_shutil_which.return_value = True\n files = ['thumbnail.jpg', 'docs', 'support', 'dosbox', 'minigalaxy-dlc.json', 'gameinfo']\n exp = 'dosbox'\n obs = launcher.determine_launcher_type(files)\n self.assertEqual(exp, obs)\n\n def test5_determine_launcher_type(self):\n files = ['thumbnail.jpg', 'docs', 'support', 'game', 'minigalaxy-dlc.json', 'gameinfo']\n exp = 'final_resort'\n obs = launcher.determine_launcher_type(files)\n self.assertEqual(exp, obs)\n", "method_code": "def determine_launcher_type(files):\n launcher_type = 'unknown'\n if 'unins000.exe' in files:\n launcher_type = 'windows'\n elif 'dosbox' in files and shutil.which('dosbox'):\n launcher_type = 'dosbox'\n elif 'scummvm' in files and shutil.which('scummvm'):\n launcher_type = 'scummvm'\n elif 'prefix' in files and shutil.which('wine'):\n launcher_type = 'wine'\n elif 'start.sh' in files:\n launcher_type = 'start_script'\n elif 'game' in files:\n launcher_type = 'final_resort'\n return launcher_type", "context": "def determine_launcher_type(files): ...\ndef config_game(game): ...\ndef regedit_game(game): ...\ndef start_game(game): ...\ndef get_execute_command(game) -> list: ...\ndef determine_launcher_type(files): ...\ndef get_exe_cmd_with_var_command(game, exe_cmd): ...\ndef get_windows_exe_cmd(game, files): ...\ndef get_dosbox_exe_cmd(game, files): ...\ndef get_scummvm_exe_cmd(game, files): ...\ndef get_start_script_exe_cmd(game, files): ...\ndef get_final_resort_exe_cmd(game, files): ...\ndef set_fps_display(game): ...\ndef run_game_subprocess(game): ...\ndef check_if_game_started_correctly(process, game): ...\ndef check_if_game_start_process_spawned_final_process(error_message, game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "test1_determine_launcher_type", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000931.py"} {"focal_file": "minigalaxy/launcher.py", "focal_class": null, "focal_method": "get_windows_exe_cmd", "tests": "import unittest\n\nclass Test_get_windows_exe_cmd(unittest.TestCase):\n @mock.patch('glob.glob')\n def test1_get_windows_exe_cmd(self, mock_glob):\n mock_glob.return_value = ['/test/install/dir/start.exe', '/test/install/dir/unins000.exe']\n files = ['thumbnail.jpg', 'docs', 'support', 'game', 'minigalaxy-dlc.json', 'start.exe', 'unins000.exe']\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = ['wine', 'start.exe']\n obs = launcher.get_windows_exe_cmd(game, files)\n self.assertEqual(exp, obs)\n\n @mock.patch('builtins.open', new_callable=mock_open, read_data='')\n @mock.patch('os.chdir')\n def test2_get_windows_exe_cmd(self, mock_os_chdir, mo):\n goggame_1414471894_info_content = '{\\n \"buildId\": \"53350324452482937\",\\n \"clientId\": \"53185732904249211\",\\n \"gameId\": \"1414471894\",\\n \"language\": \"Russian\",\\n \"languages\": [\\n \"ru-RU\"\\n ],\\n \"name\": \"Metro Exodus - Sam\\'s Story\",\\n \"osBitness\": [\\n \"64\"\\n ],\\n \"playTasks\": [],\\n \"rootGameId\": \"1407287452\",\\n \"version\": 1\\n }'\n goggame_1407287452_info_content = '{\\n \"buildId\": \"53350324452482937\",\\n \"clientId\": \"53185732904249211\",\\n \"gameId\": \"1407287452\",\\n \"language\": \"Russian\",\\n \"languages\": [\\n \"ru-RU\"\\n ],\\n \"name\": \"Metro Exodus\",\\n \"osBitness\": [\\n \"64\"\\n ],\\n \"playTasks\": [\\n {\\n \"category\": \"game\",\\n \"isPrimary\": true,\\n \"languages\": [\\n \"ru-RU\"\\n ],\\n \"name\": \"Metro Exodus\",\\n \"osBitness\": [\\n \"64\"\\n ],\\n \"path\": \"MetroExodus.exe\",\\n \"type\": \"FileTask\"\\n }\\n ],\\n \"rootGameId\": \"1407287452\",\\n \"version\": 1\\n }'\n handlers = (mock_open(read_data=goggame_1414471894_info_content).return_value, mock_open(read_data=goggame_1407287452_info_content).return_value)\n mo.side_effect = handlers\n files = ['thumbnail.jpg', 'docs', 'support', 'game', 'minigalaxy-dlc.json', 'MetroExodus.exe', 'unins000.exe', 'goggame-1407287452.info', 'goggame-1414471894.info']\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = ['wine', 'MetroExodus.exe']\n obs = launcher.get_windows_exe_cmd(game, files)\n self.assertEqual(exp, obs)\n", "method_code": "def get_windows_exe_cmd(game, files):\n exe_cmd = ['']\n prefix = os.path.join(game.install_dir, 'prefix')\n os.environ['WINEPREFIX'] = prefix\n for file in files:\n if re.match('^goggame-[0-9]*\\\\.info$', file):\n os.chdir(game.install_dir)\n with open(file, 'r') as info_file:\n info = json.loads(info_file.read())\n if info['playTasks']:\n if 'workingDir' in info['playTasks'][0] and info['playTasks'][0]['workingDir']:\n exe_cmd = ['wine', 'start', '/b', '/wait', '/d', info['playTasks'][0]['workingDir'], info['playTasks'][0]['path']]\n else:\n exe_cmd = ['wine', info['playTasks'][0]['path']]\n if exe_cmd == ['']:\n executables = glob.glob(game.install_dir + '/*.exe')\n executables.remove(os.path.join(game.install_dir, 'unins000.exe'))\n filename = os.path.splitext(os.path.basename(executables[0]))[0] + '.exe'\n exe_cmd = ['wine', filename]\n return exe_cmd", "context": "def get_windows_exe_cmd(game, files): ...\ndef config_game(game): ...\ndef regedit_game(game): ...\ndef start_game(game): ...\ndef get_execute_command(game) -> list: ...\ndef determine_launcher_type(files): ...\ndef get_exe_cmd_with_var_command(game, exe_cmd): ...\ndef get_windows_exe_cmd(game, files): ...\ndef get_dosbox_exe_cmd(game, files): ...\ndef get_scummvm_exe_cmd(game, files): ...\ndef get_start_script_exe_cmd(game, files): ...\ndef get_final_resort_exe_cmd(game, files): ...\ndef set_fps_display(game): ...\ndef run_game_subprocess(game): ...\ndef check_if_game_started_correctly(process, game): ...\ndef check_if_game_start_process_spawned_final_process(error_message, game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000932.py"} {"focal_file": "minigalaxy/launcher.py", "focal_class": null, "focal_method": "get_dosbox_exe_cmd", "tests": "import unittest\n\nclass Test_get_dosbox_exe_cmd(unittest.TestCase):\n def test_get_dosbox_exe_cmd(self):\n files = ['thumbnail.jpg', 'docs', 'support', 'dosbox_bbb_single.conf', 'dosbox_aaa.conf', 'dosbox']\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = ['dosbox', '-conf', 'dosbox_aaa.conf', '-conf', 'dosbox_bbb_single.conf', '-no-console', '-c', 'exit']\n obs = launcher.get_dosbox_exe_cmd(game, files)\n self.assertEqual(exp, obs)\n", "method_code": "def get_dosbox_exe_cmd(game, files):\n dosbox_config = ''\n dosbox_config_single = ''\n for file in files:\n if re.match('^dosbox_?([a-z]|[A-Z]|[0-9])+\\\\.conf$', file):\n dosbox_config = file\n if re.match('^dosbox_?([a-z]|[A-Z]|[0-9])+_single\\\\.conf$', file):\n dosbox_config_single = file\n print(\"Using system's dosbox to launch {}\".format(game.name))\n return ['dosbox', '-conf', dosbox_config, '-conf', dosbox_config_single, '-no-console', '-c', 'exit']", "context": "def get_dosbox_exe_cmd(game, files): ...\ndef config_game(game): ...\ndef regedit_game(game): ...\ndef start_game(game): ...\ndef get_execute_command(game) -> list: ...\ndef determine_launcher_type(files): ...\ndef get_exe_cmd_with_var_command(game, exe_cmd): ...\ndef get_windows_exe_cmd(game, files): ...\ndef get_dosbox_exe_cmd(game, files): ...\ndef get_scummvm_exe_cmd(game, files): ...\ndef get_start_script_exe_cmd(game, files): ...\ndef get_final_resort_exe_cmd(game, files): ...\ndef set_fps_display(game): ...\ndef run_game_subprocess(game): ...\ndef check_if_game_started_correctly(process, game): ...\ndef check_if_game_start_process_spawned_final_process(error_message, game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_get_dosbox_exe_cmd", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000933.py"} {"focal_file": "minigalaxy/launcher.py", "focal_class": null, "focal_method": "get_scummvm_exe_cmd", "tests": "import unittest\n\nclass Test_get_scummvm_exe_cmd(unittest.TestCase):\n def test_get_scummvm_exe_cmd(self):\n files = ['thumbnail.jpg', 'data', 'docs', 'support', 'beneath.ini', 'scummvm', 'start.sh', 'gameinfo']\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = ['scummvm', '-c', 'beneath.ini']\n obs = launcher.get_scummvm_exe_cmd(game, files)\n self.assertEqual(exp, obs)\n", "method_code": "def get_scummvm_exe_cmd(game, files):\n scummvm_config = ''\n for file in files:\n if re.match('^.*\\\\.ini$', file):\n scummvm_config = file\n break\n print(\"Using system's scrummvm to launch {}\".format(game.name))\n return ['scummvm', '-c', scummvm_config]", "context": "def get_scummvm_exe_cmd(game, files): ...\ndef config_game(game): ...\ndef regedit_game(game): ...\ndef start_game(game): ...\ndef get_execute_command(game) -> list: ...\ndef determine_launcher_type(files): ...\ndef get_exe_cmd_with_var_command(game, exe_cmd): ...\ndef get_windows_exe_cmd(game, files): ...\ndef get_dosbox_exe_cmd(game, files): ...\ndef get_scummvm_exe_cmd(game, files): ...\ndef get_start_script_exe_cmd(game, files): ...\ndef get_final_resort_exe_cmd(game, files): ...\ndef set_fps_display(game): ...\ndef run_game_subprocess(game): ...\ndef check_if_game_started_correctly(process, game): ...\ndef check_if_game_start_process_spawned_final_process(error_message, game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_get_scummvm_exe_cmd", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000934.py"} {"focal_file": "minigalaxy/launcher.py", "focal_class": null, "focal_method": "get_start_script_exe_cmd", "tests": "import unittest\n\nclass Test_get_start_script_exe_cmd(unittest.TestCase):\n def test_get_start_script_exe_cmd(self):\n files = ['thumbnail.jpg', 'docs', 'support', 'game', 'start.sh', 'minigalaxy-dlc.json', 'gameinfo']\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = ['/test/install/dir/start.sh']\n obs = launcher.get_start_script_exe_cmd(game, files)\n self.assertEqual(exp, obs)\n", "method_code": "def get_start_script_exe_cmd(game, files):\n start_sh = 'start.sh'\n exec_start = [os.path.join(game.install_dir, start_sh)] if start_sh in files else ['']\n return exec_start", "context": "def get_start_script_exe_cmd(game, files): ...\ndef config_game(game): ...\ndef regedit_game(game): ...\ndef start_game(game): ...\ndef get_execute_command(game) -> list: ...\ndef determine_launcher_type(files): ...\ndef get_exe_cmd_with_var_command(game, exe_cmd): ...\ndef get_windows_exe_cmd(game, files): ...\ndef get_dosbox_exe_cmd(game, files): ...\ndef get_scummvm_exe_cmd(game, files): ...\ndef get_start_script_exe_cmd(game, files): ...\ndef get_final_resort_exe_cmd(game, files): ...\ndef set_fps_display(game): ...\ndef run_game_subprocess(game): ...\ndef check_if_game_started_correctly(process, game): ...\ndef check_if_game_start_process_spawned_final_process(error_message, game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "test_get_start_script_exe_cmd", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000935.py"} {"focal_file": "minigalaxy/launcher.py", "focal_class": null, "focal_method": "run_game_subprocess", "tests": "import unittest\n\nclass Test_run_game_subprocess(unittest.TestCase):\n @mock.patch('os.getcwd')\n @mock.patch('os.chdir')\n @mock.patch('subprocess.Popen')\n @mock.patch('minigalaxy.launcher.get_execute_command')\n def test1_run_game_subprocess(self, launcher_mock, mock_popen, mock_os_chdir, mock_os_getcwd):\n mock_process = 'Mock Process'\n mock_popen.return_value = mock_process\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = ('', mock_process)\n obs = launcher.run_game_subprocess(game)\n self.assertEqual(exp, obs)\n\n @mock.patch('os.getcwd')\n @mock.patch('os.chdir')\n @mock.patch('subprocess.Popen')\n @mock.patch('minigalaxy.launcher.get_execute_command')\n def test2_run_game_subprocess(self, launcher_mock, mock_popen, mock_os_chdir, mock_os_getcwd):\n mock_popen.side_effect = FileNotFoundError()\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = ('No executable was found in /test/install/dir', None)\n obs = launcher.run_game_subprocess(game)\n self.assertEqual(exp, obs)\n", "method_code": "def run_game_subprocess(game):\n working_dir = os.getcwd()\n os.chdir(game.install_dir)\n try:\n process = subprocess.Popen(get_execute_command(game), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n error_message = ''\n except FileNotFoundError:\n process = None\n error_message = _('No executable was found in {}').format(game.install_dir)\n os.chdir(working_dir)\n return (error_message, process)", "context": "def run_game_subprocess(game): ...\ndef config_game(game): ...\ndef regedit_game(game): ...\ndef start_game(game): ...\ndef get_execute_command(game) -> list: ...\ndef determine_launcher_type(files): ...\ndef get_exe_cmd_with_var_command(game, exe_cmd): ...\ndef get_windows_exe_cmd(game, files): ...\ndef get_dosbox_exe_cmd(game, files): ...\ndef get_scummvm_exe_cmd(game, files): ...\ndef get_start_script_exe_cmd(game, files): ...\ndef get_final_resort_exe_cmd(game, files): ...\ndef set_fps_display(game): ...\ndef run_game_subprocess(game): ...\ndef check_if_game_started_correctly(process, game): ...\ndef check_if_game_start_process_spawned_final_process(error_message, game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000936.py"} {"focal_file": "minigalaxy/launcher.py", "focal_class": null, "focal_method": "check_if_game_started_correctly", "tests": "import unittest\n\nclass Test_check_if_game_started_correctly(unittest.TestCase):\n @mock.patch('minigalaxy.launcher.check_if_game_start_process_spawned_final_process')\n def test1_check_if_game_started_correctly(self, mock_check_game):\n mock_process = MagicMock()\n mock_process.wait.side_effect = subprocess.TimeoutExpired('cmd', 1)\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = ''\n obs = launcher.check_if_game_started_correctly(mock_process, game)\n self.assertEqual(exp, obs)\n\n @mock.patch('minigalaxy.launcher.check_if_game_start_process_spawned_final_process')\n def test2_check_if_game_started_correctly(self, mock_check_game):\n mock_process = MagicMock()\n mock_process.communicate.return_value = (b'Output message', b'Error message')\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = 'Error message'\n obs = launcher.check_if_game_started_correctly(mock_process, game)\n self.assertEqual(exp, obs)\n", "method_code": "def check_if_game_started_correctly(process, game):\n error_message = ''\n try:\n process.wait(timeout=float(3))\n error_message = 'Game start process has finished prematurely'\n except subprocess.TimeoutExpired:\n pass\n if error_message in ['Game start process has finished prematurely']:\n error_message = check_if_game_start_process_spawned_final_process(error_message, game)\n if error_message:\n stdout, stderror = process.communicate()\n if stderror:\n error_message = stderror.decode('utf-8')\n elif stdout:\n error_message = stdout.decode('utf-8')\n return error_message", "context": "def check_if_game_started_correctly(process, game): ...\ndef config_game(game): ...\ndef regedit_game(game): ...\ndef start_game(game): ...\ndef get_execute_command(game) -> list: ...\ndef determine_launcher_type(files): ...\ndef get_exe_cmd_with_var_command(game, exe_cmd): ...\ndef get_windows_exe_cmd(game, files): ...\ndef get_dosbox_exe_cmd(game, files): ...\ndef get_scummvm_exe_cmd(game, files): ...\ndef get_start_script_exe_cmd(game, files): ...\ndef get_final_resort_exe_cmd(game, files): ...\ndef set_fps_display(game): ...\ndef run_game_subprocess(game): ...\ndef check_if_game_started_correctly(process, game): ...\ndef check_if_game_start_process_spawned_final_process(error_message, game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000937.py"} {"focal_file": "minigalaxy/launcher.py", "focal_class": null, "focal_method": "check_if_game_start_process_spawned_final_process", "tests": "import unittest\n\nclass Test_check_if_game_start_process_spawned_final_process(unittest.TestCase):\n @mock.patch('os.getpid')\n @mock.patch('subprocess.check_output')\n def test1_check_if_game_start_process_spawned_final_process(self, mock_check_output, mock_getpid):\n mock_check_output.return_value = b'UID PID PPID C STIME TTY TIME CMD\\nroot 1 0 0 lis24 ? 00:00:02 /sbin/init splash\\nroot 2 0 0 lis24 ? 00:00:00 [kthreadd]\\nroot 3 2 0 lis24 ? 00:00:00 [rcu_gp]\\nroot 4 2 0 lis24 ? 00:00:00 [rcu_par_gp]\\nroot 6 2 0 lis24 ? 00:00:00 [kworker/0:0H-kblockd]\\n'\n mock_getpid.return_value = 1000\n err_msg = 'Error Message'\n game = Game('Test Game', install_dir='/test/install/dir')\n exp = err_msg\n obs = launcher.check_if_game_start_process_spawned_final_process(err_msg, game)\n self.assertEqual(exp, obs)\n\n @mock.patch('os.getpid')\n @mock.patch('subprocess.check_output')\n def test2_check_if_game_start_process_spawned_final_process(self, mock_check_output, mock_getpid):\n mock_check_output.return_value = b'UID PID PPID C STIME TTY TIME CMD\\nroot 1 0 0 lis24 ? 00:00:02 /sbin/init splash\\nroot 2 0 0 lis24 ? 00:00:00 [kthreadd]\\nroot 3 2 0 lis24 ? 00:00:00 [rcu_gp]\\nroot 4 2 0 lis24 ? 00:00:00 [rcu_par_gp]\\nroot 6 2 0 lis24 ? 00:00:00 [kworker/0:0H-kblockd]\\nmakson 1006 2 0 lis24 ? 00:00:00 /bin/sh /home/makson/.paradoxlauncher/launcher-v2.2020.15/Paradox Launcher --pdxlGameDir /home/makson/GOG Games/Stellaris/game --gameDir /home/makson/GOG Games/Stellaris/game\\n'\n mock_getpid.return_value = 1000\n err_msg = 'Error Message'\n game = Game('Stellaris', install_dir='/home/makson/GOG Games')\n exp = ''\n obs = launcher.check_if_game_start_process_spawned_final_process(err_msg, game)\n self.assertEqual(exp, obs)\n\n @mock.patch('os.getpid')\n @mock.patch('subprocess.check_output')\n def test3_check_if_game_start_process_spawned_final_process(self, mock_check_output, mock_getpid):\n mock_check_output.return_value = b'UID PID PPID C STIME TTY TIME CMD\\nroot 12486 2 0 17:47 ? 00:00:00 [kworker/u17:3-kcryptd]\\nroot 12543 2 0 17:53 ? 00:00:00 [kworker/u17:1-kcryptd]\\nroot 12617 2 0 18:02 ? 00:00:00 [kworker/5:1-ata_sff]\\nroot 12652 2 0 18:07 ? 00:00:00 [kworker/0:0-events]\\nroot 12682 2 0 18:08 ? 00:00:00 [kworker/5:2-ata_sff]\\nroot 12699 2 0 18:08 ? 00:00:00 [kworker/u17:0-kcryptd]\\nmakson 12783 6690 1 18:09 pts/4 00:00:01 /usr/bin/python3 build/scripts-3.7/minigalaxy\\nmakson 12866 1378 0 18:09 pts/4 00:00:00 /bin/sh /home/makson/.paradoxlauncher/launcher-v2.2021.1/Paradox Launcher --pdxlGameDir /home/makson/GOG Games/Imperator Rome/game/launcher --gameDir /home/makson/GOG Games/Imperator Rome/game/launcher\\n'\n mock_getpid.return_value = 1000\n err_msg = 'Error Message'\n game = Game('Imperator: Rome', install_dir='/home/makson/GOG Games')\n exp = ''\n obs = launcher.check_if_game_start_process_spawned_final_process(err_msg, game)\n self.assertEqual(exp, obs)\n", "method_code": "def check_if_game_start_process_spawned_final_process(error_message, game):\n ps_ef = subprocess.check_output(['ps', '-ef']).decode('utf-8')\n ps_list = ps_ef.split('\\n')\n for ps in ps_list:\n ps_split = ps.split()\n if len(ps_split) < 2:\n continue\n if not ps_split[1].isdigit():\n continue\n if int(ps_split[1]) > os.getpid() and game.get_install_directory_name() in ps:\n error_message = ''\n break\n return error_message", "context": "def check_if_game_start_process_spawned_final_process(error_message, game): ...\ndef config_game(game): ...\ndef regedit_game(game): ...\ndef start_game(game): ...\ndef get_execute_command(game) -> list: ...\ndef determine_launcher_type(files): ...\ndef get_exe_cmd_with_var_command(game, exe_cmd): ...\ndef get_windows_exe_cmd(game, files): ...\ndef get_dosbox_exe_cmd(game, files): ...\ndef get_scummvm_exe_cmd(game, files): ...\ndef get_start_script_exe_cmd(game, files): ...\ndef get_final_resort_exe_cmd(game, files): ...\ndef set_fps_display(game): ...\ndef run_game_subprocess(game): ...\ndef check_if_game_started_correctly(process, game): ...\ndef check_if_game_start_process_spawned_final_process(error_message, game): ...\n", "repository": "sharkwouter/minigalaxy", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000938.py"} {"focal_file": "api/apiutils.py", "focal_class": null, "focal_method": "intersection", "tests": "import unittest\n\nclass Test_intersection(unittest.TestCase):\n def test_intersection(self):\n print(self._testMethodName)\n res1 = self.api.keyword_search('Madden', max_results=10)\n res2 = self.api.keyword_search('Stonebraker', max_results=10)\n res = res1.intersection(res2)\n for el in res:\n print(str(el))\n", "method_code": " def intersection(self, drs):\n self._ranked = False\n result = DRS([], Operation(OP.NONE))\n new_data = []\n if drs.mode == DRSMode.TABLE:\n merging_tables = [(hit.source_name, hit) for hit in drs.data]\n my_tables = [(hit.source_name, hit) for hit in self.data]\n for table, hit_ext in merging_tables:\n for t, hit_in in my_tables:\n if table == t:\n new_data.append(hit_ext)\n new_data.append(hit_in)\n elif drs.mode == DRSMode.FIELDS:\n merging_data = set(drs.data)\n my_data = set(self.data)\n new_data = list(merging_data.intersection(my_data))\n result.set_data(new_data)\n result.absorb_provenance(self, annotate_and_edges=True)\n result.absorb_provenance(drs, annotate_and_edges=True)\n return result\n ", "context": "class DRS():\n def intersection(self, drs): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def union(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_intersection", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_000939.py"} {"focal_file": "api/apiutils.py", "focal_class": null, "focal_method": "union", "tests": "import unittest\n\nclass Test_union(unittest.TestCase):\n def test_union(self):\n print(self._testMethodName)\n res1 = self.api.keyword_search('Madden', max_results=10)\n res2 = self.api.schema_name_search('Stonebraker', max_results=10)\n res = res1.union(res2)\n for el in res:\n print(str(el))\n", "method_code": " def union(self, drs):\n self._ranked = False\n result = DRS([], Operation(OP.NONE))\n merging_data = set(drs.data)\n my_data = set(self.data)\n new_data = merging_data.union(my_data)\n result.set_data(list(new_data))\n result.absorb_provenance(self)\n result.absorb_provenance(drs)\n return result\n ", "context": "class DRS():\n def union(self, drs): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_union", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_000940.py"} {"focal_file": "api/apiutils.py", "focal_class": null, "focal_method": "set_difference", "tests": "import unittest\n\nclass Test_set_difference(unittest.TestCase):\n def test_difference(self):\n print(self._testMethodName)\n res1 = self.api.keyword_search('Madden', max_results=10)\n res2 = self.api.keyword_search('Stonebraker', max_results=10)\n res = res1.set_difference(res2)\n for el in res:\n print(str(el))\n", "method_code": " def set_difference(self, drs):\n self._ranked = False\n result = DRS([], Operation(OP.NONE))\n merging_data = set(drs.data)\n my_data = set(self.data)\n new_data = my_data - merging_data\n result.set_data(list(new_data))\n result.absorb_provenance(self)\n result.absorb_provenance(drs)\n return result\n ", "context": "class DRS():\n def set_difference(self, drs): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def union(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_difference", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_000941.py"} {"focal_file": "api/apiutils.py", "focal_class": null, "focal_method": "set_table_mode", "tests": "import unittest\n\nclass Test_set_table_mode(unittest.TestCase):\n def test_paths_between_table_mode(self):\n print(self._testMethodName)\n field1 = ('chembl_21', 'drug_indication', 'record_id')\n field2 = ('chembl_21', 'compound_records', 'record_id')\n drs1 = self.api.drs_from_raw_field(field1)\n drs2 = self.api.drs_from_raw_field(field2)\n drs1.set_table_mode()\n drs2.set_table_mode()\n res = self.api.paths_between(drs1, drs2, Relation.PKFK)\n data = [x for x in res]\n print('Total results: ' + str(len(data)))\n for el in data:\n print(str(el))\n print('Paths: ')\n res.visualize_provenance()\n res.debug_print()\n paths = res.paths()\n for p in paths:\n print(str(p))\n", "method_code": " def set_table_mode(self):\n self._mode = DRSMode.TABLE\n ", "context": "class DRS():\n def set_table_mode(self): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def union(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_paths_between_table_mode", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_000942.py"} {"focal_file": "api/apiutils.py", "focal_class": "Hit", "focal_method": "set_fields_mode", "tests": "import unittest\n\nclass Test_Hit_set_fields_mode(unittest.TestCase):\n def test_drs_field_iteration(self):\n print(self._testMethodName)\n h1 = Hit(0, 'dba', 'table_a', 'a', -1)\n h2 = Hit(1, 'dba', 'table_a', 'b', -1)\n h3 = Hit(2, 'dba', 'table_b', 'c', -1)\n h4 = Hit(3, 'dba', 'table_b', 'd', -1)\n drs = DRS([h1, h2, h3, h4], Operation(OP.ORIGIN))\n drs.set_fields_mode()\n for el in drs:\n print(str(el))\n self.assertTrue(True)\n", "method_code": " def set_fields_mode(self):\n self._mode = DRSMode.FIELDS\n ", "context": "class DRS():\n def set_fields_mode(self): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def union(self, drs): ...\n def set_difference(self, drs): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_drs_field_iteration", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], "pynose_source_file": "test_000943.py"} {"focal_file": "api/apiutils.py", "focal_class": "Hit", "focal_method": "set_table_mode", "tests": "import unittest\n\nclass Test_Hit_set_table_mode(unittest.TestCase):\n def test_drs_table_iteration(self):\n print(self._testMethodName)\n h1 = Hit(0, 'dba', 'table_a', 'a', -1)\n h2 = Hit(1, 'dba', 'table_a', 'b', -1)\n h3 = Hit(2, 'dba', 'table_b', 'c', -1)\n h4 = Hit(3, 'dba', 'table_b', 'd', -1)\n drs = DRS([h1, h2, h3, h4], Operation(OP.ORIGIN))\n drs.set_table_mode()\n for el in drs:\n print(str(el))\n self.assertTrue(True)\n", "method_code": " def set_table_mode(self):\n self._mode = DRSMode.TABLE\n ", "context": "class DRS():\n def set_table_mode(self): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def union(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_drs_table_iteration", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], "pynose_source_file": "test_000944.py"} {"focal_file": "api/apiutils.py", "focal_class": "Operation", "focal_method": "get_provenance", "tests": "import unittest\n\nclass Test_Operation_get_provenance(unittest.TestCase):\n def test_creation_initial_provenance(self):\n print(self._testMethodName)\n h0 = Hit(10, 'dba', 'table_c', 'v', -1)\n h1 = Hit(0, 'dba', 'table_a', 'a', -1)\n h2 = Hit(1, 'dba', 'table_a', 'b', -1)\n h3 = Hit(2, 'dba', 'table_b', 'c', -1)\n h4 = Hit(3, 'dba', 'table_b', 'd', -1)\n drs = DRS([h1, h2, h3, h4], Operation(OP.CONTENT_SIM, params=[h0]))\n prov_graph = drs.get_provenance().prov_graph()\n nodes = prov_graph.nodes()\n print('NODES')\n for n in nodes:\n print(str(n))\n print(' ')\n edges = prov_graph.edges(keys=True)\n print('EDGES')\n for e in edges:\n print(str(e))\n print(' ')\n self.assertTrue(True)\n", "method_code": " def get_provenance(self):\n return self._provenance\n ", "context": "class DRS():\n def get_provenance(self): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def union(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_creation_initial_provenance", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], "pynose_source_file": "test_000945.py"} {"focal_file": "api/apiutils.py", "focal_class": "Operation", "focal_method": "absorb_provenance", "tests": "import unittest\n\nclass Test_Operation_absorb_provenance(unittest.TestCase):\n def test_absorb_provenance(self):\n print(self._testMethodName)\n h0 = Hit(10, 'dba', 'table_c', 'v', -1)\n h1 = Hit(0, 'dba', 'table_a', 'a', -1)\n h2 = Hit(1, 'dba', 'table_a', 'b', -1)\n h3 = Hit(2, 'dba', 'table_b', 'c', -1)\n h4 = Hit(3, 'dba', 'table_b', 'd', -1)\n drs1 = DRS([h1, h2, h3, h4], Operation(OP.CONTENT_SIM, params=[h0]))\n h5 = Hit(1, 'dba', 'table_a', 'b', -1)\n h6 = Hit(16, 'dba', 'table_d', 'a', -1)\n h7 = Hit(17, 'dba', 'table_d', 'b', -1)\n drs2 = DRS([h6, h7], Operation(OP.SCHEMA_SIM, params=[h5]))\n drs = drs1.absorb_provenance(drs2)\n prov_graph = drs.get_provenance().prov_graph()\n nodes = prov_graph.nodes()\n print('NODES')\n for n in nodes:\n print(str(n))\n print(' ')\n edges = prov_graph.edges(keys=True)\n print('EDGES')\n for e in edges:\n print(str(e))\n print(' ')\n init_data = set([x for x in drs1])\n merged_data = set([x for x in drs])\n new_data = init_data - merged_data\n print('Len must be 0: ' + str(len(new_data)))\n self.assertTrue(len(new_data) == 0)\n", "method_code": " def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False):\n \"\"\"\n Merge provenance of the input parameter into self, *not* the data.\n :param drs:\n :return:\n \"\"\"\n \n def annotate_union_edges(label):\n my_data = set(self.data)\n merging_data = set(drs.data)\n disjoint = my_data.intersection(merging_data)\n node_and_edges = []\n for el in disjoint:\n input_edges1 = self._provenance.prov_graph().in_edges(el, data=True)\n input_edges2 = drs._provenance.prov_graph().in_edges(el, data=True)\n node_and_edges.append((input_edges1, input_edges2))\n for input1, input2 in node_and_edges:\n for src1, tar1, dic1 in input1:\n edge_data = merge[src1][tar1]\n for e in edge_data:\n edge_data[e][label] = 1\n for src2, tar2, dic2 in input2:\n edge_data = merge[src2][tar2]\n for e in edge_data:\n edge_data[e][label] = 1\n self._ranked = False\n prov_graph_of_merging = drs.get_provenance().prov_graph()\n merge = nx.compose(self._provenance.prov_graph(), prov_graph_of_merging)\n if annotate_and_edges:\n annotate_union_edges('AND')\n if annotate_or_edges:\n annotate_union_edges('OR')\n self._provenance.swap_p_graph(merge)\n return self\n ", "context": "class DRS():\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def union(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_absorb_provenance", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000946.py"} {"focal_file": "api/apiutils.py", "focal_class": "Operation", "focal_method": "absorb", "tests": "import unittest\n\nclass Test_Operation_absorb(unittest.TestCase):\n def test_absorb(self):\n print(self._testMethodName)\n h0 = Hit(10, 'dba', 'table_c', 'v', -1)\n h1 = Hit(0, 'dba', 'table_a', 'a', -1)\n h2 = Hit(1, 'dba', 'table_a', 'b', -1)\n h3 = Hit(2, 'dba', 'table_b', 'c', -1)\n h4 = Hit(3, 'dba', 'table_b', 'd', -1)\n drs1 = DRS([h1, h2, h3, h4], Operation(OP.CONTENT_SIM, params=[h0]))\n h5 = Hit(1, 'dba', 'table_a', 'b', -1)\n h6 = Hit(16, 'dba', 'table_d', 'a', -1)\n h7 = Hit(17, 'dba', 'table_d', 'b', -1)\n drs2 = DRS([h6, h7], Operation(OP.SCHEMA_SIM, params=[h5]))\n drs = drs1.absorb(drs2)\n prov_graph = drs.get_provenance().prov_graph()\n nodes = prov_graph.nodes()\n print('NODES')\n for n in nodes:\n print(str(n))\n print(' ')\n edges = prov_graph.edges(keys=True)\n print('EDGES')\n for e in edges:\n print(str(e))\n print(' ')\n drs1_data = set([x for x in drs1])\n drs2_data = set([x for x in drs2])\n merged_data = set([x for x in drs])\n lm = len(merged_data)\n lu = len(drs1_data.union(drs2_data))\n print('Len must be 0: ' + str(lu - lm))\n self.assertTrue(lu - lm == 0)\n", "method_code": " def absorb(self, drs):\n \"\"\"\n Merge the input parameter DRS into self, by extending provenance appropriately and appending data\n :param drs:\n :return:\n \"\"\"\n self._ranked = False\n merging_data = set(drs.data)\n my_data = set(self.data)\n new_data = merging_data.union(my_data)\n self.set_data(list(new_data))\n self.absorb_provenance(drs)\n return self\n ", "context": "class DRS():\n def absorb(self, drs): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def intersection(self, drs): ...\n def union(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_absorb", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000947.py"} {"focal_file": "api/apiutils.py", "focal_class": "Operation", "focal_method": "intersection", "tests": "import unittest\n\nclass Test_Operation_intersection(unittest.TestCase):\n def test_intersection(self):\n print(self._testMethodName)\n h0 = Hit(10, 'dba', 'table_c', 'v', -1)\n h1 = Hit(0, 'dba', 'table_a', 'a', -1)\n h2 = Hit(1, 'dba', 'table_a', 'b', -1)\n h3 = Hit(2, 'dba', 'table_b', 'c', -1)\n h4 = Hit(3, 'dba', 'table_b', 'd', -1)\n drs1 = DRS([h0, h1, h2, h3, h4], Operation(OP.ORIGIN))\n h5 = Hit(1, 'dba', 'table_a', 'b', -1)\n h6 = Hit(16, 'dba', 'table_d', 'a', -1)\n h7 = Hit(17, 'dba', 'table_d', 'b', -1)\n drs2 = DRS([h5, h6, h7], Operation(OP.ORIGIN))\n drs = drs1.intersection(drs2)\n prov_graph = drs.get_provenance().prov_graph()\n nodes = prov_graph.nodes()\n print('NODES')\n for n in nodes:\n print(str(n))\n print(' ')\n edges = prov_graph.edges(keys=True)\n print('EDGES')\n for e in edges:\n print(str(e))\n print(' ')\n data = [x for x in drs]\n ld = len(data)\n print('Len must be 1: ' + str(ld))\n self.assertTrue(ld == 1)\n", "method_code": " def intersection(self, drs):\n self._ranked = False\n result = DRS([], Operation(OP.NONE))\n new_data = []\n if drs.mode == DRSMode.TABLE:\n merging_tables = [(hit.source_name, hit) for hit in drs.data]\n my_tables = [(hit.source_name, hit) for hit in self.data]\n for table, hit_ext in merging_tables:\n for t, hit_in in my_tables:\n if table == t:\n new_data.append(hit_ext)\n new_data.append(hit_in)\n elif drs.mode == DRSMode.FIELDS:\n merging_data = set(drs.data)\n my_data = set(self.data)\n new_data = list(merging_data.intersection(my_data))\n result.set_data(new_data)\n result.absorb_provenance(self, annotate_and_edges=True)\n result.absorb_provenance(drs, annotate_and_edges=True)\n return result\n ", "context": "class DRS():\n def intersection(self, drs): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def union(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_intersection", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000948.py"} {"focal_file": "api/apiutils.py", "focal_class": "Operation", "focal_method": "union", "tests": "import unittest\n\nclass Test_Operation_union(unittest.TestCase):\n def test_union(self):\n print(self._testMethodName)\n h0 = Hit(10, 'dba', 'table_c', 'v', -1)\n h1 = Hit(0, 'dba', 'table_a', 'a', -1)\n h2 = Hit(1, 'dba', 'table_a', 'b', -1)\n h3 = Hit(2, 'dba', 'table_b', 'c', -1)\n h4 = Hit(3, 'dba', 'table_b', 'd', -1)\n drs1 = DRS([h0, h1, h2, h3, h4], Operation(OP.ORIGIN))\n h5 = Hit(1, 'dba', 'table_a', 'b', -1)\n h6 = Hit(16, 'dba', 'table_d', 'a', -1)\n h7 = Hit(17, 'dba', 'table_d', 'b', -1)\n drs2 = DRS([h5, h6, h7], Operation(OP.ORIGIN))\n drs = drs1.union(drs2)\n prov_graph = drs.get_provenance().prov_graph()\n nodes = prov_graph.nodes()\n print('NODES')\n for n in nodes:\n print(str(n))\n print(' ')\n edges = prov_graph.edges(keys=True)\n print('EDGES')\n for e in edges:\n print(str(e))\n print(' ')\n data = [x for x in drs]\n ld = len(data)\n print('Len must be 7: ' + str(ld))\n self.assertTrue(ld == 7)\n", "method_code": " def union(self, drs):\n self._ranked = False\n result = DRS([], Operation(OP.NONE))\n merging_data = set(drs.data)\n my_data = set(self.data)\n new_data = merging_data.union(my_data)\n result.set_data(list(new_data))\n result.absorb_provenance(self)\n result.absorb_provenance(drs)\n return result\n ", "context": "class DRS():\n def union(self, drs): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def set_difference(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_union", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000949.py"} {"focal_file": "api/apiutils.py", "focal_class": "Operation", "focal_method": "set_difference", "tests": "import unittest\n\nclass Test_Operation_set_difference(unittest.TestCase):\n def test_sdifference(self):\n print(self._testMethodName)\n h0 = Hit(10, 'dba', 'table_c', 'v', -1)\n h1 = Hit(0, 'dba', 'table_a', 'a', -1)\n h2 = Hit(1, 'dba', 'table_a', 'b', -1)\n h3 = Hit(2, 'dba', 'table_b', 'c', -1)\n h4 = Hit(3, 'dba', 'table_b', 'd', -1)\n drs1 = DRS([h0, h1, h2, h3, h4], Operation(OP.ORIGIN))\n h5 = Hit(1, 'dba', 'table_a', 'b', -1)\n h6 = Hit(16, 'dba', 'table_d', 'a', -1)\n h7 = Hit(17, 'dba', 'table_d', 'b', -1)\n drs2 = DRS([h5, h6, h7], Operation(OP.ORIGIN))\n drs = drs1.set_difference(drs2)\n prov_graph = drs.get_provenance().prov_graph()\n nodes = prov_graph.nodes()\n print('NODES')\n for n in nodes:\n print(str(n))\n print(' ')\n edges = prov_graph.edges(keys=True)\n print('EDGES')\n for e in edges:\n print(str(e))\n print(' ')\n data = [x for x in drs]\n ld = len(data)\n print('Len must be 4: ' + str(ld))\n self.assertTrue(ld == 4)\n", "method_code": " def set_difference(self, drs):\n self._ranked = False\n result = DRS([], Operation(OP.NONE))\n merging_data = set(drs.data)\n my_data = set(self.data)\n new_data = my_data - merging_data\n result.set_data(list(new_data))\n result.absorb_provenance(self)\n result.absorb_provenance(drs)\n return result\n ", "context": "class DRS():\n def set_difference(self, drs): ...\n def __init__(self, data, operation, lean_drs=False): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __dict__(self): ...\n def data(self): ...\n def set_data(self, data): ...\n def mode(self): ...\n def size(self): ...\n def get_provenance(self): ...\n def debug_print(self): ...\n def visualize_provenance(self, labels=False): ...\n def absorb_provenance(self, drs, annotate_and_edges=False, annotate_or_edges=False): ...\n def absorb(self, drs): ...\n def intersection(self, drs): ...\n def union(self, drs): ...\n def set_fields_mode(self): ...\n def set_table_mode(self): ...\n def paths(self): ...\n def path(self, a: Hit): ...\n def why_id(self, a: int) -> [Hit]: ...\n def why(self, a: Hit) -> [Hit]: ...\n def how_id(self, a: int) -> [Hit]: ...\n def how(self, a: Hit) -> [str]: ...\n def _compute_certainty_scores(self, aggr_strategy=None): ...\n def _compute_coverage_scores(self): ...\n def compute_ranking_scores(self): ...\n def rank_certainty(self): ...\n def rank_coverage(self): ...\n def rank_certainty_include_coverage(self): ...\n def print_tables(self): ...\n def print_columns(self): ...\n def print_tables_with_scores(self): ...\n def print_columns_with_scores(self): ...\n def pretty_print_columns(self): ...\n def pretty_print_columns_with_scores(self): ...\n\n self._data = data\n self._table_view = []\n self._idx = 0\n self._idx_table = 0\n self._mode = DRSMode.FIELDS\n self._ranked = False\n self._rank_data = defaultdict(dict)\n self._ranking_criteria = None\n self._chosen_rank = []\n self._origin_values_coverage = dict()\n", "repository": "mitdbg/aurum-datadiscovery", "test_name": "test_sdifference", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000950.py"} {"focal_file": "transmissionrpc/utils.py", "focal_class": null, "focal_method": "format_size", "tests": "import unittest\n\nclass Test_format_size(unittest.TestCase):\n def testFormatSize(self):\n table = {512: (512, 'B'), 1024: (1.0, 'KiB'), 1048575: (1023.999, 'KiB'), 1048576: (1.0, 'MiB'), 1073741824: (1.0, 'GiB'), 1099511627776: (1.0, 'TiB'), 1125899906842624: (1.0, 'PiB'), 1152921504606846976: (1.0, 'EiB')}\n for size, expected in iter(table.items()):\n result = tu.format_size(size)\n self.assertAlmostEqual(result[0], expected[0], 4)\n self.assertEqual(result[1], expected[1])\n", "method_code": "def format_size(size):\n \"\"\"\n Format byte size into IEC prefixes, B, KiB, MiB ...\n \"\"\"\n size = float(size)\n i = 0\n while size >= 1024.0 and i < len(UNITS):\n i += 1\n size /= 1024.0\n return (size, UNITS[i])", "context": "def format_size(size): ...\ndef format_size(size): ...\ndef format_speed(size): ...\ndef format_timedelta(delta): ...\ndef format_timestamp(timestamp, utc=False): ...\ndef inet_address(address, default_port, default_address='localhost'): ...\ndef rpc_bool(arg): ...\ndef make_python_name(name): ...\ndef make_rpc_name(name): ...\ndef argument_value_convert(method, argument, value, rpc_version): ...\ndef get_arguments(method, rpc_version): ...\ndef is_logger_configured(): ...\ndef add_stdout_logger(level='debug'): ...\ndef add_file_logger(filepath, level='debug'): ...\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testFormatSize", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000951.py"} {"focal_file": "transmissionrpc/utils.py", "focal_class": null, "focal_method": "format_speed", "tests": "import unittest\n\nclass Test_format_speed(unittest.TestCase):\n def testFormatSpeed(self):\n table = {512: (512, 'B/s'), 1024: (1.0, 'KiB/s'), 1048575: (1023.999, 'KiB/s'), 1048576: (1.0, 'MiB/s'), 1073741824: (1.0, 'GiB/s'), 1099511627776: (1.0, 'TiB/s'), 1125899906842624: (1.0, 'PiB/s'), 1152921504606846976: (1.0, 'EiB/s')}\n for size, expected in iter(table.items()):\n result = tu.format_speed(size)\n self.assertAlmostEqual(result[0], expected[0], 4)\n self.assertEqual(result[1], expected[1])\n", "method_code": "def format_speed(size):\n \"\"\"\n Format bytes per second speed into IEC prefixes, B/s, KiB/s, MiB/s ...\n \"\"\"\n size, unit = format_size(size)\n return (size, unit + '/s')", "context": "def format_speed(size): ...\ndef format_size(size): ...\ndef format_speed(size): ...\ndef format_timedelta(delta): ...\ndef format_timestamp(timestamp, utc=False): ...\ndef inet_address(address, default_port, default_address='localhost'): ...\ndef rpc_bool(arg): ...\ndef make_python_name(name): ...\ndef make_rpc_name(name): ...\ndef argument_value_convert(method, argument, value, rpc_version): ...\ndef get_arguments(method, rpc_version): ...\ndef is_logger_configured(): ...\ndef add_stdout_logger(level='debug'): ...\ndef add_file_logger(filepath, level='debug'): ...\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testFormatSpeed", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000952.py"} {"focal_file": "transmissionrpc/utils.py", "focal_class": null, "focal_method": "format_timedelta", "tests": "import unittest\n\nclass Test_format_timedelta(unittest.TestCase):\n def testFormatTimedelta(self):\n table = {datetime.timedelta(0, 0): '0 00:00:00', datetime.timedelta(0, 10): '0 00:00:10', datetime.timedelta(0, 60): '0 00:01:00', datetime.timedelta(0, 61): '0 00:01:01', datetime.timedelta(0, 3661): '0 01:01:01', datetime.timedelta(1, 3661): '1 01:01:01', datetime.timedelta(13, 65660): '13 18:14:20'}\n for delta, expected in iter(table.items()):\n self.assertEqual(tu.format_timedelta(delta), expected)\n", "method_code": "def format_timedelta(delta):\n \"\"\"\n Format datetime.timedelta into ::.\n \"\"\"\n minutes, seconds = divmod(delta.seconds, 60)\n hours, minutes = divmod(minutes, 60)\n return '%d %02d:%02d:%02d' % (delta.days, hours, minutes, seconds)", "context": "def format_timedelta(delta): ...\ndef format_size(size): ...\ndef format_speed(size): ...\ndef format_timedelta(delta): ...\ndef format_timestamp(timestamp, utc=False): ...\ndef inet_address(address, default_port, default_address='localhost'): ...\ndef rpc_bool(arg): ...\ndef make_python_name(name): ...\ndef make_rpc_name(name): ...\ndef argument_value_convert(method, argument, value, rpc_version): ...\ndef get_arguments(method, rpc_version): ...\ndef is_logger_configured(): ...\ndef add_stdout_logger(level='debug'): ...\ndef add_file_logger(filepath, level='debug'): ...\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testFormatTimedelta", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000953.py"} {"focal_file": "transmissionrpc/utils.py", "focal_class": null, "focal_method": "format_timestamp", "tests": "import unittest\n\nclass Test_format_timestamp(unittest.TestCase):\n def testFormatTimestamp(self):\n table = {0: '-', 1: '1970-01-01 00:00:01', 1129135532: '2005-10-12 16:45:32'}\n for timestamp, expected in iter(table.items()):\n self.assertEqual(tu.format_timestamp(timestamp, utc=True), expected)\n", "method_code": "def format_timestamp(timestamp, utc=False):\n \"\"\"\n Format unix timestamp into ISO date format.\n \"\"\"\n if timestamp > 0:\n if utc:\n dt_timestamp = datetime.datetime.utcfromtimestamp(timestamp)\n else:\n dt_timestamp = datetime.datetime.fromtimestamp(timestamp)\n return dt_timestamp.isoformat(' ')\n else:\n return '-'", "context": "def format_timestamp(timestamp, utc=False): ...\ndef format_size(size): ...\ndef format_speed(size): ...\ndef format_timedelta(delta): ...\ndef format_timestamp(timestamp, utc=False): ...\ndef inet_address(address, default_port, default_address='localhost'): ...\ndef rpc_bool(arg): ...\ndef make_python_name(name): ...\ndef make_rpc_name(name): ...\ndef argument_value_convert(method, argument, value, rpc_version): ...\ndef get_arguments(method, rpc_version): ...\ndef is_logger_configured(): ...\ndef add_stdout_logger(level='debug'): ...\ndef add_file_logger(filepath, level='debug'): ...\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testFormatTimestamp", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000954.py"} {"focal_file": "transmissionrpc/utils.py", "focal_class": null, "focal_method": "inet_address", "tests": "import unittest\n\nclass Test_inet_address(unittest.TestCase):\n def testInetAddress(self):\n table = {('127.0.0.1:80', 2000): ('127.0.0.1', 80), ('127.0.0.1', 2000): ('127.0.0.1', 2000), (':80', 2000): ('localhost', 80), (':80', 2000, '127.0.0.1'): ('127.0.0.1', 80), ('0.0.0.0:443', 2000): ('0.0.0.0', 443), ('localhost:443', 2000): ('localhost', 443)}\n for args, expected in iter(table.items()):\n self.assertEqual(tu.inet_address(*args), expected)\n self.assertRaises(tu.INetAddressError, tu.inet_address, '256.256.256.256', 2000)\n", "method_code": "def inet_address(address, default_port, default_address='localhost'):\n \"\"\"\n Parse internet address.\n \"\"\"\n addr = address.split(':')\n if len(addr) == 1:\n try:\n port = int(addr[0])\n addr = default_address\n except ValueError:\n addr = addr[0]\n port = default_port\n elif len(addr) == 2:\n try:\n port = int(addr[1])\n except ValueError:\n raise INetAddressError('Invalid address \"%s\".' % address)\n if addr[0]:\n addr = addr[0]\n else:\n addr = default_address\n else:\n raise INetAddressError('Invalid address \"%s\".' % address)\n try:\n socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM)\n except socket.gaierror:\n raise INetAddressError('Cannot look up address \"%s\".' % address)\n return (addr, port)", "context": "def inet_address(address, default_port, default_address='localhost'): ...\ndef format_size(size): ...\ndef format_speed(size): ...\ndef format_timedelta(delta): ...\ndef format_timestamp(timestamp, utc=False): ...\ndef inet_address(address, default_port, default_address='localhost'): ...\ndef rpc_bool(arg): ...\ndef make_python_name(name): ...\ndef make_rpc_name(name): ...\ndef argument_value_convert(method, argument, value, rpc_version): ...\ndef get_arguments(method, rpc_version): ...\ndef is_logger_configured(): ...\ndef add_stdout_logger(level='debug'): ...\ndef add_file_logger(filepath, level='debug'): ...\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testInetAddress", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000955.py"} {"focal_file": "transmissionrpc/client.py", "focal_class": null, "focal_method": "add_torrent", "tests": "import unittest\n\nclass Test_add_torrent(unittest.TestCase):\n def testAddTorrent(self):\n data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')\n tc = createClient(test_name='add_torrent_base64')\n torrent_path = os.path.join(data_path, 'ubuntu-12.04.2-alternate-amd64.iso.torrent')\n with open(torrent_path, 'rb') as data:\n data_b64 = base64.b64encode(data.read()).decode('utf-8')\n r = tc.add_torrent(data_b64)\n self.assertEqual(r.id, 0)\n self.assertEqual(r.hashString, 'a21c45469c565f3fb9595e4e9707e6e9d45abca6')\n self.assertEqual(r.name, 'ubuntu-12.04.2-alternate-amd64.iso')\n tc = createClient(test_name='adduri')\n self.assertRaises(ValueError, tc.add_torrent, None)\n r = tc.add_torrent('torrent.txt', paused=False, download_dir='/var/downloads', peer_limit=1)\n self.assertEqual(r.id, 0)\n self.assertEqual(r.hashString, 'A000')\n self.assertEqual(r.name, 'testtransfer0')\n r = tc.add_torrent('file://' + os.path.join(data_path, 'torrent.txt'), paused=True, download_dir='/tmp', peer_limit=200)\n self.assertEqual(r.id, 1)\n self.assertEqual(r.hashString, 'A001')\n self.assertEqual(r.name, 'testtransfer1')\n r = tc.add_torrent('file://' + os.path.join(data_path, 'ubuntu-12.04.2-alternate-amd64.iso.torrent'))\n self.assertEqual(r.id, 2)\n self.assertEqual(r.hashString, 'a21c45469c565f3fb9595e4e9707e6e9d45abca6')\n self.assertEqual(r.name, 'ubuntu-12.04.2-alternate-amd64.iso')\n r = tc.add_torrent('file://' + os.path.join(data_path, 'ubuntu-12.04.2-alternate-amd64.iso.torrent.gz'))\n self.assertEqual(r.id, 3)\n self.assertEqual(r.hashString, 'a21c45469c565f3fb9595e4e9707e6e9d45abca6')\n self.assertEqual(r.name, 'ubuntu-12.04.2-alternate-amd64.iso')\n", "method_code": " def add_torrent(self, torrent, timeout=None, **kwargs):\n \"\"\"\n Add torrent to transfers list. Takes a uri to a torrent or base64 encoded torrent data in ``torrent``.\n Additional arguments are:\n \n ===================== ===== =========== =============================================================\n Argument RPC Replaced by Description\n ===================== ===== =========== =============================================================\n ``bandwidthPriority`` 8 - Priority for this transfer.\n ``cookies`` 13 - One or more HTTP cookie(s).\n ``download_dir`` 1 - The directory where the downloaded contents will be saved in.\n ``files_unwanted`` 1 - A list of file id's that shouldn't be downloaded.\n ``files_wanted`` 1 - A list of file id's that should be downloaded.\n ``paused`` 1 - If True, does not start the transfer when added.\n ``peer_limit`` 1 - Maximum number of peers allowed.\n ``priority_high`` 1 - A list of file id's that should have high priority.\n ``priority_low`` 1 - A list of file id's that should have low priority.\n ``priority_normal`` 1 - A list of file id's that should have normal priority.\n ===================== ===== =========== =============================================================\n \n Returns a Torrent object with the fields.\n \"\"\"\n if torrent is None:\n raise ValueError('add_torrent requires data or a URI.')\n torrent_data = None\n parsed_uri = urlparse(torrent)\n if parsed_uri.scheme in ['ftp', 'ftps', 'http', 'https']:\n try:\n torrent_file = urlopen(torrent)\n if torrent_file.info().get('Content-Encoding') == 'gzip':\n torrent_data = gzip.decompress(torrent_file.read())\n else:\n torrent_data = torrent_file.read()\n torrent_data = base64.b64encode(torrent_data).decode('utf-8')\n except HTTPError as e:\n if e.code == 302 and e.url.startswith('magnet:'):\n return self.add_torrent(e.url, timeout=timeout, **kwargs)\n else:\n raise e\n if parsed_uri.scheme in ['file']:\n filepath = torrent\n if parsed_uri.path:\n filepath = parsed_uri.path\n elif parsed_uri.netloc:\n filepath = parsed_uri.netloc\n if filepath.endswith('.gz'):\n with gzip.open(filepath, 'rb') as torrent_file:\n torrent_data = torrent_file.read()\n else:\n with open(filepath, 'rb') as torrent_file:\n torrent_data = torrent_file.read()\n torrent_data = base64.b64encode(torrent_data).decode('utf-8')\n if not torrent_data:\n if torrent.endswith('.torrent') or torrent.startswith('magnet:'):\n torrent_data = None\n else:\n might_be_base64 = False\n try:\n base64.b64decode(torrent.encode('utf-8'))\n might_be_base64 = True\n except Exception:\n pass\n if might_be_base64:\n torrent_data = torrent\n args = {}\n if torrent_data:\n args = {'metainfo': torrent_data}\n else:\n args = {'filename': torrent}\n for key, value in list(kwargs.items()):\n argument = make_rpc_name(key)\n arg, val = argument_value_convert('torrent-add', argument, value, self.rpc_version)\n args[arg] = val\n return list(self._request('torrent-add', args, timeout=timeout).values())[0]\n ", "context": "class Client():\n def add_torrent(self, torrent, timeout=None, **kwargs): ...\n def __init__(self, address='localhost', port=DEFAULT_PORT, user=None, password=None, http_handler=None, timeout=None): ...\n def _get_timeout(self): ...\n def _set_timeout(self, value): ...\n def _del_timeout(self): ...\n def _http_query(self, query, timeout=None): ...\n def _request(self, method, arguments=None, ids=None, require_ids=False, timeout=None): ...\n def _update_session(self, data): ...\n def _update_server_version(self): ...\n def rpc_version(self): ...\n def _rpc_version_warning(self, version): ...\n def remove_torrent(self, ids, delete_data=False, timeout=None): ...\n def start_torrent(self, ids, bypass_queue=False, timeout=None): ...\n def start_all(self, bypass_queue=False, timeout=None): ...\n def stop_torrent(self, ids, timeout=None): ...\n def verify_torrent(self, ids, timeout=None): ...\n def reannounce_torrent(self, ids, timeout=None): ...\n def get_torrent(self, torrent_id, arguments=None, timeout=None): ...\n def get_torrents(self, ids=None, arguments=None, timeout=None): ...\n def get_files(self, ids=None, timeout=None): ...\n def set_files(self, items, timeout=None): ...\n def change_torrent(self, ids, timeout=None, **kwargs): ...\n def move_torrent_data(self, ids, location, timeout=None): ...\n def locate_torrent_data(self, ids, location, timeout=None): ...\n def rename_torrent_path(self, torrent_id, location, name, timeout=None): ...\n def queue_top(self, ids, timeout=None): ...\n def queue_bottom(self, ids, timeout=None): ...\n def queue_up(self, ids, timeout=None): ...\n def queue_down(self, ids, timeout=None): ...\n def get_session(self, timeout=None): ...\n def set_session(self, timeout=None, **kwargs): ...\n def blocklist_update(self, timeout=None): ...\n def port_test(self, timeout=None): ...\n def free_space(self, path, timeout=None): ...\n def session_stats(self, timeout=None): ...\n\n self._sequence = 0\n self.session = None\n self.session_id = 0\n self.server_version = None\n self.protocol_version = None\n self.torrent_get_arguments = get_arguments('torrent-get', self.rpc_version)\n\n timeout = property(_get_timeout, _set_timeout, _del_timeout, doc='HTTP query timeout.')\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testAddTorrent", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000956.py"} {"focal_file": "transmissionrpc/client.py", "focal_class": null, "focal_method": "remove_torrent", "tests": "import unittest\n\nclass Test_remove_torrent(unittest.TestCase):\n def testRemoveTorrent(self):\n tc = createClient(test_name='remove')\n tc.remove_torrent(['b000', 2, 3])\n tc.remove_torrent(1, delete_data=True)\n tc.remove_torrent('b002', delete_data=False)\n", "method_code": " def remove_torrent(self, ids, delete_data=False, timeout=None):\n \"\"\"\n remove torrent(s) with provided id(s). Local data is removed if\n delete_data is True, otherwise not.\n \"\"\"\n self._rpc_version_warning(3)\n self._request('torrent-remove', {'delete-local-data': rpc_bool(delete_data)}, ids, True, timeout=timeout)\n ", "context": "class Client():\n def remove_torrent(self, ids, delete_data=False, timeout=None): ...\n def __init__(self, address='localhost', port=DEFAULT_PORT, user=None, password=None, http_handler=None, timeout=None): ...\n def _get_timeout(self): ...\n def _set_timeout(self, value): ...\n def _del_timeout(self): ...\n def _http_query(self, query, timeout=None): ...\n def _request(self, method, arguments=None, ids=None, require_ids=False, timeout=None): ...\n def _update_session(self, data): ...\n def _update_server_version(self): ...\n def rpc_version(self): ...\n def _rpc_version_warning(self, version): ...\n def add_torrent(self, torrent, timeout=None, **kwargs): ...\n def start_torrent(self, ids, bypass_queue=False, timeout=None): ...\n def start_all(self, bypass_queue=False, timeout=None): ...\n def stop_torrent(self, ids, timeout=None): ...\n def verify_torrent(self, ids, timeout=None): ...\n def reannounce_torrent(self, ids, timeout=None): ...\n def get_torrent(self, torrent_id, arguments=None, timeout=None): ...\n def get_torrents(self, ids=None, arguments=None, timeout=None): ...\n def get_files(self, ids=None, timeout=None): ...\n def set_files(self, items, timeout=None): ...\n def change_torrent(self, ids, timeout=None, **kwargs): ...\n def move_torrent_data(self, ids, location, timeout=None): ...\n def locate_torrent_data(self, ids, location, timeout=None): ...\n def rename_torrent_path(self, torrent_id, location, name, timeout=None): ...\n def queue_top(self, ids, timeout=None): ...\n def queue_bottom(self, ids, timeout=None): ...\n def queue_up(self, ids, timeout=None): ...\n def queue_down(self, ids, timeout=None): ...\n def get_session(self, timeout=None): ...\n def set_session(self, timeout=None, **kwargs): ...\n def blocklist_update(self, timeout=None): ...\n def port_test(self, timeout=None): ...\n def free_space(self, path, timeout=None): ...\n def session_stats(self, timeout=None): ...\n\n self._sequence = 0\n self.session = None\n self.session_id = 0\n self.server_version = None\n self.protocol_version = None\n self.torrent_get_arguments = get_arguments('torrent-get', self.rpc_version)\n\n timeout = property(_get_timeout, _set_timeout, _del_timeout, doc='HTTP query timeout.')\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testRemoveTorrent", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000957.py"} {"focal_file": "transmissionrpc/client.py", "focal_class": null, "focal_method": "start_torrent", "tests": "import unittest\n\nclass Test_start_torrent(unittest.TestCase):\n def testStartTorrent(self):\n tc = createClient(test_name='start')\n tc.start_torrent(['abcdef', 20, 30])\n tc.start_torrent(1)\n tc.start_torrent('a0123456789')\n", "method_code": " def start_torrent(self, ids, bypass_queue=False, timeout=None):\n \"\"\"Start torrent(s) with provided id(s)\"\"\"\n method = 'torrent-start'\n if bypass_queue and self.rpc_version >= 14:\n method = 'torrent-start-now'\n self._request(method, {}, ids, True, timeout=timeout)\n ", "context": "class Client():\n def start_torrent(self, ids, bypass_queue=False, timeout=None): ...\n def __init__(self, address='localhost', port=DEFAULT_PORT, user=None, password=None, http_handler=None, timeout=None): ...\n def _get_timeout(self): ...\n def _set_timeout(self, value): ...\n def _del_timeout(self): ...\n def _http_query(self, query, timeout=None): ...\n def _request(self, method, arguments=None, ids=None, require_ids=False, timeout=None): ...\n def _update_session(self, data): ...\n def _update_server_version(self): ...\n def rpc_version(self): ...\n def _rpc_version_warning(self, version): ...\n def add_torrent(self, torrent, timeout=None, **kwargs): ...\n def remove_torrent(self, ids, delete_data=False, timeout=None): ...\n def start_all(self, bypass_queue=False, timeout=None): ...\n def stop_torrent(self, ids, timeout=None): ...\n def verify_torrent(self, ids, timeout=None): ...\n def reannounce_torrent(self, ids, timeout=None): ...\n def get_torrent(self, torrent_id, arguments=None, timeout=None): ...\n def get_torrents(self, ids=None, arguments=None, timeout=None): ...\n def get_files(self, ids=None, timeout=None): ...\n def set_files(self, items, timeout=None): ...\n def change_torrent(self, ids, timeout=None, **kwargs): ...\n def move_torrent_data(self, ids, location, timeout=None): ...\n def locate_torrent_data(self, ids, location, timeout=None): ...\n def rename_torrent_path(self, torrent_id, location, name, timeout=None): ...\n def queue_top(self, ids, timeout=None): ...\n def queue_bottom(self, ids, timeout=None): ...\n def queue_up(self, ids, timeout=None): ...\n def queue_down(self, ids, timeout=None): ...\n def get_session(self, timeout=None): ...\n def set_session(self, timeout=None, **kwargs): ...\n def blocklist_update(self, timeout=None): ...\n def port_test(self, timeout=None): ...\n def free_space(self, path, timeout=None): ...\n def session_stats(self, timeout=None): ...\n\n self._sequence = 0\n self.session = None\n self.session_id = 0\n self.server_version = None\n self.protocol_version = None\n self.torrent_get_arguments = get_arguments('torrent-get', self.rpc_version)\n\n timeout = property(_get_timeout, _set_timeout, _del_timeout, doc='HTTP query timeout.')\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testStartTorrent", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000958.py"} {"focal_file": "transmissionrpc/client.py", "focal_class": null, "focal_method": "stop_torrent", "tests": "import unittest\n\nclass Test_stop_torrent(unittest.TestCase):\n def testStopTorrent(self):\n tc = createClient(test_name='stop')\n tc.stop_torrent(2)\n tc.stop_torrent('bad')\n tc.stop_torrent(['bad', 'ba5', '30', 20])\n", "method_code": " def stop_torrent(self, ids, timeout=None):\n \"\"\"stop torrent(s) with provided id(s)\"\"\"\n self._request('torrent-stop', {}, ids, True, timeout=timeout)\n ", "context": "class Client():\n def stop_torrent(self, ids, timeout=None): ...\n def __init__(self, address='localhost', port=DEFAULT_PORT, user=None, password=None, http_handler=None, timeout=None): ...\n def _get_timeout(self): ...\n def _set_timeout(self, value): ...\n def _del_timeout(self): ...\n def _http_query(self, query, timeout=None): ...\n def _request(self, method, arguments=None, ids=None, require_ids=False, timeout=None): ...\n def _update_session(self, data): ...\n def _update_server_version(self): ...\n def rpc_version(self): ...\n def _rpc_version_warning(self, version): ...\n def add_torrent(self, torrent, timeout=None, **kwargs): ...\n def remove_torrent(self, ids, delete_data=False, timeout=None): ...\n def start_torrent(self, ids, bypass_queue=False, timeout=None): ...\n def start_all(self, bypass_queue=False, timeout=None): ...\n def verify_torrent(self, ids, timeout=None): ...\n def reannounce_torrent(self, ids, timeout=None): ...\n def get_torrent(self, torrent_id, arguments=None, timeout=None): ...\n def get_torrents(self, ids=None, arguments=None, timeout=None): ...\n def get_files(self, ids=None, timeout=None): ...\n def set_files(self, items, timeout=None): ...\n def change_torrent(self, ids, timeout=None, **kwargs): ...\n def move_torrent_data(self, ids, location, timeout=None): ...\n def locate_torrent_data(self, ids, location, timeout=None): ...\n def rename_torrent_path(self, torrent_id, location, name, timeout=None): ...\n def queue_top(self, ids, timeout=None): ...\n def queue_bottom(self, ids, timeout=None): ...\n def queue_up(self, ids, timeout=None): ...\n def queue_down(self, ids, timeout=None): ...\n def get_session(self, timeout=None): ...\n def set_session(self, timeout=None, **kwargs): ...\n def blocklist_update(self, timeout=None): ...\n def port_test(self, timeout=None): ...\n def free_space(self, path, timeout=None): ...\n def session_stats(self, timeout=None): ...\n\n self._sequence = 0\n self.session = None\n self.session_id = 0\n self.server_version = None\n self.protocol_version = None\n self.torrent_get_arguments = get_arguments('torrent-get', self.rpc_version)\n\n timeout = property(_get_timeout, _set_timeout, _del_timeout, doc='HTTP query timeout.')\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testStopTorrent", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000959.py"} {"focal_file": "transmissionrpc/client.py", "focal_class": null, "focal_method": "verify_torrent", "tests": "import unittest\n\nclass Test_verify_torrent(unittest.TestCase):\n def testVerifyTorrent(self):\n tc = createClient(test_name='verify')\n tc.verify_torrent(10000)\n tc.verify_torrent('d')\n tc.verify_torrent(['a', 'b', 'c'])\n", "method_code": " def verify_torrent(self, ids, timeout=None):\n \"\"\"verify torrent(s) with provided id(s)\"\"\"\n self._request('torrent-verify', {}, ids, True, timeout=timeout)\n ", "context": "class Client():\n def verify_torrent(self, ids, timeout=None): ...\n def __init__(self, address='localhost', port=DEFAULT_PORT, user=None, password=None, http_handler=None, timeout=None): ...\n def _get_timeout(self): ...\n def _set_timeout(self, value): ...\n def _del_timeout(self): ...\n def _http_query(self, query, timeout=None): ...\n def _request(self, method, arguments=None, ids=None, require_ids=False, timeout=None): ...\n def _update_session(self, data): ...\n def _update_server_version(self): ...\n def rpc_version(self): ...\n def _rpc_version_warning(self, version): ...\n def add_torrent(self, torrent, timeout=None, **kwargs): ...\n def remove_torrent(self, ids, delete_data=False, timeout=None): ...\n def start_torrent(self, ids, bypass_queue=False, timeout=None): ...\n def start_all(self, bypass_queue=False, timeout=None): ...\n def stop_torrent(self, ids, timeout=None): ...\n def reannounce_torrent(self, ids, timeout=None): ...\n def get_torrent(self, torrent_id, arguments=None, timeout=None): ...\n def get_torrents(self, ids=None, arguments=None, timeout=None): ...\n def get_files(self, ids=None, timeout=None): ...\n def set_files(self, items, timeout=None): ...\n def change_torrent(self, ids, timeout=None, **kwargs): ...\n def move_torrent_data(self, ids, location, timeout=None): ...\n def locate_torrent_data(self, ids, location, timeout=None): ...\n def rename_torrent_path(self, torrent_id, location, name, timeout=None): ...\n def queue_top(self, ids, timeout=None): ...\n def queue_bottom(self, ids, timeout=None): ...\n def queue_up(self, ids, timeout=None): ...\n def queue_down(self, ids, timeout=None): ...\n def get_session(self, timeout=None): ...\n def set_session(self, timeout=None, **kwargs): ...\n def blocklist_update(self, timeout=None): ...\n def port_test(self, timeout=None): ...\n def free_space(self, path, timeout=None): ...\n def session_stats(self, timeout=None): ...\n\n self._sequence = 0\n self.session = None\n self.session_id = 0\n self.server_version = None\n self.protocol_version = None\n self.torrent_get_arguments = get_arguments('torrent-get', self.rpc_version)\n\n timeout = property(_get_timeout, _set_timeout, _del_timeout, doc='HTTP query timeout.')\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testVerifyTorrent", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000960.py"} {"focal_file": "transmissionrpc/client.py", "focal_class": null, "focal_method": "get_torrent", "tests": "import unittest\n\nclass Test_get_torrent(unittest.TestCase):\n def testGetTorrent(self):\n tc = createClient(test_name='get_torrent')\n torrent = tc.get_torrent(2)\n self.assertEqual(torrent.id, 2)\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n tc = createClient(test_name='get_torrent_hash')\n torrent = tc.get_torrent('ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n self.assertEqual(torrent.id, 2)\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n", "method_code": " def get_torrent(self, torrent_id, arguments=None, timeout=None):\n \"\"\"\n Get information for torrent with provided id.\n ``arguments`` contains a list of field names to be returned, when None\n all fields are requested. See the Torrent class for more information.\n \n Returns a Torrent object with the requested fields.\n \"\"\"\n if not arguments:\n arguments = self.torrent_get_arguments\n torrent_id = parse_torrent_id(torrent_id)\n if torrent_id is None:\n raise ValueError('Invalid id')\n result = self._request('torrent-get', {'fields': arguments}, torrent_id, require_ids=True, timeout=timeout)\n if torrent_id in result:\n return result[torrent_id]\n else:\n for torrent in list(result.values()):\n if torrent.hashString == torrent_id:\n return torrent\n raise KeyError('Torrent not found in result')\n ", "context": "class Client():\n def get_torrent(self, torrent_id, arguments=None, timeout=None): ...\n def __init__(self, address='localhost', port=DEFAULT_PORT, user=None, password=None, http_handler=None, timeout=None): ...\n def _get_timeout(self): ...\n def _set_timeout(self, value): ...\n def _del_timeout(self): ...\n def _http_query(self, query, timeout=None): ...\n def _request(self, method, arguments=None, ids=None, require_ids=False, timeout=None): ...\n def _update_session(self, data): ...\n def _update_server_version(self): ...\n def rpc_version(self): ...\n def _rpc_version_warning(self, version): ...\n def add_torrent(self, torrent, timeout=None, **kwargs): ...\n def remove_torrent(self, ids, delete_data=False, timeout=None): ...\n def start_torrent(self, ids, bypass_queue=False, timeout=None): ...\n def start_all(self, bypass_queue=False, timeout=None): ...\n def stop_torrent(self, ids, timeout=None): ...\n def verify_torrent(self, ids, timeout=None): ...\n def reannounce_torrent(self, ids, timeout=None): ...\n def get_torrents(self, ids=None, arguments=None, timeout=None): ...\n def get_files(self, ids=None, timeout=None): ...\n def set_files(self, items, timeout=None): ...\n def change_torrent(self, ids, timeout=None, **kwargs): ...\n def move_torrent_data(self, ids, location, timeout=None): ...\n def locate_torrent_data(self, ids, location, timeout=None): ...\n def rename_torrent_path(self, torrent_id, location, name, timeout=None): ...\n def queue_top(self, ids, timeout=None): ...\n def queue_bottom(self, ids, timeout=None): ...\n def queue_up(self, ids, timeout=None): ...\n def queue_down(self, ids, timeout=None): ...\n def get_session(self, timeout=None): ...\n def set_session(self, timeout=None, **kwargs): ...\n def blocklist_update(self, timeout=None): ...\n def port_test(self, timeout=None): ...\n def free_space(self, path, timeout=None): ...\n def session_stats(self, timeout=None): ...\n\n self._sequence = 0\n self.session = None\n self.session_id = 0\n self.server_version = None\n self.protocol_version = None\n self.torrent_get_arguments = get_arguments('torrent-get', self.rpc_version)\n\n timeout = property(_get_timeout, _set_timeout, _del_timeout, doc='HTTP query timeout.')\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testGetTorrent", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000961.py"} {"focal_file": "transmissionrpc/client.py", "focal_class": null, "focal_method": "get_torrents", "tests": "import unittest\n\nclass Test_get_torrents(unittest.TestCase):\n def testGetTorrents(self):\n tc = createClient(test_name='info')\n r = tc.get_torrents()\n for torrent in r:\n if torrent.id == 2:\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n elif torrent.id == 3:\n self.assertEqual(torrent.name, 'ubuntu-10.04-alternate-i386.iso')\n self.assertEqual(torrent.hashString, 'a33e98826003515e46ef5075fcbf4914b307abe2')\n else:\n self.fail('Unknown torrent')\n\n def testGetTorrentsRange(self):\n tc = createClient(test_name='get_torrents_2to3')\n r = tc.get_torrents([2, 3])\n for torrent in r:\n if torrent.id == 2:\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n elif torrent.id == 3:\n self.assertEqual(torrent.name, 'ubuntu-10.04-alternate-i386.iso')\n self.assertEqual(torrent.hashString, 'a33e98826003515e46ef5075fcbf4914b307abe2')\n else:\n self.fail('Unknown torrent')\n tc = createClient(test_name='get_torrents_2to3')\n r = tc.get_torrents('2:3')\n for torrent in r:\n if torrent.id == 2:\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n elif torrent.id == 3:\n self.assertEqual(torrent.name, 'ubuntu-10.04-alternate-i386.iso')\n self.assertEqual(torrent.hashString, 'a33e98826003515e46ef5075fcbf4914b307abe2')\n else:\n self.fail('Unknown torrent')\n tc = createClient(test_name='get_torrents_2to3')\n r = tc.get_torrents('2,3')\n for torrent in r:\n if torrent.id == 2:\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n elif torrent.id == 3:\n self.assertEqual(torrent.name, 'ubuntu-10.04-alternate-i386.iso')\n self.assertEqual(torrent.hashString, 'a33e98826003515e46ef5075fcbf4914b307abe2')\n else:\n self.fail('Unknown torrent')\n tc = createClient(test_name='get_torrents_2to3')\n r = tc.get_torrents('2 3')\n for torrent in r:\n if torrent.id == 2:\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n elif torrent.id == 3:\n self.assertEqual(torrent.name, 'ubuntu-10.04-alternate-i386.iso')\n self.assertEqual(torrent.hashString, 'a33e98826003515e46ef5075fcbf4914b307abe2')\n else:\n self.fail('Unknown torrent')\n\n def testGetTorrentsHashes(self):\n tc = createClient(test_name='get_torrents_hashes')\n r = tc.get_torrents(['ab8ea951c022d4745a9b06ab8020b952a52b71ca', 'a33e98826003515e46ef5075fcbf4914b307abe2'])\n for torrent in r:\n if torrent.id == 2:\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n elif torrent.id == 3:\n self.assertEqual(torrent.name, 'ubuntu-10.04-alternate-i386.iso')\n self.assertEqual(torrent.hashString, 'a33e98826003515e46ef5075fcbf4914b307abe2')\n else:\n self.fail('Unknown torrent')\n tc = createClient(test_name='get_torrents_hashes')\n r = tc.get_torrents('ab8ea951c022d4745a9b06ab8020b952a52b71ca,a33e98826003515e46ef5075fcbf4914b307abe2')\n for torrent in r:\n if torrent.id == 2:\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n elif torrent.id == 3:\n self.assertEqual(torrent.name, 'ubuntu-10.04-alternate-i386.iso')\n self.assertEqual(torrent.hashString, 'a33e98826003515e46ef5075fcbf4914b307abe2')\n else:\n self.fail('Unknown torrent')\n tc = createClient(test_name='get_torrents_hashes')\n r = tc.get_torrents('ab8ea951c022d4745a9b06ab8020b952a52b71ca a33e98826003515e46ef5075fcbf4914b307abe2')\n for torrent in r:\n if torrent.id == 2:\n self.assertEqual(torrent.name, 'ubuntu-10.04-server-amd64.iso')\n self.assertEqual(torrent.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')\n elif torrent.id == 3:\n self.assertEqual(torrent.name, 'ubuntu-10.04-alternate-i386.iso')\n self.assertEqual(torrent.hashString, 'a33e98826003515e46ef5075fcbf4914b307abe2')\n else:\n self.fail('Unknown torrent')\n", "method_code": " def get_torrents(self, ids=None, arguments=None, timeout=None):\n \"\"\"\n Get information for torrents with provided ids. For more information see get_torrent.\n \n Returns a list of Torrent object.\n \"\"\"\n if not arguments:\n arguments = self.torrent_get_arguments\n return list(self._request('torrent-get', {'fields': arguments}, ids, timeout=timeout).values())\n ", "context": "class Client():\n def get_torrents(self, ids=None, arguments=None, timeout=None): ...\n def __init__(self, address='localhost', port=DEFAULT_PORT, user=None, password=None, http_handler=None, timeout=None): ...\n def _get_timeout(self): ...\n def _set_timeout(self, value): ...\n def _del_timeout(self): ...\n def _http_query(self, query, timeout=None): ...\n def _request(self, method, arguments=None, ids=None, require_ids=False, timeout=None): ...\n def _update_session(self, data): ...\n def _update_server_version(self): ...\n def rpc_version(self): ...\n def _rpc_version_warning(self, version): ...\n def add_torrent(self, torrent, timeout=None, **kwargs): ...\n def remove_torrent(self, ids, delete_data=False, timeout=None): ...\n def start_torrent(self, ids, bypass_queue=False, timeout=None): ...\n def start_all(self, bypass_queue=False, timeout=None): ...\n def stop_torrent(self, ids, timeout=None): ...\n def verify_torrent(self, ids, timeout=None): ...\n def reannounce_torrent(self, ids, timeout=None): ...\n def get_torrent(self, torrent_id, arguments=None, timeout=None): ...\n def get_files(self, ids=None, timeout=None): ...\n def set_files(self, items, timeout=None): ...\n def change_torrent(self, ids, timeout=None, **kwargs): ...\n def move_torrent_data(self, ids, location, timeout=None): ...\n def locate_torrent_data(self, ids, location, timeout=None): ...\n def rename_torrent_path(self, torrent_id, location, name, timeout=None): ...\n def queue_top(self, ids, timeout=None): ...\n def queue_bottom(self, ids, timeout=None): ...\n def queue_up(self, ids, timeout=None): ...\n def queue_down(self, ids, timeout=None): ...\n def get_session(self, timeout=None): ...\n def set_session(self, timeout=None, **kwargs): ...\n def blocklist_update(self, timeout=None): ...\n def port_test(self, timeout=None): ...\n def free_space(self, path, timeout=None): ...\n def session_stats(self, timeout=None): ...\n\n self._sequence = 0\n self.session = None\n self.session_id = 0\n self.server_version = None\n self.protocol_version = None\n self.torrent_get_arguments = get_arguments('torrent-get', self.rpc_version)\n\n timeout = property(_get_timeout, _set_timeout, _del_timeout, doc='HTTP query timeout.')\n", "repository": "0x022b/transmissionrpc-ng", "test_name": "testGetTorrents", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000962.py"} {"focal_file": "erpnext/buying/doctype/purchase_order/purchase_order.py", "focal_class": null, "focal_method": "make_purchase_receipt", "tests": "import unittest\n\nclass Test_make_purchase_receipt(unittest.TestCase):\n def test_make_purchase_receipt(self):\n from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt\n po = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_purchase_receipt, po.name)\n po = frappe.get_doc('Purchase Order', po.name)\n po.submit()\n pr = make_purchase_receipt(po.name)\n pr.supplier_warehouse = '_Test Warehouse 1 - _TC'\n pr.posting_date = '2013-05-12'\n self.assertEquals(pr.doctype, 'Purchase Receipt')\n self.assertEquals(len(pr.get('purchase_receipt_details')), len(test_records[0]['po_details']))\n pr.naming_series = '_T-Purchase Receipt-'\n frappe.get_doc(pr).insert()\n", "method_code": "def make_purchase_receipt(source_name, target_doc=None):\n\n def update_item(obj, target, source_parent):\n target.qty = flt(obj.qty) - flt(obj.received_qty)\n target.stock_qty = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.conversion_factor)\n target.amount = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.rate)\n target.base_amount = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.rate) * flt(source_parent.conversion_rate)\n doc = get_mapped_doc('Purchase Order', source_name, {'Purchase Order': {'doctype': 'Purchase Receipt', 'validation': {'docstatus': ['=', 1]}}, 'Purchase Order Item': {'doctype': 'Purchase Receipt Item', 'field_map': {'name': 'prevdoc_detail_docname', 'parent': 'prevdoc_docname', 'parenttype': 'prevdoc_doctype'}, 'postprocess': update_item, 'condition': lambda doc: doc.received_qty < doc.qty}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doc, set_missing_values)\n return doc", "context": "@frappe.whitelist()\ndef make_purchase_receipt(source_name, target_doc=None): ...\ndef set_missing_values(source, target): ...\ndef make_purchase_receipt(source_name, target_doc=None): ...\ndef make_purchase_invoice(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_purchase_receipt", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000963.py"} {"focal_file": "erpnext/buying/doctype/purchase_order/purchase_order.py", "focal_class": null, "focal_method": "make_purchase_invoice", "tests": "import unittest\n\nclass Test_make_purchase_invoice(unittest.TestCase):\n def test_make_purchase_invoice(self):\n from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_invoice\n po = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_purchase_invoice, po.name)\n po = frappe.get_doc('Purchase Order', po.name)\n po.submit()\n pi = make_purchase_invoice(po.name)\n self.assertEquals(pi.doctype, 'Purchase Invoice')\n self.assertEquals(len(pi.get('entries', [])), len(test_records[0]['po_details']))\n pi.posting_date = '2013-05-12'\n pi.bill_no = 'NA'\n frappe.get_doc(pi).insert()\n", "method_code": "def make_purchase_invoice(source_name, target_doc=None):\n\n def update_item(obj, target, source_parent):\n target.amount = flt(obj.amount) - flt(obj.billed_amt)\n target.base_amount = target.amount * flt(source_parent.conversion_rate)\n target.qty = target.amount / flt(obj.rate) if flt(obj.rate) and flt(obj.billed_amt) else flt(obj.qty)\n doc = get_mapped_doc('Purchase Order', source_name, {'Purchase Order': {'doctype': 'Purchase Invoice', 'validation': {'docstatus': ['=', 1]}}, 'Purchase Order Item': {'doctype': 'Purchase Invoice Item', 'field_map': {'name': 'po_detail', 'parent': 'purchase_order'}, 'postprocess': update_item, 'condition': lambda doc: doc.base_amount == 0 or doc.billed_amt < doc.amount}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doc, set_missing_values)\n return doc", "context": "@frappe.whitelist()\ndef make_purchase_invoice(source_name, target_doc=None): ...\ndef set_missing_values(source, target): ...\ndef make_purchase_receipt(source_name, target_doc=None): ...\ndef make_purchase_invoice(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_purchase_invoice", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000964.py"} {"focal_file": "erpnext/buying/doctype/supplier_quotation/supplier_quotation.py", "focal_class": null, "focal_method": "make_purchase_order", "tests": "import unittest\n\nclass Test_make_purchase_order(unittest.TestCase):\n def test_make_purchase_order(self):\n from erpnext.buying.doctype.supplier_quotation.supplier_quotation import make_purchase_order\n sq = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_purchase_order, sq.name)\n sq = frappe.get_doc('Supplier Quotation', sq.name)\n sq.submit()\n po = make_purchase_order(sq.name)\n self.assertEquals(po.doctype, 'Purchase Order')\n self.assertEquals(len(po.get('po_details')), len(sq.get('quotation_items')))\n po.naming_series = '_T-Purchase Order-'\n for doc in po.get('po_details'):\n if doc.get('item_code'):\n doc.set('schedule_date', '2013-04-12')\n po.insert()\n", "method_code": "def make_purchase_order(source_name, target_doc=None):\n\n def set_missing_values(source, target):\n target.ignore_pricing_rule = 1\n target.run_method('set_missing_values')\n target.run_method('get_schedule_dates')\n target.run_method('calculate_taxes_and_totals')\n\n def update_item(obj, target, source_parent):\n target.conversion_factor = 1\n doclist = get_mapped_doc('Supplier Quotation', source_name, {'Supplier Quotation': {'doctype': 'Purchase Order', 'validation': {'docstatus': ['=', 1]}}, 'Supplier Quotation Item': {'doctype': 'Purchase Order Item', 'field_map': [['name', 'supplier_quotation_item'], ['parent', 'supplier_quotation'], ['uom', 'stock_uom'], ['uom', 'uom'], ['prevdoc_detail_docname', 'prevdoc_detail_docname'], ['prevdoc_doctype', 'prevdoc_doctype'], ['prevdoc_docname', 'prevdoc_docname']], 'postprocess': update_item}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doc, set_missing_values)\n return doclist", "context": "@frappe.whitelist()\ndef make_purchase_order(source_name, target_doc=None): ...\ndef make_purchase_order(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_purchase_order", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000965.py"} {"focal_file": "erpnext/hr/doctype/leave_block_list/leave_block_list.py", "focal_class": null, "focal_method": "get_applicable_block_dates", "tests": "import unittest\n\nclass Test_get_applicable_block_dates(unittest.TestCase):\n def test_get_applicable_block_dates(self):\n frappe.set_user('test@example.com')\n frappe.db.set_value('Department', '_Test Department', 'leave_block_list', '_Test Leave Block List')\n self.assertTrue('2013-01-02' in [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03')])\n\n def test_get_applicable_block_dates_for_allowed_user(self):\n frappe.set_user('test1@example.com')\n frappe.db.set_value('Department', '_Test Department 1', 'leave_block_list', '_Test Leave Block List')\n self.assertEquals([], [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03')])\n\n def test_get_applicable_block_dates_all_lists(self):\n frappe.set_user('test1@example.com')\n frappe.db.set_value('Department', '_Test Department 1', 'leave_block_list', '_Test Leave Block List')\n self.assertTrue('2013-01-02' in [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03', all_lists=True)])\n", "method_code": "def get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False):\n block_dates = []\n for block_list in get_applicable_block_lists(employee, company, all_lists):\n block_dates.extend(frappe.db.sql('select block_date, reason \\n\\t\\t\\tfrom `tabLeave Block List Date` where parent=%s \\n\\t\\t\\tand block_date between %s and %s', (block_list, from_date, to_date), as_dict=1))\n return block_dates", "context": "@frappe.whitelist()\ndef get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False): ...\ndef get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False): ...\ndef get_applicable_block_lists(employee=None, company=None, all_lists=False): ...\ndef is_user_in_allow_list(block_list): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_get_applicable_block_dates", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000966.py"} {"focal_file": "erpnext/manufacturing/doctype/bom/bom.py", "focal_class": null, "focal_method": "get_bom_items_as_dict", "tests": "import unittest\n\nclass Test_get_bom_items_as_dict(unittest.TestCase):\n def test_get_items(self):\n from erpnext.manufacturing.doctype.bom.bom import get_bom_items_as_dict\n items_dict = get_bom_items_as_dict(bom='BOM/_Test FG Item 2/001', qty=1, fetch_exploded=0)\n self.assertTrue(test_records[2]['bom_materials'][0]['item_code'] in items_dict)\n self.assertTrue(test_records[2]['bom_materials'][1]['item_code'] in items_dict)\n self.assertEquals(len(items_dict.values()), 2)\n", "method_code": "def get_bom_items_as_dict(bom, qty=1, fetch_exploded=1):\n item_dict = {}\n query = 'select\\n\\t\\t\\t\\tbom_item.item_code,\\n\\t\\t\\t\\titem.item_name,\\n\\t\\t\\t\\tsum(ifnull(bom_item.qty, 0)/ifnull(bom.quantity, 1)) * %(qty)s as qty,\\n\\t\\t\\t\\titem.description,\\n\\t\\t\\t\\titem.stock_uom,\\n\\t\\t\\t\\titem.default_warehouse,\\n\\t\\t\\t\\titem.expense_account as expense_account,\\n\\t\\t\\t\\titem.buying_cost_center as cost_center\\n\\t\\t\\tfrom\\n\\t\\t\\t\\t`tab%(table)s` bom_item, `tabBOM` bom, `tabItem` item\\n\\t\\t\\twhere\\n\\t\\t\\t\\tbom_item.parent = bom.name\\n\\t\\t\\t\\tand bom_item.docstatus < 2\\n\\t\\t\\t\\tand bom_item.parent = \"%(bom)s\"\\n\\t\\t\\t\\tand item.name = bom_item.item_code\\n\\t\\t\\t\\t%(conditions)s\\n\\t\\t\\t\\tgroup by item_code, stock_uom'\n if fetch_exploded:\n items = frappe.db.sql(query % {'qty': qty, 'table': 'BOM Explosion Item', 'bom': bom, 'conditions': \"and ifnull(item.is_pro_applicable, 'No') = 'No'\\n\\t\\t\\t\\t\\tand ifnull(item.is_sub_contracted_item, 'No') = 'No' \"}, as_dict=True)\n else:\n items = frappe.db.sql(query % {'qty': qty, 'table': 'BOM Item', 'bom': bom, 'conditions': ''}, as_dict=True)\n for item in items:\n if item_dict.has_key(item.item_code):\n item_dict[item.item_code]['qty'] += flt(item.qty)\n else:\n item_dict[item.item_code] = item\n return item_dict", "context": "def get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_get_items", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000967.py"} {"focal_file": "erpnext/manufacturing/doctype/bom/bom.py", "focal_class": null, "focal_method": "get_bom_items", "tests": "import unittest\n\nclass Test_get_bom_items(unittest.TestCase):\n def test_get_items_list(self):\n from erpnext.manufacturing.doctype.bom.bom import get_bom_items\n self.assertEquals(len(get_bom_items(bom='BOM/_Test FG Item 2/001', qty=1, fetch_exploded=1)), 3)\n", "method_code": "def get_bom_items(bom, qty=1, fetch_exploded=1):\n items = get_bom_items_as_dict(bom, qty, fetch_exploded).values()\n items.sort(lambda a, b: a.item_code > b.item_code and 1 or -1)\n return items", "context": "@frappe.whitelist()\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_get_items_list", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000968.py"} {"focal_file": "erpnext/accounts/party.py", "focal_class": null, "focal_method": "get_party_details", "tests": "import unittest\n\nclass Test_get_party_details(unittest.TestCase):\n def test_party_details(self):\n from erpnext.accounts.party import get_party_details\n to_check = {'selling_price_list': None, 'customer_group': '_Test Customer Group', 'contact_designation': None, 'customer_address': '_Test Address-Office', 'contact_department': None, 'contact_email': 'test_contact_customer@example.com', 'contact_mobile': None, 'sales_team': [], 'contact_display': '_Test Contact For _Test Customer', 'contact_person': '_Test Contact For _Test Customer-_Test Customer', 'territory': u'_Test Territory', 'contact_phone': '+91 0000000000', 'customer_name': '_Test Customer'}\n make_test_records('Address')\n make_test_records('Contact')\n details = get_party_details('_Test Customer')\n for key, value in to_check.iteritems():\n self.assertEquals(value, details.get(key))\n", "method_code": "def get_party_details(party=None, account=None, party_type='Customer', company=None, posting_date=None, price_list=None, currency=None, doctype=None):\n return _get_party_details(party, account, party_type, company, posting_date, price_list, currency, doctype)", "context": "@frappe.whitelist()\ndef get_party_details(party=None, account=None, party_type='Customer', company=None, posting_date=None, price_list=None, currency=None, doctype=None): ...\ndef get_party_details(party=None, account=None, party_type='Customer', company=None, posting_date=None, price_list=None, currency=None, doctype=None): ...\ndef _get_party_details(party=None, account=None, party_type='Customer', company=None, posting_date=None, price_list=None, currency=None, doctype=None, ignore_permissions=False): ...\ndef set_address_details(out, party, party_type): ...\ndef set_contact_details(out, party, party_type): ...\ndef set_other_values(out, party, party_type): ...\ndef set_price_list(out, party, party_type, given_price_list): ...\ndef set_account_and_due_date(party, account, party_type, company, posting_date, doctype): ...\ndef get_party_account(company, party, party_type): ...\ndef get_due_date(posting_date, party, party_type, account, company): ...\ndef create_party_account(party, party_type, company): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_party_details", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000969.py"} {"focal_file": "erpnext/selling/doctype/lead/lead.py", "focal_class": null, "focal_method": "make_customer", "tests": "import unittest\n\nclass Test_make_customer(unittest.TestCase):\n def test_make_customer(self):\n from erpnext.selling.doctype.lead.lead import make_customer\n frappe.delete_doc_if_exists('Customer', '_Test Lead')\n customer = make_customer('_T-Lead-00001')\n self.assertEquals(customer.doctype, 'Customer')\n self.assertEquals(customer.lead_name, '_T-Lead-00001')\n customer.company = '_Test Company'\n customer.customer_group = '_Test Customer Group'\n customer.insert()\n", "method_code": "def make_customer(source_name, target_doc=None):\n return _make_customer(source_name, target_doc)", "context": "@frappe.whitelist()\ndef make_customer(source_name, target_doc=None): ...\ndef make_customer(source_name, target_doc=None): ...\ndef _make_customer(source_name, target_doc=None, ignore_permissions=False): ...\ndef make_opportunity(source_name, target_doc=None): ...\ndef get_lead_details(lead): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_customer", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000970.py"} {"focal_file": "erpnext/selling/doctype/quotation/quotation.py", "focal_class": null, "focal_method": "make_sales_order", "tests": "import unittest\n\nclass Test_make_sales_order(unittest.TestCase):\n def test_make_sales_order(self):\n from erpnext.selling.doctype.quotation.quotation import make_sales_order\n quotation = frappe.copy_doc(test_records[0])\n quotation.insert()\n self.assertRaises(frappe.ValidationError, make_sales_order, quotation.name)\n quotation.submit()\n sales_order = make_sales_order(quotation.name)\n self.assertEquals(sales_order.doctype, 'Sales Order')\n self.assertEquals(len(sales_order.get('sales_order_details')), 1)\n self.assertEquals(sales_order.get('sales_order_details')[0].doctype, 'Sales Order Item')\n self.assertEquals(sales_order.get('sales_order_details')[0].prevdoc_docname, quotation.name)\n self.assertEquals(sales_order.customer, '_Test Customer')\n sales_order.delivery_date = '2014-01-01'\n sales_order.naming_series = '_T-Quotation-'\n sales_order.transaction_date = '2013-05-12'\n sales_order.insert()\n", "method_code": "def make_sales_order(source_name, target_doc=None):\n return _make_sales_order(source_name, target_doc)", "context": "@frappe.whitelist()\ndef make_sales_order(source_name, target_doc=None): ...\ndef make_sales_order(source_name, target_doc=None): ...\ndef _make_sales_order(source_name, target_doc=None, ignore_permissions=False): ...\ndef _make_customer(source_name, ignore_permissions=False): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_sales_order", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000971.py"} {"focal_file": "erpnext/selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_material_request", "tests": "import unittest\n\nclass Test_make_material_request(unittest.TestCase):\n def test_make_material_request(self):\n from erpnext.selling.doctype.sales_order.sales_order import make_material_request\n so = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_material_request, so.name)\n sales_order = frappe.get_doc('Sales Order', so.name)\n sales_order.submit()\n mr = make_material_request(so.name)\n self.assertEquals(mr.material_request_type, 'Purchase')\n self.assertEquals(len(mr.get('indent_details')), len(sales_order.get('sales_order_details')))\n", "method_code": "def make_material_request(source_name, target_doc=None):\n\n def postprocess(source, doc):\n doc.material_request_type = 'Purchase'\n doc = get_mapped_doc('Sales Order', source_name, {'Sales Order': {'doctype': 'Material Request', 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Material Request Item', 'field_map': {'parent': 'sales_order_no', 'stock_uom': 'uom'}}}, target_doc, postprocess)\n return doc", "context": "@frappe.whitelist()\ndef make_material_request(source_name, target_doc=None): ...\ndef make_material_request(source_name, target_doc=None): ...\ndef make_delivery_note(source_name, target_doc=None): ...\ndef make_sales_invoice(source_name, target_doc=None): ...\ndef make_maintenance_schedule(source_name, target_doc=None): ...\ndef make_maintenance_visit(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_material_request", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000972.py"} {"focal_file": "erpnext/selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_delivery_note", "tests": "import unittest\n\nclass Test_make_delivery_note(unittest.TestCase):\n def test_make_delivery_note(self):\n from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note\n so = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_delivery_note, so.name)\n sales_order = frappe.get_doc('Sales Order', so.name)\n sales_order.submit()\n dn = make_delivery_note(so.name)\n self.assertEquals(dn.doctype, 'Delivery Note')\n self.assertEquals(len(dn.get('delivery_note_details')), len(sales_order.get('sales_order_details')))\n", "method_code": "def make_delivery_note(source_name, target_doc=None):\n\n def set_missing_values(source, target):\n if source.po_no:\n if target.po_no:\n target_po_no = target.po_no.split(', ')\n target_po_no.append(source.po_no)\n target.po_no = ', '.join(list(set(target_po_no))) if len(target_po_no) > 1 else target_po_no[0]\n else:\n target.po_no = source.po_no\n target.ignore_pricing_rule = 1\n target.run_method('set_missing_values')\n target.run_method('calculate_taxes_and_totals')\n\n def update_item(source, target, source_parent):\n target.base_amount = (flt(source.qty) - flt(source.delivered_qty)) * flt(source.base_rate)\n target.amount = (flt(source.qty) - flt(source.delivered_qty)) * flt(source.rate)\n target.qty = flt(source.qty) - flt(source.delivered_qty)\n target_doc = get_mapped_doc('Sales Order', source_name, {'Sales Order': {'doctype': 'Delivery Note', 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Delivery Note Item', 'field_map': {'rate': 'rate', 'name': 'prevdoc_detail_docname', 'parent': 'against_sales_order'}, 'postprocess': update_item, 'condition': lambda doc: doc.delivered_qty < doc.qty}, 'Sales Taxes and Charges': {'doctype': 'Sales Taxes and Charges', 'add_if_empty': True}, 'Sales Team': {'doctype': 'Sales Team', 'add_if_empty': True}}, target_doc, set_missing_values)\n return target_doc", "context": "@frappe.whitelist()\ndef make_delivery_note(source_name, target_doc=None): ...\ndef make_material_request(source_name, target_doc=None): ...\ndef make_delivery_note(source_name, target_doc=None): ...\ndef make_sales_invoice(source_name, target_doc=None): ...\ndef make_maintenance_schedule(source_name, target_doc=None): ...\ndef make_maintenance_visit(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_delivery_note", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000973.py"} {"focal_file": "erpnext/selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_sales_invoice", "tests": "import unittest\n\nclass Test_make_sales_invoice(unittest.TestCase):\n def test_make_sales_invoice(self):\n from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice\n so = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_sales_invoice, so.name)\n sales_order = frappe.get_doc('Sales Order', so.name)\n sales_order.submit()\n si = make_sales_invoice(so.name)\n self.assertEquals(si.doctype, 'Sales Invoice')\n self.assertEquals(len(si.get('entries')), len(sales_order.get('sales_order_details')))\n self.assertEquals(len(si.get('entries')), 1)\n si.posting_date = '2013-10-10'\n si.insert()\n si.submit()\n si1 = make_sales_invoice(so.name)\n self.assertEquals(len(si1.get('entries')), 0)\n", "method_code": "def make_sales_invoice(source_name, target_doc=None):\n\n def set_missing_values(source, target):\n target.is_pos = 0\n target.ignore_pricing_rule = 1\n target.run_method('set_missing_values')\n target.run_method('calculate_taxes_and_totals')\n\n def update_item(source, target, source_parent):\n target.amount = flt(source.amount) - flt(source.billed_amt)\n target.base_amount = target.amount * flt(source_parent.conversion_rate)\n target.qty = target.amount / flt(source.rate) if source.rate and source.billed_amt else source.qty\n doclist = get_mapped_doc('Sales Order', source_name, {'Sales Order': {'doctype': 'Sales Invoice', 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Sales Invoice Item', 'field_map': {'name': 'so_detail', 'parent': 'sales_order'}, 'postprocess': update_item, 'condition': lambda doc: doc.base_amount == 0 or doc.billed_amt < doc.amount}, 'Sales Taxes and Charges': {'doctype': 'Sales Taxes and Charges', 'add_if_empty': True}, 'Sales Team': {'doctype': 'Sales Team', 'add_if_empty': True}}, target_doc, set_missing_values)\n return doclist", "context": "@frappe.whitelist()\ndef make_sales_invoice(source_name, target_doc=None): ...\ndef make_material_request(source_name, target_doc=None): ...\ndef make_delivery_note(source_name, target_doc=None): ...\ndef make_sales_invoice(source_name, target_doc=None): ...\ndef make_maintenance_schedule(source_name, target_doc=None): ...\ndef make_maintenance_visit(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_sales_invoice", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000974.py"} {"focal_file": "erpnext/stock/get_item_details.py", "focal_class": null, "focal_method": "get_item_details", "tests": "import unittest\n\nclass Test_get_item_details(unittest.TestCase):\n def test_get_item_details(self):\n from erpnext.stock.get_item_details import get_item_details\n to_check = {'item_code': '_Test Item', 'item_name': '_Test Item', 'description': '_Test Item', 'warehouse': '_Test Warehouse - _TC', 'income_account': 'Sales - _TC', 'expense_account': '_Test Account Cost for Goods Sold - _TC', 'cost_center': '_Test Cost Center 2 - _TC', 'qty': 1.0, 'price_list_rate': 100.0, 'base_price_list_rate': 0.0, 'discount_percentage': 0.0, 'rate': 0.0, 'base_rate': 0.0, 'amount': 0.0, 'base_amount': 0.0, 'batch_no': None, 'item_tax_rate': '{}', 'uom': '_Test UOM', 'conversion_factor': 1.0}\n make_test_records('Item Price')\n details = get_item_details({'item_code': '_Test Item', 'company': '_Test Company', 'price_list': '_Test Price List', 'currency': '_Test Currency', 'parenttype': 'Sales Order', 'conversion_rate': 1, 'price_list_currency': '_Test Currency', 'plc_conversion_rate': 1, 'order_type': 'Sales', 'transaction_type': 'selling'})\n for key, value in to_check.iteritems():\n self.assertEquals(value, details.get(key))\n", "method_code": "def get_item_details(args):\n \"\"\"\n\t\targs = {\n\t\t\t\"item_code\": \"\",\n\t\t\t\"warehouse\": None,\n\t\t\t\"customer\": \"\",\n\t\t\t\"conversion_rate\": 1.0,\n\t\t\t\"selling_price_list\": None,\n\t\t\t\"price_list_currency\": None,\n\t\t\t\"plc_conversion_rate\": 1.0,\n\t\t\t\"parenttype\": \"\",\n\t\t\t\"parent\": \"\",\n\t\t\t\"supplier\": None,\n\t\t\t\"transaction_date\": None,\n\t\t\t\"conversion_rate\": 1.0,\n\t\t\t\"buying_price_list\": None,\n\t\t\t\"is_subcontracted\": \"Yes\" / \"No\",\n\t\t\t\"transaction_type\": \"selling\",\n\t\t\t\"ignore_pricing_rule\": 0/1\n\t\t\t\"project_name\": \"\",\n\t\t}\n\t\"\"\"\n args = process_args(args)\n item_doc = frappe.get_doc('Item', args.item_code)\n item = item_doc\n validate_item_details(args, item)\n out = get_basic_details(args, item_doc)\n get_party_item_code(args, item_doc, out)\n if out.get('warehouse'):\n out.update(get_available_qty(args.item_code, out.warehouse))\n out.update(get_projected_qty(item.name, out.warehouse))\n get_price_list_rate(args, item_doc, out)\n if args.transaction_type == 'selling' and cint(args.is_pos):\n out.update(get_pos_settings_item_details(args.company, args))\n for key, value in out.iteritems():\n if args.get(key) is None:\n args[key] = value\n out.update(get_pricing_rule_for_item(args))\n if args.get('parenttype') in ('Sales Invoice', 'Delivery Note'):\n if item_doc.has_serial_no == 'Yes' and (not args.serial_no):\n out.serial_no = get_serial_nos_by_fifo(args, item_doc)\n if args.transaction_date and item.lead_time_days:\n out.schedule_date = out.lead_time_date = add_days(args.transaction_date, item.lead_time_days)\n return out", "context": "@frappe.whitelist()\ndef get_item_details(args): ...\ndef get_item_details(args): ...\ndef process_args(args): ...\ndef get_item_code(barcode=None, serial_no=None): ...\ndef validate_item_details(args, item): ...\ndef get_basic_details(args, item_doc): ...\ndef get_price_list_rate(args, item_doc, out): ...\ndef validate_price_list(args): ...\ndef validate_conversion_rate(args, meta): ...\ndef get_party_item_code(args, item_doc, out): ...\ndef get_pos_settings_item_details(company, args, pos_settings=None): ...\ndef get_pos_settings(company): ...\ndef get_serial_nos_by_fifo(args, item_doc): ...\ndef get_conversion_factor(item_code, uom): ...\ndef get_projected_qty(item_code, warehouse): ...\ndef get_available_qty(item_code, warehouse): ...\ndef apply_price_list(args): ...\ndef apply_price_list_on_item(args): ...\ndef get_price_list_currency(price_list): ...\ndef get_price_list_currency_and_exchange_rate(args): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_get_item_details", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000975.py"} {"focal_file": "erpnext/stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_purchase_order", "tests": "import unittest\n\nclass Test_make_purchase_order(unittest.TestCase):\n def test_make_purchase_order(self):\n from erpnext.stock.doctype.material_request.material_request import make_purchase_order\n mr = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_purchase_order, mr.name)\n mr = frappe.get_doc('Material Request', mr.name)\n mr.submit()\n po = make_purchase_order(mr.name)\n self.assertEquals(po.doctype, 'Purchase Order')\n self.assertEquals(len(po.get('po_details')), len(mr.get('indent_details')))\n", "method_code": "def make_purchase_order(source_name, target_doc=None):\n doclist = get_mapped_doc('Material Request', source_name, {'Material Request': {'doctype': 'Purchase Order', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Purchase']}}, 'Material Request Item': {'doctype': 'Purchase Order Item', 'field_map': [['name', 'prevdoc_detail_docname'], ['parent', 'prevdoc_docname'], ['parenttype', 'prevdoc_doctype'], ['uom', 'stock_uom'], ['uom', 'uom']], 'postprocess': update_item, 'condition': lambda doc: doc.ordered_qty < doc.qty}}, target_doc, set_missing_values)\n return doclist", "context": "@frappe.whitelist()\ndef make_purchase_order(source_name, target_doc=None): ...\ndef update_completed_qty(doc, method): ...\ndef _update_requested_qty(doc, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doc): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doc=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doc=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doc=None): ...\ndef make_stock_entry(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_purchase_order", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000976.py"} {"focal_file": "erpnext/stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_supplier_quotation", "tests": "import unittest\n\nclass Test_make_supplier_quotation(unittest.TestCase):\n def test_make_supplier_quotation(self):\n from erpnext.stock.doctype.material_request.material_request import make_supplier_quotation\n mr = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_supplier_quotation, mr.name)\n mr = frappe.get_doc('Material Request', mr.name)\n mr.submit()\n sq = make_supplier_quotation(mr.name)\n self.assertEquals(sq.doctype, 'Supplier Quotation')\n self.assertEquals(len(sq.get('quotation_items')), len(mr.get('indent_details')))\n", "method_code": "def make_supplier_quotation(source_name, target_doc=None):\n doclist = get_mapped_doc('Material Request', source_name, {'Material Request': {'doctype': 'Supplier Quotation', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Purchase']}}, 'Material Request Item': {'doctype': 'Supplier Quotation Item', 'field_map': {'name': 'prevdoc_detail_docname', 'parent': 'prevdoc_docname', 'parenttype': 'prevdoc_doctype'}}}, target_doc, set_missing_values)\n return doclist", "context": "@frappe.whitelist()\ndef make_supplier_quotation(source_name, target_doc=None): ...\ndef update_completed_qty(doc, method): ...\ndef _update_requested_qty(doc, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doc): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doc=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doc=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doc=None): ...\ndef make_stock_entry(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_supplier_quotation", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000977.py"} {"focal_file": "erpnext/stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_stock_entry", "tests": "import unittest\n\nclass Test_make_stock_entry(unittest.TestCase):\n def test_make_stock_entry(self):\n from erpnext.stock.doctype.material_request.material_request import make_stock_entry\n mr = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_stock_entry, mr.name)\n mr = frappe.get_doc('Material Request', mr.name)\n mr.material_request_type = 'Transfer'\n mr.submit()\n se = make_stock_entry(mr.name)\n self.assertEquals(se.doctype, 'Stock Entry')\n self.assertEquals(len(se.get('mtn_details')), len(mr.get('indent_details')))\n\n def test_incorrect_mapping_of_stock_entry(self):\n mr = frappe.copy_doc(test_records[0])\n mr.material_request_type = 'Transfer'\n mr.insert()\n mr.submit()\n from erpnext.stock.doctype.material_request.material_request import make_stock_entry\n se_doc = make_stock_entry(mr.name)\n se_doc.update({'posting_date': '2013-03-01', 'posting_time': '00:00', 'fiscal_year': '_Test Fiscal Year 2013'})\n se_doc.get('mtn_details')[0].update({'qty': 60.0, 'transfer_qty': 60.0, 's_warehouse': '_Test Warehouse - _TC', 't_warehouse': '_Test Warehouse 1 - _TC', 'incoming_rate': 1.0})\n se_doc.get('mtn_details')[1].update({'qty': 3.0, 'transfer_qty': 3.0, 's_warehouse': '_Test Warehouse 1 - _TC', 'incoming_rate': 1.0})\n se = frappe.copy_doc(se_doc)\n self.assertRaises(frappe.MappingMismatchError, se.insert)\n", "method_code": "def make_stock_entry(source_name, target_doc=None):\n\n def update_item(obj, target, source_parent):\n target.conversion_factor = 1\n target.qty = flt(obj.qty) - flt(obj.ordered_qty)\n target.transfer_qty = flt(obj.qty) - flt(obj.ordered_qty)\n\n def set_missing_values(source, target):\n target.purpose = 'Material Transfer'\n target.run_method('get_stock_and_rate')\n doclist = get_mapped_doc('Material Request', source_name, {'Material Request': {'doctype': 'Stock Entry', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Transfer']}}, 'Material Request Item': {'doctype': 'Stock Entry Detail', 'field_map': {'name': 'material_request_item', 'parent': 'material_request', 'uom': 'stock_uom', 'warehouse': 't_warehouse'}, 'postprocess': update_item, 'condition': lambda doc: doc.ordered_qty < doc.qty}}, target_doc, set_missing_values)\n return doclist", "context": "@frappe.whitelist()\ndef make_stock_entry(source_name, target_doc=None): ...\ndef update_completed_qty(doc, method): ...\ndef _update_requested_qty(doc, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doc): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doc=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doc=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doc=None): ...\ndef make_stock_entry(source_name, target_doc=None): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_stock_entry", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000978.py"} {"focal_file": "erpnext/stock/doctype/purchase_receipt/purchase_receipt.py", "focal_class": null, "focal_method": "make_purchase_invoice", "tests": "import unittest\n\nclass Test_make_purchase_invoice(unittest.TestCase):\n def test_make_purchase_invoice(self):\n self._clear_stock_account_balance()\n set_perpetual_inventory(0)\n from erpnext.stock.doctype.purchase_receipt.purchase_receipt import make_purchase_invoice\n pr = frappe.copy_doc(test_records[0]).insert()\n self.assertRaises(frappe.ValidationError, make_purchase_invoice, pr.name)\n pr = frappe.get_doc('Purchase Receipt', pr.name)\n pr.submit()\n pi = make_purchase_invoice(pr.name)\n self.assertEquals(pi.doctype, 'Purchase Invoice')\n self.assertEquals(len(pi.get('entries')), len(pr.get('purchase_receipt_details')))\n pi.get('entries')[0].rate = 200\n self.assertRaises(frappe.ValidationError, frappe.get_doc(pi).submit)\n", "method_code": "def make_purchase_invoice(source_name, target_doc=None):\n from frappe.model.mapper import get_mapped_doc\n invoiced_qty_map = get_invoiced_qty_map(source_name)\n\n def set_missing_values(source, target):\n if len(target.get('entries')) == 0:\n frappe.throw(_('All items have already been invoiced'))\n doc = frappe.get_doc(target)\n doc.ignore_pricing_rule = 1\n doc.run_method('set_missing_values')\n doc.run_method('calculate_taxes_and_totals')\n\n def update_item(source_doc, target_doc, source_parent):\n target_doc.qty = source_doc.qty - invoiced_qty_map.get(source_doc.name, 0)\n doclist = get_mapped_doc('Purchase Receipt', source_name, {'Purchase Receipt': {'doctype': 'Purchase Invoice', 'validation': {'docstatus': ['=', 1]}}, 'Purchase Receipt Item': {'doctype': 'Purchase Invoice Item', 'field_map': {'name': 'pr_detail', 'parent': 'purchase_receipt', 'prevdoc_detail_docname': 'po_detail', 'prevdoc_docname': 'purchase_order'}, 'postprocess': update_item, 'filter': lambda d: d.qty - invoiced_qty_map.get(d.name, 0) <= 0}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doc, set_missing_values)\n return doclist", "context": "@frappe.whitelist()\ndef make_purchase_invoice(source_name, target_doc=None): ...\ndef make_purchase_invoice(source_name, target_doc=None): ...\ndef get_invoiced_qty_map(purchase_receipt): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_make_purchase_invoice", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000979.py"} {"focal_file": "erpnext/stock/doctype/stock_entry/stock_entry.py", "focal_class": null, "focal_method": "get_serial_nos", "tests": "import unittest\n\nclass Test_get_serial_nos(unittest.TestCase):\n def test_serial_by_series(self):\n self._clear_stock_account_balance()\n se = make_serialized_item()\n serial_nos = get_serial_nos(se.get('mtn_details')[0].serial_no)\n self.assertTrue(frappe.db.exists('Serial No', serial_nos[0]))\n self.assertTrue(frappe.db.exists('Serial No', serial_nos[1]))\n return (se, serial_nos)\n\n def test_serial_move(self):\n self._clear_stock_account_balance()\n se = make_serialized_item()\n serial_no = get_serial_nos(se.get('mtn_details')[0].serial_no)[0]\n se = frappe.copy_doc(test_records[0])\n se.purpose = 'Material Transfer'\n se.get('mtn_details')[0].item_code = '_Test Serialized Item With Series'\n se.get('mtn_details')[0].qty = 1\n se.get('mtn_details')[0].transfer_qty = 1\n se.get('mtn_details')[0].serial_no = serial_no\n se.get('mtn_details')[0].s_warehouse = '_Test Warehouse - _TC'\n se.get('mtn_details')[0].t_warehouse = '_Test Warehouse 1 - _TC'\n se.insert()\n se.submit()\n self.assertTrue(frappe.db.get_value('Serial No', serial_no, 'warehouse'), '_Test Warehouse 1 - _TC')\n se.cancel()\n self.assertTrue(frappe.db.get_value('Serial No', serial_no, 'warehouse'), '_Test Warehouse - _TC')\n\n def test_serial_warehouse_error(self):\n self._clear_stock_account_balance()\n make_serialized_item(target_warehouse='_Test Warehouse 1 - _TC')\n t = make_serialized_item()\n serial_nos = get_serial_nos(t.get('mtn_details')[0].serial_no)\n se = frappe.copy_doc(test_records[0])\n se.purpose = 'Material Transfer'\n se.get('mtn_details')[0].item_code = '_Test Serialized Item With Series'\n se.get('mtn_details')[0].qty = 1\n se.get('mtn_details')[0].transfer_qty = 1\n se.get('mtn_details')[0].serial_no = serial_nos[0]\n se.get('mtn_details')[0].s_warehouse = '_Test Warehouse 1 - _TC'\n se.get('mtn_details')[0].t_warehouse = '_Test Warehouse - _TC'\n se.insert()\n self.assertRaises(SerialNoWarehouseError, se.submit)\n\n def test_serial_cancel(self):\n self._clear_stock_account_balance()\n se, serial_nos = self.test_serial_by_series()\n se.cancel()\n serial_no = get_serial_nos(se.get('mtn_details')[0].serial_no)[0]\n self.assertFalse(frappe.db.get_value('Serial No', serial_no, 'warehouse'))\n", "method_code": " def get_serial_nos(self, item_name):\n for d in self.get('mtn_details'):\n if d.source_batch and d.item_code == item_name:\n if d.s_warehouse and frappe.db.get_value('Serial No', d.source_batch, 'name'):\n d.custom_serial_no = frappe.db.get_value('Serial No', d.source_batch, 'name')\n d.grade = frappe.db.get_value('Serial No', d.custom_serial_no, 'grade')\n return 'Done'\n ", "context": "class StockEntry(StockController):\n def get_serial_nos(self, item_name): ...\n def onload(self): ...\n def validate(self): ...\n def update_stock_serial_name(self): ...\n def on_submit(self): ...\n def on_cancel(self): ...\n def validate_fiscal_year(self): ...\n def validate_purpose(self): ...\n def set_transfer_qty(self): ...\n def validate_item(self): ...\n def validate_warehouse(self, pro_obj): ...\n def validate_production_order(self): ...\n def check_duplicate_entry_for_production_order(self): ...\n def validate_valuation_rate(self): ...\n def set_total_amount(self): ...\n def get_stock_and_rate(self, force=False): ...\n def get_incoming_rate(self, args): ...\n def get_incoming_rate_for_sales_return(self, args): ...\n def validate_incoming_rate(self): ...\n def validate_bom(self): ...\n def validate_finished_goods(self): ...\n def validate_return_reference_doc(self): ...\n def get_already_returned_item_qty(self, ref_fieldname): ...\n def update_stock_ledger(self): ...\n def update_production_order(self): ...\n def update_planned_qty(self, pro_doc): ...\n def get_source_batch(self, item_code): ...\n def duplicate_entry(self, d): ...\n def get_item_details(self, args): ...\n def get_uom_details(self, args): ...\n def get_warehouse_details(self, args): ...\n def get_items(self): ...\n def get_bom_raw_materials(self, qty): ...\n def get_pending_raw_materials(self, pro_obj): ...\n def get_issued_qty(self): ...\n def update_serial_no_warehouse(self): ...\n def add_to_stock_entry_detail(self, item_dict, bom_no=None): ...\n def validate_with_material_request(self): ...\n\n fname = 'mtn_details'\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_serial_by_series", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000980.py"} {"focal_file": "erpnext/support/doctype/newsletter/newsletter.py", "focal_class": null, "focal_method": "get_recipients", "tests": "import unittest\n\nclass Test_get_recipients(unittest.TestCase):\n def test_get_recipients_lead(self):\n w = frappe.get_doc(test_records[0])\n w.insert()\n self.assertTrue('test_lead@example.com' in w.get_recipients())\n frappe.db.sql('delete from `tabBulk Email`')\n w.send_emails()\n self.assertTrue(frappe.db.get_value('Bulk Email', {'recipient': 'test_lead@example.com'}))\n\n def test_get_recipients_lead_by_status(self):\n w = frappe.get_doc(test_records[0])\n w.lead_status = 'Converted'\n w.insert()\n self.assertTrue('test_lead3@example.com' in w.get_recipients())\n\n def test_get_recipients_contact_customer(self):\n w = frappe.get_doc(test_records[1])\n w.insert()\n self.assertTrue('test_contact_customer@example.com' in w.get_recipients())\n\n def test_get_recipients_contact_supplier(self):\n w = frappe.get_doc(test_records[1])\n w.contact_type = 'Supplier'\n w.insert()\n self.assertTrue('test_contact_supplier@example.com' in w.get_recipients())\n\n def test_get_recipients_custom(self):\n w = frappe.get_doc(test_records[2])\n w.insert()\n self.assertTrue('test_custom2@example.com' in w.get_recipients())\n self.assertTrue(frappe.db.get('Lead', {'email_id': 'test_custom2@example.com'}))\n", "method_code": " def get_recipients(self):\n self.email_field = None\n if self.send_to_type == 'Contact':\n self.send_to_doctype = 'Contact'\n if self.contact_type == 'Customer':\n return frappe.db.sql_list(\"select email_id from tabContact\\n\\t\\t\\t\\t\\twhere ifnull(email_id, '') != '' and ifnull(customer, '') != ''\")\n elif self.contact_type == 'Supplier':\n return frappe.db.sql_list(\"select email_id from tabContact\\n\\t\\t\\t\\t\\twhere ifnull(email_id, '') != '' and ifnull(supplier, '') != ''\")\n elif self.send_to_type == 'Lead':\n self.send_to_doctype = 'Lead'\n conditions = []\n if self.lead_source and self.lead_source != 'All':\n conditions.append(\" and source='%s'\" % self.lead_source.replace(\"'\", \"'\"))\n if self.lead_status and self.lead_status != 'All':\n conditions.append(\" and status='%s'\" % self.lead_status.replace(\"'\", \"'\"))\n if conditions:\n conditions = ''.join(conditions)\n return frappe.db.sql_list(\"select email_id from tabLead\\n\\t\\t\\t\\twhere ifnull(email_id, '') != '' %s\" % (conditions or ''))\n elif self.send_to_type == 'Employee':\n self.send_to_doctype = 'Employee'\n self.email_field = 'company_email'\n return frappe.db.sql_list(\"select\\n\\t\\t\\t\\tif(ifnull(company_email, '')!='', company_email, personal_email) as email_id\\n\\t\\t\\t\\tfrom `tabEmployee` where status='Active'\")\n elif self.email_list:\n email_list = [cstr(email).strip() for email in self.email_list.split(',')]\n for email in email_list:\n create_lead(email)\n self.send_to_doctype = 'Lead'\n return email_list\n ", "context": "class Newsletter(Document):\n def get_recipients(self): ...\n def onload(self): ...\n def test_send(self, doctype='Lead'): ...\n def send_emails(self): ...\n def send_bulk(self): ...\n def validate_send(self): ...\n", "repository": "suyashphadtare/vestasi-update-erp", "test_name": "test_get_recipients_lead", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000981.py"} {"focal_file": "src/s3ts/treestore.py", "focal_class": null, "focal_method": "flushStore", "tests": "import unittest\n\nclass Test_flushStore(unittest.TestCase):\n def test_fs_treestore(self):\n fileStore = LocalFileStore(makeEmptyDir(os.path.join(self.workdir, 'fs')))\n localCache = LocalFileStore(makeEmptyDir(os.path.join(self.workdir, 'cache')))\n treestore = TreeStore.create(fileStore, localCache, TreeStoreConfig(100, True))\n creationTime = datetimeFromIso('2015-01-01T00:00:00.0')\n treestore.upload('v1.0', '', creationTime, self.srcTree, CaptureUploadProgress())\n pkg = treestore.findPackage('v1.0')\n self.assertEquals(treestore.listPackages(), ['v1.0'])\n treestore.verify(pkg)\n treestore.prime(self.srcTree2, CaptureUploadProgress())\n corruptedFiles = treestore.validateLocalCache()\n self.assertEquals(len(corruptedFiles), 0)\n cb = CaptureDownloadProgress()\n treestore.download(pkg, cb)\n self.assertEquals(sorted(cb.recorded), [30, 45, 47, 100, 100])\n treestore.verifyLocal(pkg)\n destTree = os.path.join(self.workdir, 'dest-1')\n treestore.install(pkg, destTree, CaptureInstallProgress())\n self.assertEquals(subprocess.call('diff -r -x {0} {1} {2}'.format(S3TS_PROPERTIES, self.srcTree, destTree), shell=True), 0)\n treestore.rename('v1.0', 'v1.0x')\n pkg = treestore.findPackage('v1.0x')\n treestore.download(pkg, CaptureDownloadProgress())\n destTree = os.path.join(self.workdir, 'dest-2')\n treestore.install(pkg, destTree, CaptureInstallProgress())\n self.assertEquals(subprocess.call('diff -r -x {0} {1} {2}'.format(S3TS_PROPERTIES, self.srcTree, destTree), shell=True), 0)\n treestore.upload('extra', '', creationTime, self.srcTree2, CaptureUploadProgress())\n removed = treestore.flushStore()\n self.assertEquals(len(removed), 0)\n treestore.remove('v1.0x')\n removed = treestore.flushStore()\n self.assertTrue(len(removed) > 0)\n treestore.upload('v1.0', '', creationTime, self.srcTree, CaptureUploadProgress())\n removed = treestore.flushLocalCache(['extra'])\n self.assertTrue(len(removed) > 0)\n removed = treestore.flushLocalCache(['v1.0'])\n self.assertTrue(len(removed) > 0)\n with self.assertRaises(RuntimeError):\n treestore.flushLocalCache([])\n", "method_code": " def flushStore(self):\n \"\"\"\n Remote any \"dangling\" chunks from the store that are not referenced by packages.\n This will happen when packages are deleted Returns the chunks removed.\n \"\"\"\n packageNames = self.pkgStore.list(TREES_PATH)\n packages = [self.findPackage(packageName) for packageName in packageNames]\n return self.__flushStore(self.pkgStore, packages)\n ", "context": "class TreeStore(object):\n def flushStore(self): ...\n def create(cls, pkgStore, localCache, config): ...\n def open(cls, pkgStore, localCache): ...\n def forHttpOnly(cls, localCache): ...\n def __init__(self, pkgStore, localCache, config): ...\n def setDryRun(self, dryRun): ...\n def setOutVerbose(self, outVerbose): ...\n def upload(self, treeName, description, creationTime, localPath, progressCB): ...\n def uploadMetaPackage(self, meta): ...\n def uploadMany(self, treeName, description, creationTime, commonLocalPath, variantsLocalPath, progressCB): ...\n def createMerged(self, treeName, creationTime, packageMap): ...\n def find(self, treeName, metadata): ...\n def findPackage(self, treeName): ...\n def findMetaPackage(self, metaTreeName): ...\n def listPackages(self): ...\n def listMetaPackages(self): ...\n def remove(self, treeName): ...\n def rename(self, fromTreeName, toTreeName): ...\n def verify(self, pkg): ...\n def verifyLocal(self, pkg): ...\n def download(self, pkg, progressCB): ...\n def downloadHttp(self, pkg, progressCB): ...\n def sync(self, pkg, localPath, progressCB): ...\n def install(self, pkg, localPath, progressCB): ...\n def __install(self, pkg, localPath, progressCB): ...\n def compareInstall(self, pkg, localPath): ...\n def addUrls(self, pkg, expiresInSecs): ...\n def prime(self, localPath, progressCB): ...\n def validateLocalCache(self): ...\n def validateStore(self): ...\n def flushLocalCache(self, packageNames): ...\n def __validateStore(self, fileStore): ...\n def __verifyStore(self, fileStore, pkg): ...\n def __flushStore(self, fileStore, packages): ...\n def __storeFiles(self, store, localPath, progressCB): ...\n def __storeFile(self, store, root, rpath, progressCB): ...\n def __storeChunk(self, store, sha1, buf, progressCB): ...\n def __treeNamePath(self, store, treeName): ...\n def __metaTreeNamePath(self, store, metaTreeName): ...\n def __chunkPath(self, store, sha1, encoding): ...\n def __compress(self, buf): ...\n def __decompress(self, buf, encoding): ...\n def __checkSha1(self, buf, sha1, cpath): ...\n\n self.pkgStore = pkgStore\n self.localCache = localCache\n self.config = config\n self.dryRun = False\n self.outVerbose = lambda *args: None\n", "repository": "helix-collective/s3ts", "test_name": "test_fs_treestore", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000982.py"} {"focal_file": "src/s3ts/treestore.py", "focal_class": null, "focal_method": "sync", "tests": "import unittest\n\nclass Test_sync(unittest.TestCase):\n def test_sync(self):\n fileStore = LocalFileStore(makeEmptyDir(os.path.join(self.workdir, 'fs')))\n localCache = LocalFileStore(makeEmptyDir(os.path.join(self.workdir, 'cache')))\n treestore = TreeStore.create(fileStore, localCache, TreeStoreConfig(10, True))\n creationTime = datetimeFromIso('2015-01-01T00:00:00.0')\n treestore.upload('v1.0', '', creationTime, self.srcTree, CaptureUploadProgress())\n treestore.upload('v1.3', '', creationTime, self.srcTree3, CaptureUploadProgress())\n treestore.upload('v1.4', '', creationTime, self.srcTree4, CaptureUploadProgress())\n testdir = makeEmptyDir(os.path.join(self.workdir, 'test'))\n\n def assertExists(path):\n self.assertTrue(os.path.exists(os.path.join(testdir, path)))\n\n def assertContains(path, text):\n self.assertEquals(open(os.path.join(testdir, path)).read(), text)\n\n def assertDoesntExist(path):\n self.assertFalse(os.path.exists(os.path.join(testdir, path)))\n\n def assertInstalled(pkg, testdir):\n result = treestore.compareInstall(pkg, testdir)\n self.assertEquals(result.missing, set())\n self.assertEquals(result.extra, set())\n self.assertEquals(result.diffs, set())\n pkg = treestore.findPackage('v1.0')\n treestore.download(pkg, CaptureDownloadProgress())\n treestore.sync(pkg, testdir, CaptureInstallProgress())\n assertContains('code/file1.py', self.FILE1)\n assertContains('code/file2.py', self.FILE2)\n assertContains('assets/car-01.db', self.CAR01)\n assertExists(S3TS_PACKAGEFILE)\n assertInstalled(pkg, testdir)\n pkg = treestore.findPackage('v1.0')\n treestore.download(pkg, CaptureDownloadProgress())\n treestore.sync(pkg, testdir, CaptureInstallProgress())\n assertContains('code/file1.py', self.FILE1)\n assertContains('code/file2.py', self.FILE2)\n assertContains('assets/car-01.db', self.CAR01)\n assertExists(S3TS_PACKAGEFILE)\n assertInstalled(pkg, testdir)\n pkg = treestore.findPackage('v1.3')\n treestore.download(pkg, CaptureDownloadProgress())\n treestore.sync(pkg, testdir, CaptureInstallProgress())\n assertContains('code/file1.py', self.FILE1)\n assertContains('code/file2.py', self.FILE2_A)\n assertDoesntExist('assets/car-01.db')\n assertContains('code/file4.py', self.FILE4)\n assertContains('text/text', self.FILE5)\n assertExists(S3TS_PACKAGEFILE)\n assertInstalled(pkg, testdir)\n pkg = treestore.findPackage('v1.0')\n treestore.download(pkg, CaptureDownloadProgress())\n treestore.sync(pkg, testdir, CaptureInstallProgress())\n assertContains('code/file1.py', self.FILE1)\n assertContains('code/file2.py', self.FILE2)\n assertContains('assets/car-01.db', self.CAR01)\n assertDoesntExist('code/file4.py')\n assertExists(S3TS_PACKAGEFILE)\n assertInstalled(pkg, testdir)\n os.unlink(os.path.join(testdir, S3TS_PACKAGEFILE))\n pkg = treestore.findPackage('v1.3')\n treestore.download(pkg, CaptureDownloadProgress())\n treestore.sync(pkg, testdir, CaptureInstallProgress())\n assertContains('code/file1.py', self.FILE1)\n assertContains('code/file2.py', self.FILE2_A)\n assertDoesntExist('assets/car-01.db')\n assertContains('code/file4.py', self.FILE4)\n assertExists(S3TS_PACKAGEFILE)\n assertInstalled(pkg, testdir)\n with open(os.path.join(testdir, 'debug.log'), 'w') as f:\n f.write('something')\n pkg = treestore.findPackage('v1.3')\n treestore.sync(pkg, testdir, CaptureInstallProgress())\n assertInstalled(pkg, testdir)\n pkg = treestore.findPackage('v1.4')\n treestore.download(pkg, CaptureDownloadProgress())\n treestore.sync(pkg, testdir, CaptureInstallProgress())\n assertContains('text', self.FILE5)\n assertInstalled(pkg, testdir)\n", "method_code": " def sync(self, pkg, localPath, progressCB):\n \"\"\"synchronise the content of localpath with the given package,\n reusing existing files where possible.\n \n progressCB will be called with parameters (nBytes) as the installation progresses,\n \"\"\"\n try:\n existingPkg = package.readInstallPackage(localPath)\n except IOError:\n existingPkg = None\n if not existingPkg:\n syncPkg, pathsToRemove = (pkg, [])\n if os.path.exists(localPath):\n shutil.rmtree(localPath)\n os.makedirs(localPath)\n else:\n syncPkg, _ = package.packageDiff(existingPkg, pkg)\n localPaths = set(utils.allFilePaths(localPath))\n targetPaths = set([os.path.normpath(f.path) for f in pkg.files])\n pathsToRemove = localPaths.difference(targetPaths)\n pathsToRemove.discard(package.S3TS_PACKAGEFILE)\n os.unlink(os.path.join(localPath, package.S3TS_PACKAGEFILE))\n installTime = datetime.datetime.now()\n for path in pathsToRemove:\n path = os.path.join(localPath, path)\n self.outVerbose('removing {}', path)\n os.unlink(path)\n utils.removeEmptyDirectories(localPath, removeRoot=False)\n self.__install(syncPkg, localPath, progressCB)\n package.writeInstallPackage(localPath, pkg)\n writeInstallProperties(localPath, InstallProperties(pkg.name, installTime))\n ", "context": "class TreeStore(object):\n def sync(self, pkg, localPath, progressCB): ...\n def create(cls, pkgStore, localCache, config): ...\n def open(cls, pkgStore, localCache): ...\n def forHttpOnly(cls, localCache): ...\n def __init__(self, pkgStore, localCache, config): ...\n def setDryRun(self, dryRun): ...\n def setOutVerbose(self, outVerbose): ...\n def upload(self, treeName, description, creationTime, localPath, progressCB): ...\n def uploadMetaPackage(self, meta): ...\n def uploadMany(self, treeName, description, creationTime, commonLocalPath, variantsLocalPath, progressCB): ...\n def createMerged(self, treeName, creationTime, packageMap): ...\n def find(self, treeName, metadata): ...\n def findPackage(self, treeName): ...\n def findMetaPackage(self, metaTreeName): ...\n def listPackages(self): ...\n def listMetaPackages(self): ...\n def remove(self, treeName): ...\n def rename(self, fromTreeName, toTreeName): ...\n def verify(self, pkg): ...\n def verifyLocal(self, pkg): ...\n def download(self, pkg, progressCB): ...\n def downloadHttp(self, pkg, progressCB): ...\n def install(self, pkg, localPath, progressCB): ...\n def __install(self, pkg, localPath, progressCB): ...\n def compareInstall(self, pkg, localPath): ...\n def addUrls(self, pkg, expiresInSecs): ...\n def prime(self, localPath, progressCB): ...\n def validateLocalCache(self): ...\n def validateStore(self): ...\n def flushLocalCache(self, packageNames): ...\n def flushStore(self): ...\n def __validateStore(self, fileStore): ...\n def __verifyStore(self, fileStore, pkg): ...\n def __flushStore(self, fileStore, packages): ...\n def __storeFiles(self, store, localPath, progressCB): ...\n def __storeFile(self, store, root, rpath, progressCB): ...\n def __storeChunk(self, store, sha1, buf, progressCB): ...\n def __treeNamePath(self, store, treeName): ...\n def __metaTreeNamePath(self, store, metaTreeName): ...\n def __chunkPath(self, store, sha1, encoding): ...\n def __compress(self, buf): ...\n def __decompress(self, buf, encoding): ...\n def __checkSha1(self, buf, sha1, cpath): ...\n\n self.pkgStore = pkgStore\n self.localCache = localCache\n self.config = config\n self.dryRun = False\n self.outVerbose = lambda *args: None\n", "repository": "helix-collective/s3ts", "test_name": "test_sync", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000983.py"} {"focal_file": "src/s3ts/treestore.py", "focal_class": null, "focal_method": "verify", "tests": "import unittest\n\nclass Test_verify(unittest.TestCase):\n def test_s3_treestore(self):\n s3c = boto.connect_s3()\n bucket = s3c.get_bucket(os.environ['S3TS_BUCKET'])\n with EmptyS3Bucket(bucket):\n fileStore = S3FileStore(bucket)\n localCache = LocalFileStore(makeEmptyDir(os.path.join(self.workdir, 'cache')))\n treestore = TreeStore.create(fileStore, localCache, TreeStoreConfig(100, True))\n creationTime = datetimeFromIso('2015-01-01T00:00:00.0')\n treestore.upload('v1.0', '', creationTime, self.srcTree, CaptureUploadProgress())\n pkg = treestore.findPackage('v1.0')\n self.assertEquals(treestore.listPackages(), ['v1.0'])\n treestore.verify(pkg)\n cb = CaptureDownloadProgress()\n treestore.download(pkg, cb)\n self.assertEquals(sorted(cb.recorded), [30, 45, 47, 100, 100])\n treestore.verifyLocal(pkg)\n destTree = os.path.join(self.workdir, 'dest-1')\n treestore.install(pkg, destTree, CaptureInstallProgress())\n self.assertEquals(subprocess.call('diff -r -x {0} {1} {2}'.format(S3TS_PROPERTIES, self.srcTree, destTree), shell=True), 0)\n self.assertEquals(readInstallProperties(destTree).treeName, 'v1.0')\n result = treestore.compareInstall(pkg, destTree)\n self.assertEquals(len(result.missing), 0)\n self.assertEquals(len(result.extra), 0)\n self.assertEquals(len(result.diffs), 0)\n with open(os.path.join(destTree, 'code/file1.py'), 'w') as f:\n f.write('x')\n with open(os.path.join(destTree, 'code/file3.py'), 'w') as f:\n f.write('y')\n os.unlink(os.path.join(destTree, 'assets/car-01.db'))\n result = treestore.compareInstall(pkg, destTree)\n self.assertEquals(result.missing, set(['assets/car-01.db']))\n self.assertEquals(result.extra, set(['code/file3.py']))\n self.assertEquals(result.diffs, set(['code/file1.py']))\n shutil.rmtree(destTree)\n treestore.install(pkg, destTree, CaptureInstallProgress())\n result = treestore.compareInstall(pkg, destTree)\n self.assertEquals(len(result.missing), 0)\n self.assertEquals(len(result.extra), 0)\n self.assertEquals(len(result.diffs), 0)\n pkg = treestore.findPackage('v1.0')\n treestore.addUrls(pkg, 3600)\n self.assertEquals(len(result.missing), 0)\n self.assertEquals(len(result.extra), 0)\n self.assertEquals(len(result.diffs), 0)\n localCache = LocalFileStore(makeEmptyDir(os.path.join(self.workdir, 'cache')))\n treestore2 = TreeStore.forHttpOnly(localCache)\n cb = CaptureDownloadProgress()\n treestore2.downloadHttp(pkg, cb)\n self.assertEquals(sorted(cb.recorded), [30, 45, 47, 100, 100])\n destTree2 = os.path.join(self.workdir, 'dest-2')\n treestore2.install(pkg, destTree2, CaptureInstallProgress())\n self.assertEquals(subprocess.call('diff -r -x {0} {1} {2}'.format(S3TS_PROPERTIES, self.srcTree, destTree2), shell=True), 0)\n treestore.rename('v1.0', 'v1.0x')\n pkg = treestore.findPackage('v1.0x')\n treestore.download(pkg, CaptureDownloadProgress())\n destTree = os.path.join(self.workdir, 'dest-3')\n treestore.install(pkg, destTree, CaptureInstallProgress())\n self.assertEquals(subprocess.call('diff -r -x {0} {1} {2}'.format(S3TS_PROPERTIES, self.srcTree, destTree), shell=True), 0)\n treestore.remove('v1.0x')\n", "method_code": " def verify(self, pkg):\n \"\"\"confirms that all data for the given package is present in the store\"\"\"\n self.__verifyStore(self.pkgStore, pkg)\n ", "context": "class TreeStore(object):\n def verify(self, pkg): ...\n def create(cls, pkgStore, localCache, config): ...\n def open(cls, pkgStore, localCache): ...\n def forHttpOnly(cls, localCache): ...\n def __init__(self, pkgStore, localCache, config): ...\n def setDryRun(self, dryRun): ...\n def setOutVerbose(self, outVerbose): ...\n def upload(self, treeName, description, creationTime, localPath, progressCB): ...\n def uploadMetaPackage(self, meta): ...\n def uploadMany(self, treeName, description, creationTime, commonLocalPath, variantsLocalPath, progressCB): ...\n def createMerged(self, treeName, creationTime, packageMap): ...\n def find(self, treeName, metadata): ...\n def findPackage(self, treeName): ...\n def findMetaPackage(self, metaTreeName): ...\n def listPackages(self): ...\n def listMetaPackages(self): ...\n def remove(self, treeName): ...\n def rename(self, fromTreeName, toTreeName): ...\n def verifyLocal(self, pkg): ...\n def download(self, pkg, progressCB): ...\n def downloadHttp(self, pkg, progressCB): ...\n def sync(self, pkg, localPath, progressCB): ...\n def install(self, pkg, localPath, progressCB): ...\n def __install(self, pkg, localPath, progressCB): ...\n def compareInstall(self, pkg, localPath): ...\n def addUrls(self, pkg, expiresInSecs): ...\n def prime(self, localPath, progressCB): ...\n def validateLocalCache(self): ...\n def validateStore(self): ...\n def flushLocalCache(self, packageNames): ...\n def flushStore(self): ...\n def __validateStore(self, fileStore): ...\n def __verifyStore(self, fileStore, pkg): ...\n def __flushStore(self, fileStore, packages): ...\n def __storeFiles(self, store, localPath, progressCB): ...\n def __storeFile(self, store, root, rpath, progressCB): ...\n def __storeChunk(self, store, sha1, buf, progressCB): ...\n def __treeNamePath(self, store, treeName): ...\n def __metaTreeNamePath(self, store, metaTreeName): ...\n def __chunkPath(self, store, sha1, encoding): ...\n def __compress(self, buf): ...\n def __decompress(self, buf, encoding): ...\n def __checkSha1(self, buf, sha1, cpath): ...\n\n self.pkgStore = pkgStore\n self.localCache = localCache\n self.config = config\n self.dryRun = False\n self.outVerbose = lambda *args: None\n", "repository": "helix-collective/s3ts", "test_name": "test_s3_treestore", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000984.py"} {"focal_file": "src/s3ts/treestore.py", "focal_class": null, "focal_method": "findPackage", "tests": "import unittest\n\nclass Test_findPackage(unittest.TestCase):\n def test_s3_merged_package(self):\n s3c = boto.connect_s3()\n bucket = s3c.get_bucket(os.environ['S3TS_BUCKET'])\n with EmptyS3Bucket(bucket):\n localCache = LocalFileStore(makeEmptyDir(os.path.join(self.workdir, 'cache')))\n treestore = TreeStore.create(S3FileStore(bucket), localCache, TreeStoreConfig(100, True))\n creationTime = datetimeFromIso('2015-01-01T00:00:00.0')\n treestore.upload('src1', '', creationTime, self.srcTree, CaptureUploadProgress())\n treestore.upload('src2', '', creationTime, self.srcTree2, CaptureUploadProgress())\n treestore.upload('src3', '', creationTime, self.srcTree3, CaptureUploadProgress())\n treestore.createMerged('merged', creationTime, {'.': 'src1', 'subdir-a': 'src2', 'subdir-b': 'src3'})\n pkg = treestore.findPackage('merged')\n treestore.download(pkg, CaptureDownloadProgress())\n destTree = os.path.join(self.workdir, 'merged')\n treestore.install(pkg, destTree, CaptureInstallProgress())\n\n def assertSameContent(path1, path2):\n with open(path1) as f1:\n with open(path2) as f2:\n self.assertEquals(f1.read(), f2.read())\n assertSameContent(os.path.join(destTree, 'code/file1.py'), os.path.join(self.srcTree, 'code/file1.py'))\n assertSameContent(os.path.join(destTree, 'subdir-a/code/file4.py'), os.path.join(self.srcTree2, 'code/file4.py'))\n assertSameContent(os.path.join(destTree, 'subdir-b/text/text'), os.path.join(self.srcTree3, 'text/text'))\n", "method_code": " def findPackage(self, treeName):\n \"\"\"Return the package definition for the given name\"\"\"\n return self.pkgStore.getFromJson(self.__treeNamePath(self.pkgStore, treeName), package.PackageJS())\n ", "context": "class TreeStore(object):\n def findPackage(self, treeName): ...\n def create(cls, pkgStore, localCache, config): ...\n def open(cls, pkgStore, localCache): ...\n def forHttpOnly(cls, localCache): ...\n def __init__(self, pkgStore, localCache, config): ...\n def setDryRun(self, dryRun): ...\n def setOutVerbose(self, outVerbose): ...\n def upload(self, treeName, description, creationTime, localPath, progressCB): ...\n def uploadMetaPackage(self, meta): ...\n def uploadMany(self, treeName, description, creationTime, commonLocalPath, variantsLocalPath, progressCB): ...\n def createMerged(self, treeName, creationTime, packageMap): ...\n def find(self, treeName, metadata): ...\n def findMetaPackage(self, metaTreeName): ...\n def listPackages(self): ...\n def listMetaPackages(self): ...\n def remove(self, treeName): ...\n def rename(self, fromTreeName, toTreeName): ...\n def verify(self, pkg): ...\n def verifyLocal(self, pkg): ...\n def download(self, pkg, progressCB): ...\n def downloadHttp(self, pkg, progressCB): ...\n def sync(self, pkg, localPath, progressCB): ...\n def install(self, pkg, localPath, progressCB): ...\n def __install(self, pkg, localPath, progressCB): ...\n def compareInstall(self, pkg, localPath): ...\n def addUrls(self, pkg, expiresInSecs): ...\n def prime(self, localPath, progressCB): ...\n def validateLocalCache(self): ...\n def validateStore(self): ...\n def flushLocalCache(self, packageNames): ...\n def flushStore(self): ...\n def __validateStore(self, fileStore): ...\n def __verifyStore(self, fileStore, pkg): ...\n def __flushStore(self, fileStore, packages): ...\n def __storeFiles(self, store, localPath, progressCB): ...\n def __storeFile(self, store, root, rpath, progressCB): ...\n def __storeChunk(self, store, sha1, buf, progressCB): ...\n def __treeNamePath(self, store, treeName): ...\n def __metaTreeNamePath(self, store, metaTreeName): ...\n def __chunkPath(self, store, sha1, encoding): ...\n def __compress(self, buf): ...\n def __decompress(self, buf, encoding): ...\n def __checkSha1(self, buf, sha1, cpath): ...\n\n self.pkgStore = pkgStore\n self.localCache = localCache\n self.config = config\n self.dryRun = False\n self.outVerbose = lambda *args: None\n", "repository": "helix-collective/s3ts", "test_name": "test_s3_merged_package", "smells": [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000985.py"} {"focal_file": "relay_in.py", "focal_class": null, "focal_method": "_contains_required_args", "tests": "import unittest\n\nclass Test_contains_required_args(unittest.TestCase):\n def test_contains_required_args(self):\n self.assertTrue(_contains_required_args(Test_relay_in._TEST_ARGS, Test_relay_in._TEST_REQUIRED_ARGS))\n\n def test_not_contains_required_args(self):\n self.assertFalse(_contains_required_args(Test_relay_in._TEST_ARGS, Test_relay_in._TEST_REQUIRED_ARGS + ['--test3']))\n", "method_code": "def _contains_required_args(args, required_args):\n \"\"\" Validates the arg string from ZNC contains required arg keys \"\"\"\n return len([x for x in required_args if x in args]) == len(required_args)", "context": "def _contains_required_args(args, required_args): ...\ndef _contains_required_args(args, required_args): ...\ndef _parse_args(args, required_args): ...\ndef _is_valid_module_args(parsed_args, required_args): ...\n", "repository": "nerdfarm/znc-relay-in", "test_name": "test_contains_required_args", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000986.py"} {"focal_file": "relay_in.py", "focal_class": null, "focal_method": "_parse_args", "tests": "import unittest\n\nclass Test_parse_args(unittest.TestCase):\n def test_parse_args(self):\n test_module_args = _parse_args(Test_relay_in._TEST_ARGS, Test_relay_in._TEST_REQUIRED_ARGS)\n self.assertTrue(Test_relay_in._TEST_REQUIRED_ARGS.sort() == list(test_module_args.keys()).sort())\n\n def test_no_extra_parse_args(self):\n test_module_args = _parse_args(Test_relay_in._TEST_ARGS + ' --test3=three', Test_relay_in._TEST_REQUIRED_ARGS)\n self.assertTrue(Test_relay_in._TEST_REQUIRED_ARGS.sort() == list(test_module_args.keys()).sort())\n\n def test_missing_parse_args(self):\n try:\n _parse_args(Test_relay_in._TEST_ARGS.replace('--test2', ''), Test_relay_in._TEST_REQUIRED_ARGS)\n except Exception as error:\n self.assertTrue(isinstance(error, ValueError))\n", "method_code": "def _parse_args(args, required_args):\n \"\"\" Parse args according to required args \"\"\"\n module_args = {}\n split_args = []\n for index, token in enumerate([x for x in re.split('=|--', args.strip()) if x.strip()]):\n if token:\n if index % 2 == 0:\n split_args.append('--' + token.strip())\n else:\n split_args.append(token.strip())\n for arg in required_args:\n index = split_args.index(arg)\n if index > -1:\n value = split_args[index + 1]\n if value and value not in required_args:\n module_args[arg] = value.strip()\n return module_args", "context": "def _parse_args(args, required_args): ...\ndef _contains_required_args(args, required_args): ...\ndef _parse_args(args, required_args): ...\ndef _is_valid_module_args(parsed_args, required_args): ...\n", "repository": "nerdfarm/znc-relay-in", "test_name": "test_parse_args", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000987.py"} {"focal_file": "relay_in.py", "focal_class": null, "focal_method": "_is_valid_module_args", "tests": "import unittest\n\nclass Test_is_valid_module_args(unittest.TestCase):\n def test_is_valid_module_args(self):\n test_module_args = _parse_args(Test_relay_in._TEST_ARGS, Test_relay_in._TEST_REQUIRED_ARGS)\n self.assertTrue(_is_valid_module_args(test_module_args, Test_relay_in._TEST_REQUIRED_ARGS))\n\n def test_not_is_valid_module_args(self):\n bad_module_args = {'--test0': 'zero', '--test1': 'one', '--test3': 'two'}\n self.assertFalse(_is_valid_module_args(bad_module_args, Test_relay_in._TEST_REQUIRED_ARGS))\n", "method_code": "def _is_valid_module_args(parsed_args, required_args):\n \"\"\" Validate that parsed args have required args, and no values are None or empty strings \"\"\"\n return len([x for x in required_args if x not in parsed_args.keys()]) == 0 and len([x for x in parsed_args.values() if not x]) == 0", "context": "def _is_valid_module_args(parsed_args, required_args): ...\ndef _contains_required_args(args, required_args): ...\ndef _parse_args(args, required_args): ...\ndef _is_valid_module_args(parsed_args, required_args): ...\n", "repository": "nerdfarm/znc-relay-in", "test_name": "test_is_valid_module_args", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000988.py"} {"focal_file": "ztpserver/topology.py", "focal_class": "Node", "focal_method": "create_node", "tests": "import unittest\n\nclass Test_Node_create_node(unittest.TestCase):\n def test_create_node_success(self):\n node = create_node()\n systemmac = node.systemmac\n kwargs = node.as_dict()\n node = Node(**kwargs)\n self.assertEqual(node.systemmac, systemmac)\n", "method_code": "def create_node(nodeattrs):\n try:\n if nodeattrs.get('systemmac') is not None:\n _systemmac = nodeattrs['systemmac']\n for symbol in [':', '.']:\n _systemmac = str(_systemmac).replace(symbol, '')\n nodeattrs['systemmac'] = _systemmac\n node = Node(**nodeattrs)\n log.debug('%s: created node object %r' % (node.identifier(), node))\n return node\n except KeyError as err:\n log.error('Failed to create node - missing attribute: %s' % err)", "context": "def create_node(nodeattrs): ...\ndef neighbordb_path(): ...\ndef load_file(filename, content_type, node_id): ...\ndef load_neighbordb(node_id, contents=None): ...\ndef load_pattern(pattern, content_type=CONTENT_TYPE_YAML, node_id=None): ...\ndef create_node(nodeattrs): ...\ndef load_resources(attributes, node, node_id): ...\ndef replace_config_action(resource, filename=None): ...\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_create_node_success", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000989.py"} {"focal_file": "ztpserver/topology.py", "focal_class": "Node", "focal_method": "add_neighbors", "tests": "import unittest\n\nclass Test_Node_add_neighbors(unittest.TestCase):\n def test_create_node_neighbors_valid(self):\n nodeattrs = create_node()\n remote_device = random_string()\n remote_interface = random_string()\n neighbors = {'Ethernet1': {'device': remote_device, 'port': remote_interface}}\n nodeattrs.add_neighbors(neighbors)\n kwargs = nodeattrs.as_dict()\n node = Node(**kwargs)\n self.assertIsNotNone(node.neighbors('Ethernet1'))\n self.assertEqual(node.neighbors('Ethernet1')[0].device, remote_device)\n self.assertEqual(node.neighbors('Ethernet1')[0].interface, remote_interface)\n\n def test_add_neighbors_success(self):\n nodeattrs = create_node()\n remote_device = random_string()\n remote_interface = random_string()\n neighbors = {'Ethernet1': [{'device': remote_device, 'port': remote_interface}]}\n kwargs = nodeattrs.as_dict()\n node = Node(**kwargs)\n node.add_neighbors(neighbors)\n self.assertIsNotNone(node.neighbors('Ethernet1'))\n self.assertEqual(node.neighbors('Ethernet1')[0].device, remote_device)\n self.assertEqual(node.neighbors('Ethernet1')[0].interface, remote_interface)\n", "method_code": " def add_neighbors(self, neighbors):\n log.info(\"%s: parsing node's LLDP Neighbor information\" % self.identifier())\n for interface, peers in neighbors.items():\n self.add_neighbor(interface, peers)\n ", "context": "class Node(object):\n def add_neighbors(self, neighbors): ...\n def __init__(self, **kwargs): ...\n def __repr__(self): ...\n def identifier(self): ...\n def add_neighbor(self, interface, peers): ...\n def serialize(self): ...\n\n self.systemmac = kwargs.get('systemmac')\n self.model = kwargs.get('model')\n self.serialnumber = kwargs.get('serialnumber')\n self.version = kwargs.get('version')\n self.neighbors = OrderedCollection()\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_create_node_neighbors_valid", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000990.py"} {"focal_file": "ztpserver/topology.py", "focal_class": "Node", "focal_method": "add_neighbor", "tests": "import unittest\n\nclass Test_Node_add_neighbor(unittest.TestCase):\n def test_add_neighbor(self):\n systemmac = random_string()\n peer = Mock()\n intf = random_string()\n node = Node(systemmac=systemmac)\n node.add_neighbor(intf, [dict(device=peer.remote_device, port=peer.remote_interface)])\n self.assertIsNotNone(node.neighbors(intf))\n self.assertEqual(node.neighbors(intf)[0].device, peer.remote_device)\n self.assertEqual(node.neighbors(intf)[0].interface, peer.remote_interface)\n", "method_code": " def add_neighbor(self, interface, peers):\n try:\n if self.neighbors.get(interface):\n raise NodeError(\"%s: interface '%s' already added to node\" % (self.identifier(), interface))\n _neighbors = list()\n for peer in peers:\n log.debug('%s: creating neighbor %s:%s for interface %s' % (self.identifier(), peer['device'], peer['port'], interface))\n _neighbors.append(Neighbor(peer['device'], peer['port']))\n self.neighbors[interface] = _neighbors\n except KeyError as err:\n log.error('%s: failed to neighbor because of missing key (%s)' % (self.identifier(), str(err)))\n raise NodeError('%s: failed to neighbor because of KeyError (%s)' % (self.identifier(), str(err)))\n ", "context": "class Node(object):\n def add_neighbor(self, interface, peers): ...\n def __init__(self, **kwargs): ...\n def __repr__(self): ...\n def identifier(self): ...\n def add_neighbors(self, neighbors): ...\n def serialize(self): ...\n\n self.systemmac = kwargs.get('systemmac')\n self.model = kwargs.get('model')\n self.serialnumber = kwargs.get('serialnumber')\n self.version = kwargs.get('version')\n self.neighbors = OrderedCollection()\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_add_neighbor", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000991.py"} {"focal_file": "ztpserver/topology.py", "focal_class": "Node", "focal_method": "serialize", "tests": "import unittest\n\nclass Test_Node_serialize(unittest.TestCase):\n def test_serialize_success(self):\n nodeattrs = create_node()\n kwargs = nodeattrs.as_dict()\n node = Node(**kwargs)\n result = node.serialize()\n self.assertEqual(result, nodeattrs.as_dict())\n", "method_code": " def serialize(self):\n result = {}\n for prop in ['model', 'systemmac', 'serialnumber', 'version']:\n if getattr(self, prop):\n result[prop] = getattr(self, prop)\n neighbors = {}\n if self.neighbors:\n for interface, neighbor_list in self.neighbors.items():\n serialized_neighbor_list = []\n for neighbor in neighbor_list:\n serialized_neighbor_list.append(dict(device=neighbor.device, port=neighbor.interface))\n neighbors[interface] = serialized_neighbor_list\n result['neighbors'] = neighbors\n return result\n ", "context": "class Node(object):\n def serialize(self): ...\n def __init__(self, **kwargs): ...\n def __repr__(self): ...\n def identifier(self): ...\n def add_neighbor(self, interface, peers): ...\n def add_neighbors(self, neighbors): ...\n\n self.systemmac = kwargs.get('systemmac')\n self.model = kwargs.get('model')\n self.serialnumber = kwargs.get('serialnumber')\n self.version = kwargs.get('version')\n self.neighbors = OrderedCollection()\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_serialize_success", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000992.py"} {"focal_file": "ztpserver/topology.py", "focal_class": "Pattern", "focal_method": "add_interface", "tests": "import unittest\n\nclass Test_Pattern_add_interface(unittest.TestCase):\n @classmethod\n def test_add_interface_success(cls):\n kwargs = dict(name=random_string(), definition=random_string(), interfaces=None)\n pattern = Pattern(**kwargs)\n remote_remote_device = random_string()\n remote_intf = random_string()\n neighbors = dict(Ethernet1={'device': remote_remote_device, 'port': remote_intf})\n pattern.add_interface(neighbors)\n", "method_code": " def add_interface(self, interface):\n try:\n if not hasattr(interface, 'items'):\n log.error(\"%s: pattern '%s' - failed to add interface %s: missing attribute (items)\" % (self.node_id, self.name, interface))\n raise PatternError(\"%s: pattern '%s' - failed to add interface %s: missing attribute (items)\" % (self.node_id, self.name, interface))\n for intf, neighbors in interface.items():\n remote_device, remote_interface = self.parse_interface(neighbors)\n metadata = dict(interface=intf, neighbors=neighbors)\n patterns = list()\n if intf in ['none', 'any']:\n patterns.append(InterfacePattern(intf, remote_device, remote_interface, self.node_id))\n else:\n intfs = expand_range(intf)\n for item in intfs:\n pattern = InterfacePattern(item, remote_device, remote_interface, self.node_id)\n patterns.append(pattern)\n self.interfaces.append(dict(metadata=metadata, patterns=patterns))\n except InterfacePatternError:\n log.error(\"%s: pattern '%s' - failed to add interface %s\" % (self.node_id, self.name, interface))\n raise PatternError(\"%s: pattern '%s' - failed to add interface %s\" % (self.node_id, self.name, interface))\n ", "context": "class Pattern(object):\n def add_interface(self, interface): ...\n def __init__(self, name=None, definition=None, config_handler=None, interfaces=None, node=None, variables=None, node_id=None): ...\n def __repr__(self): ...\n def variable_substitution(self): ...\n def serialize(self): ...\n def parse_interface(self, neighbor): ...\n def add_interfaces(self, interfaces): ...\n def match_node(self, node): ...\n\n self.name = name\n self.definition = definition\n self.config_handler = config_handler\n self.node = node\n self.node_id = node_id\n self.variables = variables or dict()\n self.interfaces = list()\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000993.py"} {"focal_file": "ztpserver/topology.py", "focal_class": null, "focal_method": "neighbordb_path", "tests": "import unittest\n\nclass Test_neighbordb_path(unittest.TestCase):\n def test_neighbordb_path(self):\n result = neighbordb_path()\n self.assertEqual(result, '/usr/share/ztpserver/neighbordb')\n", "method_code": "def neighbordb_path():\n \"\"\" Returns the path for neighbordb based on the conf file\n \"\"\"\n filepath = runtime.default.data_root\n filename = runtime.neighbordb.filename\n return os.path.join(filepath, filename)", "context": "def neighbordb_path(): ...\ndef neighbordb_path(): ...\ndef load_file(filename, content_type, node_id): ...\ndef load_neighbordb(node_id, contents=None): ...\ndef load_pattern(pattern, content_type=CONTENT_TYPE_YAML, node_id=None): ...\ndef create_node(nodeattrs): ...\ndef load_resources(attributes, node, node_id): ...\ndef replace_config_action(resource, filename=None): ...\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_neighbordb_path", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000994.py"} {"focal_file": "ztpserver/topology.py", "focal_class": null, "focal_method": "load_file", "tests": "import unittest\n\nclass Test_load_file(unittest.TestCase):\n @patch('ztpserver.topology.load')\n def test_load_file(self, m_load):\n result = load_file(random_string(), random_string(), random_string())\n self.assertEqual(result, m_load.return_value)\n", "method_code": "def load_file(filename, content_type, node_id):\n \"\"\" Returns the contents of a file specified by filename.\n\n The requred content_type argument is required and indicates the\n text serialization format the contents are stored in.\n\n If the serializer load function encounters errors, None is returned\n\n \"\"\"\n try:\n return load(filename, content_type, node_id)\n except SerializerError:\n log.error('%s: failed to load file: %s' % (node_id, filename))\n raise", "context": "def load_file(filename, content_type, node_id): ...\ndef neighbordb_path(): ...\ndef load_file(filename, content_type, node_id): ...\ndef load_neighbordb(node_id, contents=None): ...\ndef load_pattern(pattern, content_type=CONTENT_TYPE_YAML, node_id=None): ...\ndef create_node(nodeattrs): ...\ndef load_resources(attributes, node, node_id): ...\ndef replace_config_action(resource, filename=None): ...\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000995.py"} {"focal_file": "ztpserver/topology.py", "focal_class": null, "focal_method": "load_neighbordb", "tests": "import unittest\n\nclass Test_load_neighbordb(unittest.TestCase):\n @patch('ztpserver.topology.validate_neighbordb')\n @patch('ztpserver.topology.load')\n def test_load_neighbordb(self, _, m_load):\n contents = '\\n variables:\\n foo: bar\\n patterns:\\n - name: dummy pattern\\n definition: dummy_definition\\n interfaces:\\n - any: any\\n '\n m_load.return_value = yaml.load(contents)\n result = load_neighbordb(random_string())\n self.assertIsNotNone(result)\n\n @patch('ztpserver.topology.load')\n def test_load_neighbordb_no_variables(self, m_load):\n contents = '\\n patterns:\\n - name: dummy pattern\\n definition: dummy_definition\\n interfaces:\\n - any: any\\n '\n m_load.return_value = yaml.load(contents)\n result = load_neighbordb(random_string())\n self.assertIsInstance(result, Neighbordb)\n", "method_code": "def load_neighbordb(node_id, contents=None):\n try:\n if not contents:\n log.info('%s: loading neighbordb file: %s' % (node_id, neighbordb_path()))\n contents = load_file(neighbordb_path(), CONTENT_TYPE_YAML, node_id)\n if not contents:\n log.info('%s: unable to load neighbordb - file is missing/empty' % node_id)\n contents = dict()\n if not validate_neighbordb(contents, node_id):\n log.error('%s: failed to validate neighbordb' % node_id)\n return\n neighbordb = Neighbordb(node_id)\n if 'variables' in contents:\n neighbordb.add_variables(contents['variables'])\n if 'patterns' in contents:\n neighbordb.add_patterns(contents['patterns'])\n log.debug('%s: loaded neighbordb: %s' % (node_id, neighbordb))\n return neighbordb\n except SerializerError as err:\n tokens = err.message.split('Error:')\n log.error('%s: failed to load neighbordb: %s' % (node_id, 'Error:'.join(tokens[1:]) if len(tokens) > 1 else err.message))\n return None\n except Exception as err:\n log.error('%s: failed to load neighbordb because of error: %s' % (node_id, err))\n return None", "context": "def load_neighbordb(node_id, contents=None): ...\ndef neighbordb_path(): ...\ndef load_file(filename, content_type, node_id): ...\ndef load_neighbordb(node_id, contents=None): ...\ndef load_pattern(pattern, content_type=CONTENT_TYPE_YAML, node_id=None): ...\ndef create_node(nodeattrs): ...\ndef load_resources(attributes, node, node_id): ...\ndef replace_config_action(resource, filename=None): ...\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000996.py"} {"focal_file": "ztpserver/topology.py", "focal_class": null, "focal_method": "load_pattern", "tests": "import unittest\n\nclass Test_load_pattern(unittest.TestCase):\n def test_load_pattern_minimal(self):\n pattern = load_pattern({'name': random_string(), 'definition': random_string(), 'interfaces': []})\n self.assertIsInstance(pattern, Pattern)\n\n def test_load_pattern_with_interfaces(self):\n contents = '\\n name: test\\n # Default pattern - always succeeds\\n definition: dummy_definition\\n interfaces:\\n - any: any:any\\n '\n kwargs = yaml.load(contents)\n pattern = load_pattern(kwargs)\n self.assertIsInstance(pattern, Pattern)\n", "method_code": "def load_pattern(pattern, content_type=CONTENT_TYPE_YAML, node_id=None):\n \"\"\" Returns an instance of Pattern \"\"\"\n try:\n if not isinstance(pattern, collections.Mapping):\n pattern = load_file(pattern, content_type, node_id)\n if 'config-handler' in pattern:\n pattern['config_handler'] = pattern['config-handler']\n del pattern['config-handler']\n for dummy in ['definition', 'name', 'config_handler']:\n if dummy not in pattern:\n pattern[dummy] = dummy\n if not validate_pattern(pattern, node_id):\n log.error('%s: failed to validate pattern attributes' % node_id)\n return None\n pattern['node_id'] = node_id\n return Pattern(**pattern)\n except TypeError as exc:\n log.error(\"%s: failed to load pattern '%s' (%s)\" % (node_id, pattern, exc))", "context": "def load_pattern(pattern, content_type=CONTENT_TYPE_YAML, node_id=None): ...\ndef neighbordb_path(): ...\ndef load_file(filename, content_type, node_id): ...\ndef load_neighbordb(node_id, contents=None): ...\ndef load_pattern(pattern, content_type=CONTENT_TYPE_YAML, node_id=None): ...\ndef create_node(nodeattrs): ...\ndef load_resources(attributes, node, node_id): ...\ndef replace_config_action(resource, filename=None): ...\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_load_pattern_minimal", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000997.py"} {"focal_file": "ztpserver/topology.py", "focal_class": null, "focal_method": "replace_config_action", "tests": "import unittest\n\nclass Test_replace_config_action(unittest.TestCase):\n def test_replace_config_action(self):\n resource = random_string()\n result = replace_config_action(resource)\n self.assertEqual('install static startup-config file', result['name'])\n self.assertEqual('replace_config', result['action'])\n self.assertTrue(result['always_execute'])\n", "method_code": "def replace_config_action(resource, filename=None):\n \"\"\" Builds a definition with a single action replace_config \"\"\"\n filename = filename or 'startup-config'\n server_url = runtime.default.server_url\n url = url_path_join(server_url, 'nodes/', str(resource), filename)\n action = dict(name='install static startup-config file', action='replace_config', always_execute=True, attributes={'url': url})\n return action", "context": "def replace_config_action(resource, filename=None): ...\ndef neighbordb_path(): ...\ndef load_file(filename, content_type, node_id): ...\ndef load_neighbordb(node_id, contents=None): ...\ndef load_pattern(pattern, content_type=CONTENT_TYPE_YAML, node_id=None): ...\ndef create_node(nodeattrs): ...\ndef load_resources(attributes, node, node_id): ...\ndef replace_config_action(resource, filename=None): ...\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_replace_config_action", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000998.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "config", "tests": "import unittest\n\nclass Test_config(unittest.TestCase):\n @patch('ztpserver.controller.create_repository')\n def test_no_config(self, m_repository):\n cfg = {'return_value.read.return_value': {}}\n m_repository.return_value.get_file.configure_mock(**cfg)\n controller = ztpserver.controller.BootstrapController()\n request = Request.blank('')\n request.remote_addr = ''\n resp = controller.config(request)\n self.assertEqual(resp['body'], controller.DEFAULT_CONFIG)\n self.assertEqual(resp['content_type'], constants.CONTENT_TYPE_JSON)\n", "method_code": " def config(self, request, **kwargs):\n \"\"\" Handles GET /bootstrap/config \"\"\"\n body = self.DEFAULT_CONFIG.copy()\n try:\n filename = self.expand(BOOTSTRAP_CONF)\n config = self.repository.get_file(filename).read(CONTENT_TYPE_YAML)\n if not config:\n log.warning('Bootstrap config file empty')\n else:\n if 'logging' in config and config['logging']:\n body['logging'] = config['logging']\n log.info('%s: syslog info included in bootstrap config' % request.remote_addr)\n if 'xmpp' in config and config['xmpp']:\n body['xmpp'] = config['xmpp']\n for key in ['username', 'password', 'domain']:\n if key not in body['xmpp']:\n log.warning(\"Bootstrap config: '%s' missing from XMPP config\" % key)\n if 'rooms' not in body['xmpp'] or not body['xmpp']['rooms']:\n log.warning('Bootstrap config: no XMPP rooms configured')\n log.info('%s: xmpp info included in bootstrap config' % request.remote_addr)\n resp = dict(body=body, content_type=CONTENT_TYPE_JSON)\n except FileObjectNotFound:\n log.warning('Bootstrap config file not found')\n resp = dict(body=body, content_type=CONTENT_TYPE_JSON)\n except FileObjectError:\n log.error('Failed to read bootstrap config file (%s)' % filename)\n resp = self.http_bad_request()\n except Exception as exc:\n log.error('Failed to load bootstrap config file (%s): %s' % (filename, exc))\n resp = self.http_bad_request()\n return resp\n ", "context": "class BootstrapController(BaseController):\n def config(self, request, **kwargs): ...\n def __repr__(self): ...\n def index(self, request, **kwargs): ...\n\n DEFAULT_CONFIG = {'logging': list(), 'xmpp': dict()}\n FOLDER = 'bootstrap'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000999.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "create", "tests": "import unittest\n\nclass Test_create(unittest.TestCase):\n @patch('ztpserver.controller.create_repository')\n def test_create(self, m_repository):\n node = Mock(systemmac=random_string(), serialnumber=random_string())\n body = dict(systemmac=node.systemmac, serialnumber=node.serialnumber)\n request = Request.blank('/nodes')\n request.body = json.dumps(body)\n controller = ztpserver.controller.NodesController()\n with patch.object(controller, 'fsm') as m_fsm:\n controller.create(request)\n self.assertEqual(self.identifier(node), m_fsm.call_args[1]['node_id'])\n", "method_code": " def create(self, request, **kwargs):\n \"\"\" Handle the POST /nodes request\n \n The create method will handle in incoming POST request from the node\n and determine if the node already exists or not. If the node\n does not exist, then the node will be created based on the\n request body.\n \n Args:\n request (webob.Request): the request object from WSGI\n \n Returns:\n A dict as the result of the state machine which is used to\n create a WSGI response object.\n \n \"\"\"\n log.info('%s: received system information from node:\\n%s' % (request.remote_addr, request.json))\n try:\n node = create_node(request.json)\n except Exception as err:\n log.error('Unable to create node: %s (request=%s)' % (err, request))\n response = self.http_bad_request()\n return self.response(**response)\n node_id = node.identifier()\n if not node_id:\n log.error('Missing node identifier: %s (request=%s)' % (node, request))\n response = self.http_bad_request()\n return self.response(**response)\n identifier = runtime.default.identifier\n log.info('%s: node ID is %s:%s' % (request.remote_addr, identifier, node_id))\n return self.fsm('node_exists', request=request, node=node, node_id=node_id)\n ", "context": "class NodesController(BaseController):\n def create(self, request, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001000.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "node_exists", "tests": "import unittest\n\nclass Test_node_exists(unittest.TestCase):\n @patch('ztpserver.controller.create_repository')\n def test_node_exists(self, m_repository):\n m_repository.return_value.exists.return_value = True\n node = Mock(serialnumber=random_string(), systemmac=random_string())\n controller = ztpserver.controller.NodesController()\n resp, state = controller.node_exists(dict(), node=node, node_id=self.identifier(node))\n self.assertEqual(state, 'dump_node')\n self.assertEqual(resp['status'], constants.HTTP_STATUS_CONFLICT)\n\n @patch('ztpserver.controller.create_repository')\n def test_node_exists_failure(self, m_repository):\n m_repository.return_value.exists.return_value = False\n node = Mock(serialnumber=random_string(), systemmac=random_string())\n controller = ztpserver.controller.NodesController()\n resp, state = controller.node_exists(dict(), node=node, node_id=self.identifier(node))\n self.assertEqual(state, 'post_config')\n self.assertIsInstance(resp, dict)\n self.assertEqual(resp, dict())\n", "method_code": " def node_exists(self, response, *args, **kwargs):\n \"\"\" Checks if the node already exists and determines the next state\n \n This method will check for the existence of the node in the\n repository based on the node_id. The node_id keyword is pulled\n from the kwargs dict.\n \n Args:\n response (dict): the response object being constructed\n kwargs (dict): arbitrary keyword arguments\n \n Returns:\n A tuple that includes the updated response object and the\n next state to transition to. If the node already exists\n in the repository with a valid definition or startup-config,\n then the next state is 'dump_node' otherwise the next state\n is 'post_config'\n \n \"\"\"\n next_state = 'post_config'\n node_id = kwargs.get('node_id')\n if self.repository.exists(self.expand(node_id, DEFINITION_FN)) or self.repository.exists(self.expand(node_id, STARTUP_CONFIG_FN)):\n log.info('%s: this node already exists on the server' % node_id)\n response['status'] = HTTP_STATUS_CONFLICT\n next_state = 'dump_node'\n elif self.repository.exists(self.expand(node_id)):\n log.error('%s: node found on server, but no definition or startup-config configured' % node_id)\n return (self.http_bad_request(), None)\n return (response, next_state)\n ", "context": "class NodesController(BaseController):\n def node_exists(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001001.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "dump_node", "tests": "import unittest\n\nclass Test_dump_node(unittest.TestCase):\n @patch('ztpserver.controller.create_repository')\n def test_dump_node_success(self, m_repository):\n node = Mock(serialnumber=random_string(), systemmac=random_string())\n cfg = dict()\n cfg['return_value.get_file'] = Mock()\n m_repository.configure_mock(**cfg)\n controller = ztpserver.controller.NodesController()\n resp, state = controller.dump_node(dict(), node=node, node_id=self.identifier(node))\n self.assertEqual(state, 'set_location')\n self.assertIsInstance(resp, dict)\n self.assertEqual(resp, dict())\n", "method_code": " def dump_node(self, response, *args, **kwargs):\n \"\"\" Writes the contents of the node to the repository\n \n Args:\n response (dict): the response object being constructed\n kwargs (dict): arbitrary keyword arguments\n \n Returns:\n a tuple of response object and next state. The next state is\n 'set_location'\n \n \"\"\"\n try:\n node = kwargs.get('node')\n node_id = kwargs.get('node_id')\n contents = node.serialize()\n filename = self.expand(node_id, NODE_FN)\n fobj = self.repository.get_file(filename)\n except FileObjectNotFound:\n fobj = self.repository.add_file(filename)\n finally:\n fobj.write(contents, CONTENT_TYPE_JSON)\n log.info('%s: node data written to %s:\\n%s' % (node_id, filename, contents))\n return (response, 'set_location')\n ", "context": "class NodesController(BaseController):\n def dump_node(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001002.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "set_location", "tests": "import unittest\n\nclass Test_set_location(unittest.TestCase):\n def test_set_location_success(self):\n node = Mock(serialnumber=random_string(), systemmac=random_string())\n controller = ztpserver.controller.NodesController()\n resp, state = controller.set_location(dict(), node=node, node_id=self.identifier(node))\n location = 'nodes/%s' % self.identifier(node)\n self.assertIsNone(state)\n self.assertIsInstance(resp, dict)\n self.assertEqual(resp['location'], location)\n", "method_code": " def set_location(self, response, *args, **kwargs):\n \"\"\" Writes the HTTP Content-Location header\n \n Args:\n response (dict): the response object being constructed\n kwargs (dict): arbitrary keyword arguments\n \n Returns:\n a tuple of response object and next state. The next state is\n None.\n \n Raises:\n Exception: catches a general exception for logging and then\n re-raises it\n \"\"\"\n node_id = kwargs.get('node_id')\n response['location'] = self.expand(node_id)\n return (response, None)\n ", "context": "class NodesController(BaseController):\n def set_location(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_set_location_success", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001003.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "post_config", "tests": "import unittest\n\nclass Test_post_config(unittest.TestCase):\n def test_post_config_success(self):\n request = Mock(json=dict(config=random_string()))\n node = Mock(serialnumber=random_string(), systemmac=random_string())\n controller = ztpserver.controller.NodesController()\n resp, state = controller.post_config(dict(), request=request, node=node, node_id=self.identifier(node))\n self.assertEqual(state, 'set_location')\n self.assertIsInstance(resp, dict)\n self.assertEqual(resp['status'], constants.HTTP_STATUS_CREATED)\n", "method_code": " def post_config(self, response, *args, **kwargs):\n \"\"\" Writes the nodes startup config file if found in the request\n \n Args:\n response (dict): the response object being constructed\n kwargs (dict): arbitrary keyword arguments\n \n Returns:\n a tuple of response object and next state. If a config key\n was found in the request, the next state is 'set_location'.\n If not, the next state is 'post_node'.\n \n \"\"\"\n if 'config' not in kwargs['request'].json:\n next_state = 'post_node'\n log.info('%s: node does not exist on the server - will try to match node against neighbordb' % kwargs['node_id'])\n else:\n config = kwargs['request'].json['config']\n node_id = kwargs['node_id']\n self.repository.add_folder(self.expand(node_id))\n config_fn = self.expand(node_id, STARTUP_CONFIG_FN)\n self.repository.add_file(config_fn).write(config)\n response['status'] = HTTP_STATUS_CREATED\n next_state = 'set_location'\n return (response, next_state)\n ", "context": "class NodesController(BaseController):\n def post_config(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_post_config_success", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001004.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "get_definition", "tests": "import unittest\n\nclass Test_get_definition(unittest.TestCase):\n @patch('ztpserver.controller.create_repository')\n def test_get_definition_success(self, m_repository):\n cfg = {'return_value.read.return_value': MagicMock()}\n m_repository.return_value.get_file.configure_mock(**cfg)\n controller = ztpserver.controller.NodesController()\n resp, state = controller.get_definition(dict(), resource=random_string())\n self.assertEqual(state, 'get_attributes')\n self.assertIsInstance(resp, dict)\n", "method_code": " def get_definition(self, response, *args, **kwargs):\n \"\"\" Reads the node specific definition from disk and stores it in the\n repsonse dict with key `definition`\n \"\"\"\n try:\n filename = self.expand(kwargs['resource'], DEFINITION_FN)\n fobj = self.repository.get_file(filename)\n definition = fobj.read(CONTENT_TYPE_YAML, kwargs['resource'])\n actions = []\n if 'actions' in definition:\n actions = definition['actions']\n if 'definition' in response:\n _actions = list()\n for action in actions:\n always_execute = action.get('always_execute', False)\n if always_execute:\n _actions.append(action)\n log.debug('%s: always_execute action %s included in definition' % (kwargs['resource'], action.get('name')))\n else:\n log.debug('%s: action %s not included in definition' % (kwargs['resource'], action.get('name')))\n response['definition']['actions'] += _actions\n else:\n for action in actions:\n log.debug('%s: action %s included in definition' % (kwargs['resource'], action.get('name')))\n response['definition'] = definition\n log.debug('%s: defintion is %s (%s)' % (kwargs['resource'], filename, definition['actions']))\n except FileObjectNotFound:\n log.warning('%s: missing definition %s' % (kwargs['resource'], filename))\n except FileObjectError as err:\n log.error(err.message)\n raise Exception('failed to load definition %s' % filename)\n return (response, 'get_attributes')\n ", "context": "class NodesController(BaseController):\n def get_definition(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001005.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "get_startup_config", "tests": "import unittest\n\nclass Test_get_startup_config(unittest.TestCase):\n @patch('ztpserver.controller.replace_config_action')\n def test_get_startup_config_success(self, m_replace_config_action):\n m_replace_config_action.return_value = dict()\n ztpserver.topology.replace_config_action = Mock(return_value=dict())\n response = dict(definition={'actions': list()})\n controller = ztpserver.controller.NodesController()\n resp, state = controller.get_startup_config(response, resource=random_string())\n self.assertEqual(state, 'get_definition')\n self.assertIsInstance(resp, dict)\n\n @patch('ztpserver.controller.replace_config_action')\n def test_get_startup_config_success_no_definition(self, m_replace_config_action):\n resource = random_string()\n action_name = random_string()\n action = {'name': action_name, 'action': 'replace_config'}\n m_replace_config_action.return_value = action\n ztpserver.topology.replace_config_action = Mock(return_value=action)\n controller = ztpserver.controller.NodesController()\n resp, state = controller.get_startup_config(dict(), resource=resource)\n self.assertEqual(state, 'get_definition')\n self.assertIsInstance(resp, dict)\n self.assertTrue(resp['get_startup_config'])\n self.assertTrue(resp['definition'], 'Autogenerated definition')\n self.assertEqual(resp['definition']['actions'][0]['name'], action_name)\n", "method_code": " def get_startup_config(self, response, *args, **kwargs):\n response['get_startup_config'] = False\n try:\n filename = self.expand(kwargs['resource'], STARTUP_CONFIG_FN)\n self.repository.get_file(filename)\n response['get_startup_config'] = True\n actions = [replace_config_action(kwargs['resource'], STARTUP_CONFIG_FN)]\n response['definition'] = dict(name='Autogenerated definition', actions=actions)\n except FileObjectNotFound:\n log.debug('%s: no startup-config %s' % (kwargs['resource'], filename))\n return (response, 'get_definition')\n ", "context": "class NodesController(BaseController):\n def get_startup_config(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001006.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "do_validation", "tests": "import unittest\n\nclass Test_do_validation(unittest.TestCase):\n @patch('ztpserver.controller.load_pattern')\n def test_do_validation_success(self, m_load_pattern):\n cfg = {'return_value.match_node.return_value': True}\n m_load_pattern.configure_mock(**cfg)\n controller = ztpserver.controller.NodesController()\n resp, state = controller.do_validation(dict(), resource=random_string(), node=Mock())\n self.assertEqual(state, 'get_startup_config')\n self.assertIsInstance(resp, dict)\n\n def test_do_validation_disabled_success(self):\n ztpserver.config.runtime.set_value('disable_topology_validation', True, 'default')\n controller = ztpserver.controller.NodesController()\n resp, state = controller.do_validation(dict(), resource=random_string())\n self.assertEqual(state, 'get_startup_config')\n self.assertIsInstance(resp, dict)\n", "method_code": " def do_validation(self, response, *args, **kwargs):\n if not runtime.default.disable_topology_validation:\n log.info('%s: topology validation is ENABLED' % kwargs['resource'])\n filename = self.expand(kwargs['resource'], PATTERN_FN)\n fobj = self.repository.get_file(filename)\n try:\n log.info('%s: checking syntax of pattern file used for topology validation: %s' % (kwargs['resource'], filename))\n pattern = load_pattern(fobj.name, node_id=kwargs['resource'])\n except SerializerError as err:\n log.error(err.message)\n raise Exception('failed to load pattern %s' % filename)\n if not pattern:\n raise Exception('failed to validate pattern')\n log.info('%s: evaluating node against pattern: %s' % (kwargs['resource'], filename))\n if not pattern.match_node(kwargs['node']):\n log.error('%s: node failed pattern validation (%s)' % (kwargs['resource'], filename))\n raise ValidationError('%s: node failed pattern validation (%s)' % (kwargs['resource'], filename))\n log.info('%s: node passed pattern validation: %s' % (kwargs['resource'], filename))\n else:\n log.warning('%s: topology validation is DISABLED' % kwargs['resource'])\n return (response, 'get_startup_config')\n ", "context": "class NodesController(BaseController):\n def do_validation(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001007.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "get_attributes", "tests": "import unittest\n\nclass Test_get_attributes(unittest.TestCase):\n @patch('ztpserver.controller.create_repository')\n def test_get_attributes_success(self, m_repository):\n cfg = {'return_value.read.return_value': random_string()}\n m_repository.return_value.get_file.configure_mock(**cfg)\n controller = ztpserver.controller.NodesController()\n resp, state = controller.get_attributes(dict(), resource=random_string())\n self.assertEqual(state, 'do_substitution')\n self.assertIsInstance(resp, dict)\n\n @patch('ztpserver.controller.create_repository')\n def test_get_attributes_missing(self, m_repository):\n node = create_node()\n m_repository.return_value.exists.return_value = False\n m_repository.return_value.get_file = Mock(side_effect=ztpserver.repository.FileObjectNotFound)\n controller = ztpserver.controller.NodesController()\n resp, state = controller.get_attributes(dict(), resource=self.identifier(node))\n self.assertEqual(state, 'do_substitution')\n self.assertIsInstance(resp, dict)\n self.assertEqual(resp['attributes'], dict())\n", "method_code": " def get_attributes(self, response, *args, **kwargs):\n \"\"\" Reads the resource specific attributes file and stores it in the\n response dict as 'attributes'\n \"\"\"\n try:\n filename = self.expand(kwargs['resource'], ATTRIBUTES_FN)\n fileobj = self.repository.get_file(filename)\n attributes = fileobj.read(CONTENT_TYPE_YAML)\n response['attributes'] = attributes\n log.debug('%s: loaded %s attributes from %s' % (kwargs['resource'], attributes, filename))\n except FileObjectNotFound:\n log.warning('%s: no node specific attributes file' % kwargs['resource'])\n response['attributes'] = dict()\n return (response, 'do_substitution')\n ", "context": "class NodesController(BaseController):\n def get_attributes(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001008.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "do_substitution", "tests": "import unittest\n\nclass Test_do_substitution(unittest.TestCase):\n def test_do_substitution_success(self):\n defattrs = dict(foo='$foo')\n definition = create_definition()\n definition.add_attribute('foo', 'bar')\n definition.add_action(name='dummy action', attributes=defattrs)\n response = dict(definition=definition.as_dict())\n controller = ztpserver.controller.NodesController()\n resp, state = controller.do_substitution(response, resource=random_string())\n self.assertEqual(state, 'do_resources')\n self.assertIsInstance(resp, dict)\n foo = resp['definition']['actions'][0]['attributes']['foo']\n self.assertEqual(foo, 'bar')\n\n def test_do_substitution_with_attributes(self):\n defattrs = dict(foo='$foo')\n definition = create_definition()\n definition.add_attribute('foo', 'bar')\n definition.add_action(name='dummy action', attributes=defattrs)\n g_attr_foo = random_string()\n attributes = create_attributes()\n attributes.add_attribute('foo', g_attr_foo)\n response = dict(definition=definition.as_dict(), attributes=attributes.as_dict())\n controller = ztpserver.controller.NodesController()\n resp, state = controller.do_substitution(response, resource=random_string())\n self.assertEqual(state, 'do_resources')\n self.assertIsInstance(resp, dict)\n foo = resp['definition']['actions'][0]['attributes']['foo']\n self.assertEqual(foo, g_attr_foo)\n\n def test_do_substitution_without_actions(self):\n definition = create_definition()\n definition.actions.append({'name': 'foo'})\n response = dict(definition=definition.as_dict())\n controller = ztpserver.controller.NodesController()\n resp, state = controller.do_substitution(response, resource=random_string())\n self.assertEqual(state, 'do_resources')\n self.assertIsInstance(resp, dict)\n", "method_code": " def do_substitution(self, response, *args, **kwargs):\n definition = response.get('definition')\n attrs = definition.get('attributes', dict())\n nodeattrs = response.get('attributes', dict())\n \n def lookup(name):\n log.debug('%s: lookup up value for variable %s' % (kwargs['resource'], name))\n return nodeattrs.get(name, attrs.get(name))\n _actions = list()\n for action in definition['actions']:\n log.debug('%s: processing action %s (variable substitution)' % (kwargs['resource'], action.get('name')))\n _attributes = dict()\n if 'attributes' in action:\n for key, value in action.get('attributes').items():\n try:\n update = dict()\n for _key, _value in value.items():\n if str(_value).startswith('$'):\n _value = lookup(_value[1:])\n update[_key] = _value\n except AttributeError:\n if str(value).startswith('$'):\n value = lookup(value[1:])\n update = value\n finally:\n _attributes[key] = update\n action['attributes'] = _attributes\n _actions.append(action)\n definition['actions'] = _actions\n response['definition'] = definition\n return (response, 'do_resources')\n ", "context": "class NodesController(BaseController):\n def do_substitution(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_do_substitution_success", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001009.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "do_resources", "tests": "import unittest\n\nclass Test_do_resources(unittest.TestCase):\n def test_do_resources_success(self):\n var_foo = random_string()\n ztpserver.controller.load_resources = Mock(return_value=dict(foo=var_foo))\n definition = create_definition()\n definition.add_action(name='dummy action', attributes=dict(foo=random_string()))\n response = dict(definition=definition.as_dict())\n controller = ztpserver.controller.NodesController()\n resp, state = controller.do_resources(response, node=Mock(), resource=random_string())\n self.assertEqual(state, 'finalize_response')\n self.assertIsInstance(resp, dict)\n foo = resp['definition']['actions'][0]['attributes']['foo']\n self.assertEqual(foo, var_foo)\n", "method_code": " def do_resources(self, response, *args, **kwargs):\n definition = response['definition']\n node = kwargs.get('node')\n _actions = list()\n try:\n for action in definition.get('actions'):\n attrs = action.get('attributes', dict())\n action['attributes'] = load_resources(attrs, node, kwargs['resource'])\n _actions.append(action)\n except Exception as exc:\n log.error(exc)\n raise Exception('failed to allocate resources')\n definition['actions'] = _actions\n response['definition'] = definition\n return (response, 'finalize_response')\n ", "context": "class NodesController(BaseController):\n def do_resources(self, response, *args, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def put_config(self, request, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_do_resources_success", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001010.py"} {"focal_file": "ztpserver/controller.py", "focal_class": null, "focal_method": "put_config", "tests": "import unittest\n\nclass Test_put_config(unittest.TestCase):\n @patch('os.path.isfile')\n def test_put_config_success(self, m_is_file):\n m_is_file.return_value = False\n resource = random_string()\n body = random_string()\n request = Mock(content_type=constants.CONTENT_TYPE_OTHER, body=body)\n controller = ztpserver.controller.NodesController()\n resp = controller.put_config(request, resource=resource)\n self.assertEqual(resp, dict())\n", "method_code": " def put_config(self, request, **kwargs):\n node_id = kwargs['resource']\n log.debug('%s: startup-config PUT request: \\n%s\\n' % (node_id, request))\n fobj = None\n try:\n body = str(request.body)\n content_type = str(request.content_type)\n filename = self.expand(node_id, STARTUP_CONFIG_FN)\n fobj = self.repository.get_file(filename)\n except FileObjectNotFound:\n log.debug('%s: file not found: %s (adding it)' % (node_id, filename))\n fobj = self.repository.add_file(filename)\n finally:\n if fobj:\n fobj.write(body, content_type)\n else:\n log.error('%s: unable to write %s' % (node_id, filename))\n return self.http_bad_request()\n script = self.repository.expand(self.expand(node_id, CONFIG_HANDLER_FN))\n if os.path.isfile(script):\n proc = subprocess.Popen(script, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)\n code = proc.returncode\n out, err = proc.communicate()\n if code or err:\n log.warn('Startup-config saved for %s (%s failed: return code=%s, stderr=%s)' % (node_id, script, code, err))\n log.debug('%s output: \\n%s' % (script, out))\n else:\n log.info('Startup-config saved for %s (%s executed successfully)' % (node_id, script))\n log.debug('%s output: \\n%s' % (script, out))\n else:\n log.info('Startup-config saved for %s (no config-handler)' % node_id)\n return {}\n ", "context": "class NodesController(BaseController):\n def put_config(self, request, **kwargs): ...\n def __repr__(self): ...\n def fsm(self, state, **kwargs): ...\n def get_config(self, request, resource, **kwargs): ...\n def create(self, request, **kwargs): ...\n def node_exists(self, response, *args, **kwargs): ...\n def post_config(self, response, *args, **kwargs): ...\n def post_node(self, response, *args, **kwargs): ...\n def dump_node(self, response, *args, **kwargs): ...\n def set_location(self, response, *args, **kwargs): ...\n def show(self, request, resource, *args, **kwargs): ...\n def do_validation(self, response, *args, **kwargs): ...\n def get_startup_config(self, response, *args, **kwargs): ...\n def get_definition(self, response, *args, **kwargs): ...\n def get_attributes(self, response, *args, **kwargs): ...\n def do_substitution(self, response, *args, **kwargs): ...\n def do_resources(self, response, *args, **kwargs): ...\n def finalize_response(self, response, *args, **kwargs): ...\n\n FOLDER = 'nodes'\n", "repository": "arista-eosplus/ztpserver", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001011.py"} {"focal_file": "ztpserver/config.py", "focal_class": null, "focal_method": "add_attribute", "tests": "import unittest\n\nclass Test_add_attribute(unittest.TestCase):\n def test_group_add_attribute(self):\n obj = ztpserver.config.Group('test', self.config)\n obj.add_attribute('test')\n self.assertEqual(self.config.attributes[0], ('test', 'test'))\n\n def test_config_add_attribute_valid(self):\n attr = self.Attr('test', str, None, None)\n self.config.add_attribute(attr)\n self.assertIsNone(getattr(self.config, 'test'))\n self.assertIn((None, 'test'), self.config.attributes)\n\n def test_config_add_attribute_default_value(self):\n attr = self.Attr('test', str, None, 'value')\n self.config.add_attribute(attr)\n self.assertEqual(self.config.test, 'value')\n\n def test_config_add_attribute_group_and_default_value(self):\n attr = self.Attr('test', str, 'group', 'value')\n self.config.add_attribute(attr)\n self.assertEqual(self.config.group.test, 'value')\n self.assertIsInstance(self.config.group, ztpserver.config.Group)\n\n def test_config_add_attribute_duplicate(self):\n attr = self.Attr('test', str, None, None)\n self.config.add_attribute(attr)\n self.assertRaises(AttributeError, self.config.add_attribute, attr)\n\n def test_config_set_value_attribute(self):\n attr = self.Attr('test', str, None, None)\n self.config.add_attribute(attr)\n self.config.set_value('test', 'value')\n self.assertEqual(self.config.test, 'value')\n", "method_code": " def add_attribute(self, item):\n self.config.add_attribute(item, self.name)\n ", "context": "class Group(collections.Mapping):\n def add_attribute(self, item): ...\n def __init__(self, name, config): ...\n def __getattr__(self, name): ...\n def __getitem__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __delitem__(self): ...\n def __setitem__(self): ...\n def _keys(self): ...\n\n self.name = name\n self.config = config\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_group_add_attribute", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001012.py"} {"focal_file": "ztpserver/config.py", "focal_class": null, "focal_method": "add_group", "tests": "import unittest\n\nclass Test_add_group(unittest.TestCase):\n def test_config_add_group(self):\n for grp in ['test', 100]:\n self.config.add_group(grp)\n grp = str(grp) if isinstance(grp, int) else grp\n self.assertIn(grp, self.config.groups)\n self.assertIsInstance(getattr(self.config, grp), ztpserver.config.Group)\n", "method_code": " def add_group(self, group):\n if isinstance(group, Group):\n self.groups.append(group.name)\n else:\n group = str(group)\n self.groups.append(group)\n ", "context": "class Config(collections.Mapping):\n def add_group(self, group): ...\n def __init__(self): ...\n def __getattr__(self, name): ...\n def __getitem__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __repr__(self): ...\n def __delitem__(self): ...\n def __setitem__(self): ...\n def __get_attribute__(self, name, group=None): ...\n def add_attribute(self, item, group=None): ...\n def _transform(self, item, value): ...\n def set_value(self, name, value, group=None): ...\n def clear_value(self, name, group=None): ...\n def read(self, filename): ...\n\n self.attributes = dict()\n self.groups = list()\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_config_add_group", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001013.py"} {"focal_file": "ztpserver/config.py", "focal_class": null, "focal_method": "clear_value", "tests": "import unittest\n\nclass Test_clear_value(unittest.TestCase):\n def test_config_runtime_clear_value(self):\n obj = ztpserver.config.runtime\n obj.set_value('interface', '1.1.1.1', 'server')\n self.assertEqual(obj.server.interface, '1.1.1.1')\n obj.clear_value('interface', 'server')\n self.assertEqual(obj.server.interface, '0.0.0.0')\n", "method_code": " def clear_value(self, name, group=None):\n \"\"\" clears the attributes value and resets it to default \"\"\"\n if not group and name in self.groups:\n raise AttributeError('Failed to clear value (name=%s, group=%s): cannot clear values for a group' % (name, group))\n item = self.attributes.get((group, name))\n if item['_metadata'].default is None:\n item['value'] = None\n else:\n item['value'] = self._transform(item, item['_metadata'].default)\n ", "context": "class Config(collections.Mapping):\n def clear_value(self, name, group=None): ...\n def __init__(self): ...\n def __getattr__(self, name): ...\n def __getitem__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __repr__(self): ...\n def __delitem__(self): ...\n def __setitem__(self): ...\n def __get_attribute__(self, name, group=None): ...\n def add_attribute(self, item, group=None): ...\n def add_group(self, group): ...\n def _transform(self, item, value): ...\n def set_value(self, name, value, group=None): ...\n def read(self, filename): ...\n\n self.attributes = dict()\n self.groups = list()\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_config_runtime_clear_value", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001014.py"} {"focal_file": "ztpserver/config.py", "focal_class": null, "focal_method": "set_value", "tests": "import unittest\n\nclass Test_set_value(unittest.TestCase):\n def test_config_runtime_set_value(self):\n obj = ztpserver.config.runtime\n obj.set_value('interface', '1.1.1.1', 'server')\n self.assertEqual(obj.server.interface, '1.1.1.1')\n", "method_code": " def set_value(self, name, value, group=None):\n if not group and name in self.groups:\n raise AttributeError('Failed to set value (name=%s, group=%s): cannot set a value for a group' % (name, group))\n item = self.attributes.get((group, name))\n if item is None:\n raise AttributeError('Failed to set value (name=%s, group=%s): missing item' % (name, group))\n item['value'] = self._transform(item, value)\n ", "context": "class Config(collections.Mapping):\n def set_value(self, name, value, group=None): ...\n def __init__(self): ...\n def __getattr__(self, name): ...\n def __getitem__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __repr__(self): ...\n def __delitem__(self): ...\n def __setitem__(self): ...\n def __get_attribute__(self, name, group=None): ...\n def add_attribute(self, item, group=None): ...\n def add_group(self, group): ...\n def _transform(self, item, value): ...\n def clear_value(self, name, group=None): ...\n def read(self, filename): ...\n\n self.attributes = dict()\n self.groups = list()\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_config_runtime_set_value", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001015.py"} {"focal_file": "ztpserver/utils.py", "focal_class": null, "focal_method": "expand_range", "tests": "import unittest\n\nclass Test_expand_range(unittest.TestCase):\n def test_expand_basic_range(self):\n \"\"\" Issue #358\n \"\"\"\n result = utils.expand_range('Ethernet2-4')\n self.assertItemsEqual(result, ['Ethernet2', 'Ethernet3', 'Ethernet4'])\n\n def test_expand_linecard_range(self):\n \"\"\" Issue #358\n \"\"\"\n result = utils.expand_range('Ethernet2/2-2/4')\n self.assertItemsEqual(result, ['Ethernet2/2', 'Ethernet2/3', 'Ethernet2/4'])\n", "method_code": "def expand_range(interfaces):\n \"\"\" Returns a naturally sorted list of items expanded from interfaces. \"\"\"\n items = set()\n prefix = None\n for group in [x.strip() for x in interfaces.split(',')]:\n ranges = [x.strip() for x in group.split('-')]\n if len(ranges) == 1:\n interface = ranges[0].lower()\n match = ETHERNET_RE.match(interface)\n if match:\n intf_no = interface[len(match.groups()[0]):]\n for token in intf_no.split('/'):\n if int(token) < 1:\n log.warning('Unable to expand interface range: %s (invalid interface number)' % group)\n raise TypeError('Unable to expand interface range: %s (invalid interface number)' % group)\n prefix = 'Ethernet'\n items.add('%s%s' % (prefix, intf_no))\n else:\n match = MANAGEMENT_RE.match(interface)\n if match:\n intf_no = interface[len(match.groups()[0]):]\n for token in intf_no.split('/'):\n if int(token) < 1:\n log.warning('Unable to expand interface range: %s (invalid interface number)' % group)\n raise TypeError('Unable to expand interface range: %s (invalid interface number)' % group)\n prefix = 'Management'\n items.add('%s%s' % (prefix, intf_no))\n else:\n match = INTERFACE_NO_RE.match(interface)\n if match:\n for token in interface.split('/'):\n if int(token) < 1:\n log.warning('Unable to expand interface range: %s (invalid interface number)' % group)\n raise TypeError('Unable to expand interface range: %s (invalid interface number)' % group)\n items.add('%s%s' % (prefix, interface))\n else:\n log.warning('Unable to expand interface range: %s (invalid interface)' % group)\n raise TypeError('Unable to expand interface range: %s (invalid interface)' % group)\n elif len(ranges) == 2:\n [start, end] = [x.lower() for x in ranges]\n items_len = len(items)\n for regex, intf_type in [(ETHERNET_RE, 'Ethernet'), (MANAGEMENT_RE, 'Management'), (INTERFACE_NO_RE, prefix)]:\n match_start = regex.match(start)\n if match_start:\n if regex != INTERFACE_NO_RE:\n start_intf_tokens = start[len(match_start.groups()[0]):].split('/')\n else:\n start_intf_tokens = start.split('/')\n match_end = regex.match(end)\n end_intf_tokens = None\n if match_end:\n if regex != INTERFACE_NO_RE:\n end_intf_tokens = end[len(match_end.groups()[0]):].split('/')\n else:\n end_intf_tokens = end.split('/')\n else:\n match_end = INTERFACE_NO_RE.match(end)\n if match_end:\n end_intf_tokens = end.split('/')\n if not end_intf_tokens:\n log.warning('Unable to expand interface range: %s (invalid range end)' % group)\n raise TypeError('Unable to expand interface range: %s (invalid range end)' % group)\n if start_intf_tokens[:-1] != end_intf_tokens[:-1]:\n log.warning('Unable to expand interface range: %s (invalid range)' % group)\n raise TypeError('Unable to expand interface range: %s (invalid range)' % group)\n start_index = int(start_intf_tokens[-1])\n end_index = int(end_intf_tokens[-1])\n if start_index >= end_index:\n log.warning('Unable to expand interface range: %s (non-increasing range)' % group)\n raise TypeError('Unable to expand interface range: %s (non-increasing range)' % group)\n if start_index < 1 or end_index < 1:\n log.warning('Unable to expand interface range: %s (invalid interface number)' % group)\n raise TypeError('Unable to expand interface range: %s (invalid interface number)' % group)\n for index in range(start_index, end_index + 1):\n prefix = intf_type\n items.add('%s%s' % (intf_type, '/'.join(start_intf_tokens[:-1] + [str(index)])))\n if items_len == len(items):\n log.warning('Unable to expand interface range: %s ' % group)\n raise TypeError('Unable to expand interface range: %s ' % group)\n else:\n log.warning('Unable to expand interface range: %s (invalid input)' % group)\n raise TypeError('Unable to expand interface range: %s (invalid input)' % group)\n log.debug('%s expanded to: %s' % (interfaces, items))\n return items", "context": "def expand_range(interfaces): ...\ndef atoi(text): ...\ndef natural_keys(text): ...\ndef expand_range(interfaces): ...\ndef parse_interface(neighbor, node_id): ...\ndef url_path_join(*parts): ...\ndef get_first_token(sequence): ...\ndef all_files(path): ...\n", "repository": "arista-eosplus/ztpserver", "test_name": "test_expand_basic_range", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001016.py"} {"focal_file": "ocookie/__init__.py", "focal_class": "ocookie.CookieDict", "focal_method": "cookie_header_value", "tests": "import unittest\n\nclass Test_ocookie_CookieDict_cookie_header_value(unittest.TestCase):\n def test_cookie_header_value_one(self):\n cookie_dict = ocookie.CookieDict()\n cookie_dict['a'] = ocookie.Cookie('a', 'b')\n header_value = cookie_dict.cookie_header_value()\n self.assertEqual('a=b', header_value)\n\n def test_cookie_header_value_two(self):\n cookie_dict = ocookie.CookieDict()\n cookie_dict['a'] = ocookie.Cookie('a', 'b')\n cookie_dict['c'] = ocookie.Cookie('c', 'd')\n header_value = cookie_dict.cookie_header_value()\n self.assertTrue(header_value == 'a=b; c=d' or header_value == 'c=d; a=b')\n\n def test_cookie_header_value_empty(self):\n cookie_dict = ocookie.CookieDict()\n cookie_dict['a'] = ocookie.Cookie('a', 'aa')\n cookie_dict['b'] = ocookie.Cookie('b', '')\n cookie_dict['c'] = ocookie.Cookie('c', None)\n header_value = cookie_dict.cookie_header_value()\n self.assertEqual('a=aa', header_value)\n\n def test_cookie_header_value_colon(self):\n cookie_dict = ocookie.CookieDict()\n cookie_dict['a'] = ocookie.Cookie('a', 'b:c')\n header_value = cookie_dict.cookie_header_value()\n self.assertEqual('a=b:c', header_value)\n", "method_code": " def cookie_header_value(self):\n pairs = [name + '=' + self[name].value for name in self if self[name].value is not None and self[name].value.strip() != '']\n return '; '.join(pairs)\n ", "context": "class CookieDict(dict):\n def cookie_header_value(self): ...", "repository": "p/ocookie", "test_name": "test_cookie_header_value_one", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001017.py"} {"focal_file": "ocookie/__init__.py", "focal_class": "ocookie.Cookie", "focal_method": "add", "tests": "import unittest\n\nclass Test_ocookie_Cookie_add(unittest.TestCase):\n def test_add(self):\n cookie_jar = ocookie.CookieJar()\n cookie = ocookie.Cookie('foo', 'bar')\n cookie_jar.add(cookie)\n self.assertTrue('foo' in cookie_jar)\n self.assertFalse('bar' in cookie_jar)\n", "method_code": " def add(self, cookie):\n \"\"\"Adds a cookie to the cookie jar.\n \n If a cookie already exists with the same name, the old cookie is\n overwritten with the provided cookie.\n \n If the expiration time of the new cookie is in the past then\n no cookie is set (and if there was an existing cookie with the\n same name, the old cookie is deleted).\n \"\"\"\n if not isinstance(cookie, LiveCookie):\n cookie = LiveCookie(cookie.name, cookie.value, **cookie.attributes)\n if cookie.valid():\n self.cookie_dict[cookie.name] = cookie\n elif cookie.name in self.cookie_dict:\n del self.cookie_dict[cookie.name]\n ", "context": "class CookieJar(object):\n def add(self, cookie): ...\n def __init__(self, cookie_jar=None): ...\n def __iter__(self): ...\n def __delitem__(self, name): ...\n def __getitem__(self, name): ...\n def __setitem__(self, name, cookie): ...\n def __contains__(self, name): ...\n def valid_cookies(self): ...\n def build_cookie_header_value(self): ...\n def clear(self): ...\n def keys(self): ...\n", "repository": "p/ocookie", "test_name": "test_add", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001018.py"} {"focal_file": "ocookie/__init__.py", "focal_class": "ocookie.Cookie", "focal_method": "clear", "tests": "import unittest\n\nclass Test_ocookie_Cookie_clear(unittest.TestCase):\n def test_clear(self):\n cookie_jar = ocookie.CookieJar()\n cookie = ocookie.Cookie('foo', 'bar')\n cookie_jar.add(cookie)\n assert 'foo' in cookie_jar\n cookie_jar.clear()\n assert 'foo' not in cookie_jar\n", "method_code": " def clear(self):\n self.cookie_dict = CookieDict()\n ", "context": "class CookieJar(object):\n def clear(self): ...\n def __init__(self, cookie_jar=None): ...\n def __iter__(self): ...\n def __delitem__(self, name): ...\n def __getitem__(self, name): ...\n def __setitem__(self, name, cookie): ...\n def __contains__(self, name): ...\n def add(self, cookie): ...\n def valid_cookies(self): ...\n def build_cookie_header_value(self): ...\n def keys(self): ...\n", "repository": "p/ocookie", "test_name": "test_clear", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001019.py"} {"focal_file": "ocookie/__init__.py", "focal_class": "ocookie.Cookie", "focal_method": "build_cookie_header_value", "tests": "import unittest\n\nclass Test_ocookie_Cookie_build_cookie_header_value(unittest.TestCase):\n def test_build_cookie_header_value(self):\n cookie_jar = ocookie.CookieJar()\n cookie = ocookie.Cookie('foo', 'bar')\n cookie_jar.add(cookie)\n assert 'foo' in cookie_jar\n expected = 'foo=bar'\n self.assertEqual(expected, cookie_jar.build_cookie_header_value())\n\n def test_build_cookie_header_value_two_cookies(self):\n cookie_jar = ocookie.CookieJar()\n cookie_jar.add(ocookie.Cookie('foo', 'foo-value'))\n cookie_jar.add(ocookie.Cookie('bar', 'bar-value'))\n actual = cookie_jar.build_cookie_header_value()\n self.assertTrue(actual == 'foo=foo-value; bar=bar-value' or actual == 'bar=bar-value; foo=foo-value')\n\n def test_build_cookie_header_value_empty(self):\n cookie_jar = ocookie.CookieJar()\n cookie_jar.add(ocookie.Cookie('foo', 'foo-value'))\n cookie_jar.add(ocookie.Cookie('bar', ''))\n cookie_jar.add(ocookie.Cookie('quux', None))\n expected = 'foo=foo-value'\n self.assertEqual(expected, cookie_jar.build_cookie_header_value())\n\n def test_build_cookie_header_value_colon(self):\n cookie_jar = ocookie.CookieJar()\n cookie_jar.add(ocookie.Cookie('foo', 'a:b'))\n expected = 'foo=a:b'\n self.assertEqual(expected, cookie_jar.build_cookie_header_value())\n", "method_code": " def build_cookie_header_value(self):\n \"\"\"Creates value for a Cookie header, as would be sent by a user agent,\n from cookies currently in the jar.\n \n Cookies that are expired are not included.\n \"\"\"\n cookies = []\n for cookie in self.valid_cookies():\n if cookie.value is not None and cookie.value.strip() != '':\n text = cookie.name + '=' + cookie.value\n cookies.append(text)\n return '; '.join(cookies)\n ", "context": "class CookieJar(object):\n def build_cookie_header_value(self): ...\n def __init__(self, cookie_jar=None): ...\n def __iter__(self): ...\n def __delitem__(self, name): ...\n def __getitem__(self, name): ...\n def __setitem__(self, name, cookie): ...\n def __contains__(self, name): ...\n def add(self, cookie): ...\n def valid_cookies(self): ...\n def clear(self): ...\n def keys(self): ...\n", "repository": "p/ocookie", "test_name": "test_build_cookie_header_value", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001020.py"} {"focal_file": "fdrmethods.py", "focal_class": null, "focal_method": "dsfdr", "tests": "import unittest\n\nclass Test_dsfdr(unittest.TestCase):\n def test_dsfdr(self):\n res_ds = fdrmethods.dsfdr(self.data, self.labels, method='meandiff', transformtype='none', alpha=0.1, numperm=1000, fdrmethod='dsfdr')\n self.assertEqual(np.shape(res_ds)[0], self.data.shape[0])\n np.testing.assert_array_equal(res_ds[0], [True, False, False])\n res_bh = fdrmethods.dsfdr(self.data, self.labels, method='meandiff', transformtype='none', alpha=0.1, numperm=1000, fdrmethod='bhfdr')\n self.assertEqual(np.shape(res_bh)[0], self.data.shape[0])\n np.testing.assert_array_equal(res_bh[0], [True, False, False])\n res_by = fdrmethods.dsfdr(self.data, self.labels, method='meandiff', transformtype='none', alpha=0.1, numperm=1000, fdrmethod='byfdr')\n self.assertEqual(np.shape(res_by)[0], self.data.shape[0])\n np.testing.assert_array_equal(res_by[0], [True, False, False])\n np.random.seed(31)\n res_ds2 = fdrmethods.dsfdr(self.data_sim, self.labels_sim, method='meandiff', transformtype='none', alpha=0.1, numperm=1000, fdrmethod='dsfdr')[0]\n fdr_ds2 = np.sum(np.where(res_ds2)[0] >= 100) / np.sum(res_ds2)\n np.testing.assert_equal(fdr_ds2 <= 0.1, True)\n np.random.seed(31)\n res_bh2 = fdrmethods.dsfdr(self.data_sim, self.labels_sim, method='meandiff', transformtype='none', alpha=0.1, numperm=1000, fdrmethod='bhfdr')[0]\n self.assertEqual(np.shape(res_bh2)[0], self.data_sim.shape[0])\n fdr_bh2 = np.sum(np.where(res_bh2)[0] >= 100) / np.sum(res_bh2)\n np.testing.assert_equal(fdr_bh2 <= 0.1, True)\n np.random.seed(31)\n res_by2 = fdrmethods.dsfdr(self.data_sim, self.labels_sim, method='meandiff', transformtype='none', alpha=0.1, numperm=1000, fdrmethod='byfdr')[0]\n self.assertEqual(np.shape(res_by2)[0], self.data_sim.shape[0])\n fdr_by2 = np.sum(np.where(res_by2)[0] >= 100) / np.sum(res_by2)\n np.testing.assert_equal(fdr_by2 <= 0.1, True)\n", "method_code": "def dsfdr(data, labels, transformtype='rankdata', method='meandiff', alpha=0.1, numperm=1000, fdrmethod='dsfdr'):\n \"\"\"\n\tcalculate the Discrete FDR for the data\n\n\tinput:\n\tdata : N x S numpy array\n\t\teach column is a sample (S total), each row an OTU (N total)\n\tlabels : a 1d numpy array (length S)\n\t\tthe labels of each sample (same order as data) with the group (0/1 if binary, 0-G-1 if G groups, or numeric values for correlation)\n\t\n\n\ttransformtype : str or ''\n\t\ttransformation to apply to the data before caluculating the test statistic\n\t\t'rankdata' : rank transfrom each OTU reads\n\t\t'log2data' : calculate log2 for each OTU using minimal cutoff of 2\n\t\t'normdata' : normalize the data to constant sum per samples\n\t\t'binarydata' : convert to binary absence/presence\n\n\tmethod : str or function\n\t\tthe method to use for the statistical test. options:\n\t\t'meandiff' : mean(A)-mean(B) (binary)\n\t\t'mannwhitney' : mann-whitneu u-test (binary)\n\t\t'kruwallis' : kruskal-wallis test (multiple groups)\n\t\t'stdmeandiff' : (mean(A)-mean(B))/(std(A)+std(B)) (binary)\n\t\t'spearman' : spearman correlation (numeric)\n\t\t'pearson' : pearson correlation (numeric)\n\t\t'nonzerospearman' : spearman correlation only non-zero entries (numeric)\n\t\t'nonzeropearson' : pearson correlation only non-zero entries (numeric)\n\t\tfunction : use this function to calculate the test statistic (input is data,labels, output is array of float)\t\n\n\talpha : float\n\t\tthe desired FDR control level\n\tnumperm : int\n\t\tnumber of permutations to perform\n\n\tfdrmethod : str\n\t\tthe FDR procedure to determine significant bacteria\n\t\t'dsfdr' : discrete FDR method\n\t\t'bhfdr' : Benjamini-Hochberg FDR method\n\t\t'byfdr' : Benjamini-Yekutielli FDR method \n\t\t'filterBH' : Benjamini-Hochberg FDR method with filtering\n\n\toutput:\n\treject : np array of bool (length N)\n\t\tTrue for OTUs where the null hypothesis is rejected\n\ttstat : np array of float (length N)\n\t\tthe test statistic value for each OTU (for effect size)\n\tpvals : np array of float (length N)\n\t the p-value for each OTU\t\n\t\"\"\"\n data = data.copy()\n if fdrmethod == 'filterBH':\n index = []\n n0 = np.sum(labels == 0)\n n1 = np.sum(labels == 1)\n for i in range(np.shape(data)[0]):\n nonzeros = np.count_nonzero(data[i, :])\n if nonzeros < min(n0, n1):\n pval_min = (comb(n0, nonzeros, exact=True) + comb(n1, nonzeros, exact=True)) / comb(n0 + n1, nonzeros)\n if pval_min <= alpha:\n index.append(i)\n else:\n index.append(i)\n data = data[index, :]\n if transformtype == 'rankdata':\n data = transform.rankdata(data)\n elif transformtype == 'log2data':\n data = transform.log2data(data)\n elif transformtype == 'binarydata':\n data = transform.binarydata(data)\n elif transformtype == 'normdata':\n data = transform.normdata(data)\n elif transformtype is None:\n pass\n else:\n raise ValueError('transform type %s not supported' % transformtype)\n numbact = np.shape(data)[0]\n labels = labels.copy()\n if method == 'meandiff':\n method = statistics.meandiff\n tstat = method(data, labels)\n t = np.abs(tstat)\n numsamples = np.shape(data)[1]\n p = np.zeros([numsamples, numperm])\n k1 = 1 / np.sum(labels == 0)\n k2 = 1 / np.sum(labels == 1)\n for cperm in range(numperm):\n np.random.shuffle(labels)\n p[labels == 0, cperm] = k1\n p2 = np.ones(p.shape) * k2\n p2[p > 0] = 0\n mean1 = np.dot(data, p)\n mean2 = np.dot(data, p2)\n u = np.abs(mean1 - mean2)\n elif method == 'mannwhitney' or method == 'kruwallis' or method == 'stdmeandiff':\n if method == 'mannwhitney':\n method = statistics.mannwhitney\n if method == 'kruwallis':\n method = statistics.kruwallis\n if method == 'stdmeandiff':\n method = statistics.stdmeandiff\n tstat = method(data, labels)\n t = np.abs(tstat)\n u = np.zeros([numbact, numperm])\n for cperm in range(numperm):\n rlabels = np.random.permutation(labels)\n rt = method(data, rlabels)\n u[:, cperm] = rt\n elif method == 'spearman' or method == 'pearson':\n if method == 'spearman':\n data = transform.rankdata(data)\n labels = sp.stats.rankdata(labels)\n meanval = np.mean(data, axis=1).reshape([data.shape[0], 1])\n data = data - np.repeat(meanval, data.shape[1], axis=1)\n labels = labels - np.mean(labels)\n tstat = np.dot(data, labels)\n t = np.abs(tstat)\n permlabels = np.zeros([len(labels), numperm])\n for cperm in range(numperm):\n rlabels = np.random.permutation(labels)\n permlabels[:, cperm] = rlabels\n u = np.abs(np.dot(data, permlabels))\n elif method == 'nonzerospearman' or method == 'nonzeropearson':\n t = np.zeros([numbact])\n tstat = np.zeros([numbact])\n u = np.zeros([numbact, numperm])\n for i in range(numbact):\n index = np.nonzero(data[i, :])\n label_nonzero = labels[index]\n sample_nonzero = data[i, :][index]\n if method == 'nonzerospearman':\n sample_nonzero = sp.stats.rankdata(sample_nonzero)\n label_nonzero = sp.stats.rankdata(label_nonzero)\n sample_nonzero = sample_nonzero - np.mean(sample_nonzero)\n label_nonzero = label_nonzero - np.mean(label_nonzero)\n tstat[i] = np.dot(sample_nonzero, label_nonzero)\n t[i] = np.abs(tstat[i])\n permlabels = np.zeros([len(label_nonzero), numperm])\n for cperm in range(numperm):\n rlabels = np.random.permutation(label_nonzero)\n permlabels[:, cperm] = rlabels\n u[i, :] = np.abs(np.dot(sample_nonzero, permlabels))\n elif isinstance(method, types.FunctionType):\n t = method(data, labels)\n tstat = t.copy()\n u = np.zeros([numbact, numperm])\n for cperm in range(numperm):\n rlabels = np.random.permutation(labels)\n rt = method(data, rlabels)\n u[:, cperm] = rt\n else:\n print('unsupported method %s' % method)\n return (None, None)\n for crow in range(numbact):\n closepos = np.isclose(t[crow], u[crow, :])\n u[crow, closepos] = t[crow]\n pvals = np.zeros([numbact])\n pvals_u = np.zeros([numbact, numperm])\n for crow in range(numbact):\n allstat = np.hstack([t[crow], u[crow, :]])\n allstat = 1 - sp.stats.rankdata(allstat, method='min') / len(allstat)\n pvals[crow] = allstat[0]\n pvals_u[crow, :] = allstat[1:]\n if fdrmethod == 'dsfdr':\n sortp = list(set(pvals))\n sortp = np.sort(sortp)\n sortp = sortp[::-1]\n foundit = False\n allfdr = []\n allt = []\n for cp in sortp:\n realnum = np.sum(pvals <= cp)\n fdr = (realnum + np.count_nonzero(pvals_u <= cp)) / (realnum * (numperm + 1))\n allfdr.append(fdr)\n allt.append(cp)\n if fdr <= alpha:\n realcp = cp\n foundit = True\n break\n if not foundit:\n reject = np.repeat([False], numbact)\n return (reject, tstat, pvals)\n reject = np.zeros(numbact, dtype=int)\n reject = pvals <= realcp\n elif fdrmethod == 'bhfdr' or fdrmethod == 'filterBH':\n t_star = np.array([t] * numperm).transpose()\n pvals = (np.sum(u >= t_star, axis=1) + 1) / (numperm + 1)\n reject = statsmodels.sandbox.stats.multicomp.multipletests(pvals, alpha=alpha, method='fdr_bh')[0]\n elif fdrmethod == 'byfdr':\n t_star = np.array([t] * numperm).transpose()\n pvals = (np.sum(u >= t_star, axis=1) + 1) / (numperm + 1)\n reject = statsmodels.sandbox.stats.multicomp.multipletests(pvals, alpha=alpha, method='fdr_by')[0]\n else:\n raise ValueError('fdr method %s not supported' % fdrmethod)\n return (reject, tstat, pvals)", "context": "def dsfdr(data, labels, transformtype='rankdata', method='meandiff', alpha=0.1, numperm=1000, fdrmethod='dsfdr'): ...\ndef dsfdr(data, labels, transformtype='rankdata', method='meandiff', alpha=0.1, numperm=1000, fdrmethod='dsfdr'): ...\n", "repository": "serenejiang/CodeReview_DSFDR", "test_name": "test_dsfdr", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001021.py"} {"focal_file": "statistics.py", "focal_class": null, "focal_method": "meandiff", "tests": "import unittest\n\nclass Test_meandiff(unittest.TestCase):\n def test_meandiff(self):\n res = statistics.meandiff(self.data, self.labels)\n self.assertEqual(len(res), self.data.shape[0])\n self.assertEqual(res[0], -30.25)\n self.assertEqual(res[1], 0)\n self.assertEqual(res[2], -0.75)\n", "method_code": "def meandiff(data, labels):\n mean0 = np.mean(data[:, labels == 0], axis=1)\n mean1 = np.mean(data[:, labels == 1], axis=1)\n tstat = mean1 - mean0\n return tstat", "context": "def meandiff(data, labels): ...\ndef meandiff(data, labels): ...\ndef stdmeandiff(data, labels): ...\ndef mannwhitney(data, labels): ...\ndef kruwallis(data, labels): ...\ndef pearson(data, labels): ...\ndef spearman(data, labels): ...\n", "repository": "serenejiang/CodeReview_DSFDR", "test_name": "test_meandiff", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001022.py"} {"focal_file": "statistics.py", "focal_class": null, "focal_method": "stdmeandiff", "tests": "import unittest\n\nclass Test_stdmeandiff(unittest.TestCase):\n def test_stdmeandiff(self):\n res = statistics.stdmeandiff(self.data, self.labels)\n self.assertEqual(len(res), self.data.shape[0])\n npt.assert_almost_equal(res[0], -1.57, decimal=2)\n self.assertEqual(res[1], 0)\n npt.assert_almost_equal(res[2], -0.39, decimal=2)\n", "method_code": "def stdmeandiff(data, labels):\n mean0 = np.mean(data[:, labels == 0], axis=1)\n mean1 = np.mean(data[:, labels == 1], axis=1)\n sd0 = np.std(data[:, labels == 0], axis=1, ddof=1)\n sd1 = np.std(data[:, labels == 1], axis=1, ddof=1)\n tstat = (mean1 - mean0) / (sd1 + sd0)\n return tstat", "context": "def stdmeandiff(data, labels): ...\ndef meandiff(data, labels): ...\ndef stdmeandiff(data, labels): ...\ndef mannwhitney(data, labels): ...\ndef kruwallis(data, labels): ...\ndef pearson(data, labels): ...\ndef spearman(data, labels): ...\n", "repository": "serenejiang/CodeReview_DSFDR", "test_name": "test_stdmeandiff", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001023.py"} {"focal_file": "statistics.py", "focal_class": null, "focal_method": "mannwhitney", "tests": "import unittest\n\nclass Test_mannwhitney(unittest.TestCase):\n def test_mannwhitney(self):\n res = statistics.mannwhitney(self.data, self.labels)\n self.assertEqual(len(res), self.data.shape[0])\n self.assertEqual(res[0], 0)\n self.assertEqual(res[1], 8)\n self.assertEqual(res[2], 5.5)\n", "method_code": "def mannwhitney(data, labels):\n group0 = data[:, labels == 0]\n group1 = data[:, labels == 1]\n tstat = np.array([scipy.stats.mannwhitneyu(group0[i, :], group1[i, :]).statistic for i in range(np.shape(data)[0])])\n return tstat", "context": "def mannwhitney(data, labels): ...\ndef meandiff(data, labels): ...\ndef stdmeandiff(data, labels): ...\ndef mannwhitney(data, labels): ...\ndef kruwallis(data, labels): ...\ndef pearson(data, labels): ...\ndef spearman(data, labels): ...\n", "repository": "serenejiang/CodeReview_DSFDR", "test_name": "test_mannwhitney", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001024.py"} {"focal_file": "statistics.py", "focal_class": null, "focal_method": "kruwallis", "tests": "import unittest\n\nclass Test_kruwallis(unittest.TestCase):\n def test_kruwallis(self):\n res = statistics.kruwallis(self.data2, self.labels2)\n self.assertEqual(len(res), self.data.shape[0])\n npt.assert_almost_equal(res[0], 6.58, decimal=2)\n self.assertEqual(res[1], 0)\n npt.assert_almost_equal(res[2], 2.55, decimal=2)\n", "method_code": "def kruwallis(data, labels):\n n = len(np.unique(labels))\n allt = []\n for cbact in range(np.shape(data)[0]):\n group = []\n for j in range(n):\n group.append(data[cbact, labels == j])\n tstat = scipy.stats.kruskal(*group).statistic\n allt.append(tstat)\n return allt", "context": "def kruwallis(data, labels): ...\ndef meandiff(data, labels): ...\ndef stdmeandiff(data, labels): ...\ndef mannwhitney(data, labels): ...\ndef kruwallis(data, labels): ...\ndef pearson(data, labels): ...\ndef spearman(data, labels): ...\n", "repository": "serenejiang/CodeReview_DSFDR", "test_name": "test_kruwallis", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001025.py"} {"focal_file": "pymdl2001/demo/demo_module.py", "focal_class": null, "focal_method": "demo", "tests": "import unittest\n\nclass Test_demo(unittest.TestCase):\n def test_demo(self):\n TestCase.assertEqual(self, 2, 2, '这里的单元测试不通过')\n TestCase.assertEqual(self, 2, 2)\n TestCase.assertEqual(self, demo.start(), None)\n TestCase.assertEqual(self, DemoClass.demo(self.demo), 'Hello world.\\nHello Demo.')\n TestCase.assertEqual(self, DemoClass.demo(self.demo), 'Hello world.\\nHello Demo.')\n", "method_code": " def demo(self):\n \"\"\"函数样例\n 和Java不同的是,这里的函数说明写在函数体里面\n :return: 一条hello字符串\n \"\"\"\n statement_hello = 'Hello world.\\nHello Demo.'\n return statement_hello\n ", "context": "class DemoClass():\n def demo(self): ...\n def demo_add(self, a, b): ...\n", "repository": "0jiejie0/sum", "test_name": "test_demo", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001026.py"} {"focal_file": "pymdl2001/demo/demo_module.py", "focal_class": null, "focal_method": "demo_add", "tests": "import unittest\n\nclass Test_demo_add(unittest.TestCase):\n def test_demo_add(self):\n TestCase.assertEqual(self, DemoClass.demo_add(self.demo, 1, 3), 4)\n", "method_code": " def demo_add(self, a, b):\n return a + b\n ", "context": "class DemoClass():\n def demo_add(self, a, b): ...\n def demo(self): ...\n", "repository": "0jiejie0/sum", "test_name": "test_demo_add", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001027.py"} {"focal_file": "tornado_aws/client.py", "focal_class": null, "focal_method": "_parse_awz_error", "tests": "import unittest\n\nclass Test_parse_awz_error(unittest.TestCase):\n def test_awz_error(self):\n content = b'{\"__type\": \"MissingAuthenticationTokenException\", \"message\": \"Missing Authentication Token\"}'\n expectation = {'__type': 'MissingAuthenticationTokenException', 'message': 'Missing Authentication Token'}\n with self.client_with_default_creds('s3') as obj:\n self.assertDictEqual(obj._parse_awz_error(content), expectation)\n", "method_code": " def _parse_awz_error(content):\n \"\"\"Returns the AWZ error parsed out of the HTTPError that was raised.\n \n :param bytes content: The response error content\n :rtype: dict|None\n \n \"\"\"\n payload = json.loads(content.decode('utf-8'))\n if isinstance(payload, dict) and '__type' in payload:\n if '#' in payload['__type']:\n payload['__type'] = payload['__type'][payload['__type'].index('#') + 1:]\n return payload\n ", "context": "class AWSClient(object):\n @staticmethod\n def _parse_awz_error(content): ...\n def __init__(self, service, profile=None, region=None, access_key=None, secret_key=None, security_token=None, endpoint=None): ...\n def fetch(self, method, path='/', query_args=None, headers=None, body=b'', recursed=False): ...\n def close(self): ...\n def _process_error(self, error): ...\n def _aws_error_from_xml(error): ...\n def _awz_response(response): ...\n def _parse_xml_error(content): ...\n def _auth_header(self, amz_date, date_stamp, request_hash, signed_headers): ...\n def _create_request(self, method, path='/', query_args=None, headers=None, body=b''): ...\n def _endpoint(self, endpoint): ...\n def _get_client_adapter(self): ...\n def _hostname(url): ...\n def _quote(value): ...\n def _sign(key, msg): ...\n def _signed_request(self, method, path, query_args, headers, body): ...\n def _query_string(self, query_args): ...\n def _signature(self, amz_date, date_stamp, request_hash): ...\n def _signed_headers(headers): ...\n def _signing_key(self, date_stamp): ...\n\n self._client = self._get_client_adapter()\n self._service = service\n self._profile = profile or os.getenv('AWS_DEFAULT_PROFILE', 'default')\n self._region = region or config.get_region(self._profile)\n self._auth_config = config.Authorization(self._profile, access_key, secret_key, security_token, self._client)\n self._endpoint_url = self._endpoint(endpoint)\n self._host = self._hostname(self._endpoint_url)\n\n ALGORITHM = 'AWS4-HMAC-SHA256'\n ASYNC = False\n CONNECT_TIMEOUT = 10\n REQUEST_TIMEOUT = 30\n SCHEME = 'https'\n", "repository": "gmr/tornado-aws", "test_name": "test_awz_error", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001028.py"} {"focal_file": "tornado_aws/client.py", "focal_class": null, "focal_method": "_parse_xml_error", "tests": "import unittest\n\nclass Test_parse_xml_error(unittest.TestCase):\n def test_simpledb_error(self):\n content = b'Missing Authentication Token'\n expectation = {'Code': 'MissingAuthenticationTokenException', 'Message': 'Missing Authentication Token'}\n with self.client_with_default_creds('simpledb') as obj:\n self.assertDictEqual(obj._parse_xml_error(content), expectation)\n\n def test_unparsable_error(self):\n content = b'error'\n with self.client_with_default_creds('invalid') as obj:\n with self.assertRaises(ValueError):\n obj._parse_xml_error(content)\n", "method_code": " def _parse_xml_error(content):\n \"\"\"Returns the XML error parsed out of the HTTPError that was raised.\n \n :param bytes content: The response error content\n :rtype: dict\n :raises: ValueError\n \n \"\"\"\n payload = txml.loads(content.decode('utf-8'))\n if 'Error' in payload:\n return payload['Error']\n elif 'Errors' in payload and 'Error' in payload['Errors']:\n return payload['Errors']['Error']\n elif 'Response' in payload and 'Errors' in payload['Response'] and ('Error' in payload['Response']['Errors']):\n payload['Response']['Errors']['Error']['RequestId'] = payload['Response'].get('RequestID')\n return payload['Response']['Errors']['Error']\n key = tuple(payload.keys())[0]\n if 'Message' in payload[key]:\n return {'Code': key, 'Message': payload[key]['Message']}\n raise ValueError\n ", "context": "class AWSClient(object):\n @staticmethod\n def _parse_xml_error(content): ...\n def __init__(self, service, profile=None, region=None, access_key=None, secret_key=None, security_token=None, endpoint=None): ...\n def fetch(self, method, path='/', query_args=None, headers=None, body=b'', recursed=False): ...\n def close(self): ...\n def _process_error(self, error): ...\n def _aws_error_from_xml(error): ...\n def _awz_response(response): ...\n def _parse_awz_error(content): ...\n def _auth_header(self, amz_date, date_stamp, request_hash, signed_headers): ...\n def _create_request(self, method, path='/', query_args=None, headers=None, body=b''): ...\n def _endpoint(self, endpoint): ...\n def _get_client_adapter(self): ...\n def _hostname(url): ...\n def _quote(value): ...\n def _sign(key, msg): ...\n def _signed_request(self, method, path, query_args, headers, body): ...\n def _query_string(self, query_args): ...\n def _signature(self, amz_date, date_stamp, request_hash): ...\n def _signed_headers(headers): ...\n def _signing_key(self, date_stamp): ...\n\n self._client = self._get_client_adapter()\n self._service = service\n self._profile = profile or os.getenv('AWS_DEFAULT_PROFILE', 'default')\n self._region = region or config.get_region(self._profile)\n self._auth_config = config.Authorization(self._profile, access_key, secret_key, security_token, self._client)\n self._endpoint_url = self._endpoint(endpoint)\n self._host = self._hostname(self._endpoint_url)\n\n ALGORITHM = 'AWS4-HMAC-SHA256'\n ASYNC = False\n CONNECT_TIMEOUT = 10\n REQUEST_TIMEOUT = 30\n SCHEME = 'https'\n", "repository": "gmr/tornado-aws", "test_name": "test_simpledb_error", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001029.py"} {"focal_file": "tornado_aws/client.py", "focal_class": null, "focal_method": "_process_error", "tests": "import unittest\n\nclass Test_process_error(unittest.TestCase):\n def test_process_error_awz_creds(self):\n content = b'{\"__type\": \"MissingAuthenticationTokenException\", \"message\": \"Missing Authentication Token\"}'\n stream = io.BytesIO(content)\n request = httpclient.HTTPRequest('/test')\n headers = httputil.HTTPHeaders({'Content-Type': 'application/x-amz-json-1.1', 'Server': 'Server', 'X-Amz-Request-Id': '3840c615-0503-4a53-a2f6-07afa795a5d6', 'Date': 'Tue, 06 Jun 2017 18:31:47 GMT'})\n response = httpclient.HTTPResponse(request, 400, headers, stream)\n error = httpclient.HTTPError(400, 'Bad Request', response)\n with self.client_with_default_creds('dynamodb') as obj:\n result = obj._process_error(error)\n self.assertTrue(result[0])\n\n def test_process_dynamodb_error_creds(self):\n content = b'{\"__type\": \"com.amazonaws.dynamodb.v20120810#MissingAuthenticationTokenException\", \"message\": \"Missing Authentication Token\"}'\n stream = io.BytesIO(content)\n request = httpclient.HTTPRequest('/test')\n headers = httputil.HTTPHeaders({'Content-Type': 'application/x-amz-json-1.0', 'Server': 'Server', 'X-Amz-Request-Id': '3840c615-0503-4a53-a2f6-07afa795a5d6', 'Date': 'Tue, 06 Jun 2017 18:31:47 GMT'})\n response = httpclient.HTTPResponse(request, 400, headers, stream)\n error = httpclient.HTTPError(400, 'Bad Request', response)\n with self.client_with_default_creds('dynamodb') as obj:\n result = obj._process_error(error)\n self.assertTrue(result[0])\n self.assertIsInstance(result[1], exceptions.AWSError)\n\n def test_process_error_s3(self):\n content = b'\\nExpiredTokenThe provided token has expired.DA1C5F526B1A0EF2381a948d-a988-4e7a-aefe-e27e82555bed'\n stream = io.BytesIO(content)\n request = httpclient.HTTPRequest('/')\n headers = httputil.HTTPHeaders({'Content-Type': 'application/xml', 'Server': 'Server', 'X-Amz-Request-Id': '3840c615-0503-4a53-a2f6-07afa795a5d6', 'Date': 'Tue, 06 Jun 2017 18:31:47 GMT'})\n response = httpclient.HTTPResponse(request, 400, headers, stream)\n error = httpclient.HTTPError(400, 'Bad Request', response)\n with self.client_with_default_creds('s3') as obj:\n result = obj._process_error(error)\n self.assertTrue(result[0])\n self.assertIsInstance(result[1], exceptions.AWSError)\n\n def test_process_error_ec2_non_auth(self):\n content = b'InvalidActionThe action CreateVolume is not valid for this web service.cb159b66-84a7-43bf-8a02-c839cc50b164'\n stream = io.BytesIO(content)\n request = httpclient.HTTPRequest('/')\n headers = httputil.HTTPHeaders({'Content-Type': 'application/xml', 'Server': 'Server', 'X-Amz-Request-Id': '3840c615-0503-4a53-a2f6-07afa795a5d6', 'Date': 'Tue, 06 Jun 2017 18:31:47 GMT'})\n response = httpclient.HTTPResponse(request, 400, headers, stream)\n error = httpclient.HTTPError(400, 'Bad Request', response)\n with self.client_with_default_creds('dynamodb') as obj:\n result = obj._process_error(error)\n self.assertFalse(result[0])\n self.assertIsInstance(result[1], exceptions.AWSError)\n", "method_code": " def _process_error(self, error):\n \"\"\"Attempt to process the error coming from AWS. Returns ``True``\n if the client should attempt to fetch credentials and the AWSError\n exception to raise if the client did not have an authentication error.\n \n :param tornado.httpclient.HTTPError error: The HTTP error\n :rtype: (tuple, tornado_aws.exceptions.AWSError)\n \n \"\"\"\n LOGGER.error('Error: %r', error)\n if error.code == 599:\n return (False, None)\n elif error.code == 400 and self._awz_response(error.response):\n awz_error = self._parse_awz_error(error.response.body)\n return (awz_error and awz_error['__type'] in _REFRESH_EXCEPTIONS, exceptions.AWSError(type=awz_error['__type'], message=awz_error.get('message', '(null)')))\n try:\n xml_error = self._parse_xml_error(error.response.body)\n except ValueError:\n LOGGER.debug('Could not fallback to XML: %r', error)\n return (False, None)\n return (xml_error and xml_error['Code'] in _REFRESH_XML_EXCEPTIONS, self._aws_error_from_xml(xml_error))\n ", "context": "class AWSClient(object):\n def _process_error(self, error): ...\n def __init__(self, service, profile=None, region=None, access_key=None, secret_key=None, security_token=None, endpoint=None): ...\n def fetch(self, method, path='/', query_args=None, headers=None, body=b'', recursed=False): ...\n def close(self): ...\n def _aws_error_from_xml(error): ...\n def _awz_response(response): ...\n def _parse_awz_error(content): ...\n def _parse_xml_error(content): ...\n def _auth_header(self, amz_date, date_stamp, request_hash, signed_headers): ...\n def _create_request(self, method, path='/', query_args=None, headers=None, body=b''): ...\n def _endpoint(self, endpoint): ...\n def _get_client_adapter(self): ...\n def _hostname(url): ...\n def _quote(value): ...\n def _sign(key, msg): ...\n def _signed_request(self, method, path, query_args, headers, body): ...\n def _query_string(self, query_args): ...\n def _signature(self, amz_date, date_stamp, request_hash): ...\n def _signed_headers(headers): ...\n def _signing_key(self, date_stamp): ...\n\n self._client = self._get_client_adapter()\n self._service = service\n self._profile = profile or os.getenv('AWS_DEFAULT_PROFILE', 'default')\n self._region = region or config.get_region(self._profile)\n self._auth_config = config.Authorization(self._profile, access_key, secret_key, security_token, self._client)\n self._endpoint_url = self._endpoint(endpoint)\n self._host = self._hostname(self._endpoint_url)\n\n ALGORITHM = 'AWS4-HMAC-SHA256'\n ASYNC = False\n CONNECT_TIMEOUT = 10\n REQUEST_TIMEOUT = 30\n SCHEME = 'https'\n", "repository": "gmr/tornado-aws", "test_name": "test_process_error_awz_creds", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001030.py"} {"focal_file": "tornado_aws/config.py", "focal_class": null, "focal_method": "_parse_file", "tests": "import unittest\n\nclass Test_parse_file(unittest.TestCase):\n def test_parsing_file(self):\n expectation = {'section a': {'key-1': uuid.uuid4().hex, 'key-2': uuid.uuid4().hex}, 'section b': {'key-a': uuid.uuid4().hex, 'key-b': uuid.uuid4().hex}}\n with tempfile.NamedTemporaryFile() as handle:\n handle.write(utils.build_ini(expectation))\n handle.flush()\n value = config._parse_file(handle.name)\n self.assertDictEqual(expectation, value)\n", "method_code": "def _parse_file(file_path):\n \"\"\"Parse the specified configuration file, returning a nested dict\n of key/value pairs by section.\n\n :param str file_path: The path of the file to read.\n :rtype: dict\n\n \"\"\"\n file_path = path.abspath(path.expanduser(path.expandvars(file_path)))\n LOGGER.debug('Attempting to load credentials from %s', file_path)\n if not path.exists(file_path):\n raise exceptions.ConfigNotFound(path=file_path)\n parser = configparser.RawConfigParser()\n try:\n parser.read(file_path)\n except configparser.Error as error:\n LOGGER.error('Error reading file: %s', error)\n raise exceptions.ConfigParserError(path=file_path)\n config = {}\n for section in parser.sections():\n config[section] = {}\n for option in parser.options(section):\n config[section][option] = parser.get(section, option)\n return config", "context": "def _parse_file(file_path): ...\ndef get_region(profile): ...\ndef _is_async_client(client): ...\ndef _parse_file(file_path): ...\ndef _request_region_from_instance(): ...\n", "repository": "gmr/tornado-aws", "test_name": "test_parsing_file", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001031.py"} {"focal_file": "tornado_aws/config.py", "focal_class": "tornado_aws.config.Authorization", "focal_method": "reset", "tests": "import unittest\n\nclass Test_tornado_aws_config_Authorization_reset(unittest.TestCase):\n def test_assignment_and_reset(self):\n obj = config.Authorization('default', client=httpclient.HTTPClient())\n access_key = uuid.uuid4().hex\n secret_key = uuid.uuid4().hex\n token = uuid.uuid4().hex\n expiration = datetime.datetime.now().isoformat()\n obj._assign_credentials({'AccessKeyId': access_key, 'SecretAccessKey': secret_key, 'Expiration': expiration, 'Token': token})\n self.assertEqual(obj.access_key, access_key)\n self.assertEqual(obj.secret_key, secret_key)\n self.assertEqual(obj._expiration, expiration)\n self.assertEqual(obj.security_token, token)\n obj.reset()\n self.assertIsNone(obj.access_key)\n self.assertIsNone(obj.secret_key)\n self.assertIsNone(obj._expiration)\n self.assertIsNone(obj.security_token)\n", "method_code": " def reset(self):\n \"\"\"Reset the security credentials.\n \n :raises: tornado_aws.exceptions.LocalCredentialsError()\n \n \"\"\"\n self._access_key = None\n self._secret_key = None\n self._expiration = None\n self._security_token = None\n ", "context": "class Authorization(object):\n def reset(self): ...\n def __init__(self, profile, access_key=None, secret_key=None, security_token=None, client=None): ...\n def access_key(self): ...\n def local_credentials(self): ...\n def secret_key(self): ...\n def security_token(self): ...\n def needs_credentials(self): ...\n def refresh(self): ...\n def _assign_credentials(self, data): ...\n def _fetch_credentials(self): ...\n def _fetch_credentials_async(self): ...\n def _future_exception(inner, outer): ...\n def _get_config_value(self, config, key): ...\n def _get_instance_credentials(self, role): ...\n def _get_instance_credentials_async(self, role): ...\n def _get_role(self): ...\n def _get_role_async(self): ...\n def _resolve_credentials(self, access_key=None, secret_key=None, security_token=None): ...\n def _resolve_config_file_credentials(self): ...\n\n self._client = client\n self._profile = profile\n self._local_credentials = False\n self._access_key = None\n self._secret_key = None\n self._security_token = None\n self._expiration = None\n self._is_async = _is_async_client(client)\n self._ioloop = ioloop.IOLoop.current() if self._is_async else None\n", "repository": "gmr/tornado-aws", "test_name": "test_assignment_and_reset", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001032.py"} {"focal_file": "src/pages/FunnelsPO.py", "focal_class": null, "focal_method": "funnel_signup", "tests": "import unittest\n\nclass Test_funnel_signup(unittest.TestCase):\n @unittest.skip('Debug mode')\n def test_buy_now_funnel_signup(self):\n self.workflow.funnel_signup(cn='United States', sn='California', ptype=5, route='/buy-now/fax-numbers')\n self.workflow.populate_email_element('/buy-now/account-setup')\n self.workflow.populate_billing_elements('United States', 'California', '/Buy-Now/Billing-Info')\n\n def test_free_trial_funnel_signup(self):\n self.workflow.funnel_signup(cn='United States', sn='California', route='/free-trial/fax-numbers')\n self.workflow.populate_email_element(route='/free-trial/account-setup')\n self.workflow.populate_billing_elements(cn='United States', sn='California', route='/free-trial/Billing-Info')\n", "method_code": " def funnel_signup(self, cn, sn=None, ptype=None, route=None):\n self.driver.get(self.base_url + route)\n country = self.driver.find_element(*Fl.COUNTRYDDL)\n state = self.driver.find_element(*Fl.STATEDDL)\n areacode = self.driver.find_element(*Fl.AREACODEDDL)\n country_sel = Sel(country)\n state_sel = Sel(state)\n areacode_sel = Sel(areacode)\n country_sel.select_by_visible_text(cn)\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'numberchooser-state')))\n if sn is None:\n state_count = state_sel.options\n state_sel.select_by_index(rn.randint(3, len(state_count) - 1))\n else:\n state_sel.select_by_visible_text(sn)\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'numberchooser-city')))\n area_count = areacode_sel.options\n areacode_sel.select_by_index(rn.randint(3, len(area_count) - 1))\n if ptype == 1:\n emonth = self.driver.find_element(*Fl.ESSENTIAL_MONTH_RDIO)\n self.wait.until(EC.element_to_be_clickable((By.ID, 'essential-month')))\n emonth.click()\n nextb = self.driver.find_element(*Fl.ESSENTIAL_NEXT_BTN)\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btnessential')))\n elif ptype == 2:\n eyear = self.driver.find_element(*Fl.ESSENTIAL_ANNUAL_RDIO)\n self.wait.until(EC.element_to_be_clickable((By.ID, 'essential-year')))\n eyear.click()\n nextb = self.driver.find_element(*Fl.ESSENTIAL_NEXT_BTN)\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btnessential')))\n elif ptype == 3:\n vmonth = self.driver.find_element(*Fl.VALUE_MONTH_RDIO)\n self.wait.until(EC.element_to_be_clickable((By.ID, 'value-month')))\n vmonth.click()\n nextb = self.driver.find_element(*Fl.VALUE_NEXT_BTN)\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btnvalue')))\n elif ptype == 4:\n vyear = self.driver.find_element(*Fl.VALUE_ANNAUL_RDIO)\n self.wait.until(EC.element_to_be_clickable((By.ID, 'value-year')))\n vyear.click()\n nextb = self.driver.find_element(*Fl.VALUE_NEXT_BTN)\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btnvalue')))\n elif ptype == 5:\n pmonth = self.driver.find_element(*Fl.PRO_MONTH_RDIO)\n self.wait.until(EC.element_to_be_clickable((By.ID, 'professional-month')))\n pmonth.click()\n nextb = self.driver.find_element(*Fl.PRO_NEXT_BTN)\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btnprofessional')))\n elif ptype == 6:\n pyear = self.driver.find_element(*Fl.PRO_ANNUAL_RDIO)\n self.wait.until(EC.element_to_be_clickable((By.ID, 'professional-year')))\n pyear.click()\n nextb = self.driver.find_element(*Fl.PRO_NEXT_BTN)\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btnprofessional')))\n else:\n pass\n try:\n nextb.click()\n except UnboundLocalError as e:\n self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'agreement')))\n nextb = self.driver.find_element(*Fl.BILL_NEXT_BTN)\n nextb.click()\n ", "context": "class FunnelPageObjects(BasePageElement):\n def funnel_signup(self, cn, sn=None, ptype=None, route=None): ...\n def __init__(self, driver, base_url): ...\n def populate_email_element(self, route=None): ...\n def populate_billing_elements(self, cn, sn, ctype='visa16', route=None): ...\n def assert_success_elements(self): ...\n\n self.base_url = base_url\n self.driver = driver\n self.f = Factory.create()\n self.wait = WebDriverWait(self.driver, 100)\n", "repository": "copyleftdev/MFUN", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001033.py"} {"focal_file": "enczipstream/__init__.py", "focal_class": "enczipstream.ZipFile", "focal_method": "write_iter", "tests": "import unittest\n\nclass Test_enczipstream_ZipFile_write_iter(unittest.TestCase):\n def test_write_iterable(self):\n z = enczipstream.ZipFile(mode='w')\n\n def string_generator():\n for _ in range(10):\n yield b'enczipstream\\x01\\n'\n data = [string_generator(), string_generator()]\n for i, d in enumerate(data):\n z.write_iter(iterable=d, arcname='data_{0}'.format(i))\n f = tempfile.NamedTemporaryFile(suffix='zip', delete=False)\n for chunk in z:\n f.write(chunk)\n f.close()\n z2 = zipfile.ZipFile(f.name, 'r')\n self.assertFalse(z2.testzip())\n os.remove(f.name)\n\n def test_write_iterable_pwd(self):\n z = enczipstream.ZipFile(mode='w', pwd=self.password)\n\n def string_generator():\n for _ in range(10):\n yield b'enczipstream\\x01\\n'\n data = [string_generator(), string_generator()]\n for i, d in enumerate(data):\n z.write_iter(iterable=d, arcname='data_{0}'.format(i))\n f = tempfile.NamedTemporaryFile(suffix='zip', delete=False)\n for chunk in z:\n f.write(chunk)\n f.close()\n z2 = zipfile.ZipFile(f.name, 'r')\n z2.setpassword(self.password)\n self.assertFalse(z2.testzip())\n os.remove(f.name)\n", "method_code": " def write_iter(self, arcname, iterable, compress_type=None):\n \"\"\"Write the bytes iterable `iterable` to the archive under the name `arcname`.\"\"\"\n kwargs = {'arcname': arcname, 'iterable': iterable, 'compress_type': compress_type}\n self.paths_to_write.append(kwargs)\n ", "context": "class ZipFile(zipfile.ZipFile):\n def write_iter(self, arcname, iterable, compress_type=None): ...\n def __init__(self, fileobj=None, mode='w', compression=ZIP_STORED, allowZip64=False, pwd=None): ...\n def __iter__(self): ...\n def __enter__(self): ...\n def __exit__(self, type, value, traceback): ...\n def comment(self): ...\n def comment(self, comment): ...\n def write(self, filename, arcname=None, compress_type=None): ...\n def writestr(self, arcname, data, compress_type=None): ...\n def __write(self, filename=None, iterable=None, arcname=None, compress_type=None, pwd=None): ...\n def __close(self): ...\n\n self._comment = b''\n self.paths_to_write = []\n self.pwd = pwd\n", "repository": "quarkslab/python-zipstream", "test_name": "test_write_iterable", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001034.py"} {"focal_file": "enczipstream/__init__.py", "focal_class": "enczipstream.ZipFile", "focal_method": "writestr", "tests": "import unittest\n\nclass Test_enczipstream_ZipFile_writestr(unittest.TestCase):\n def test_writestr(self):\n z = enczipstream.ZipFile(mode='w')\n with open(SAMPLE_FILE_RTF, 'rb') as fp:\n z.writestr('sample.rtf', fp.read())\n f = tempfile.NamedTemporaryFile(suffix='zip', delete=False)\n for chunk in z:\n f.write(chunk)\n f.close()\n z2 = zipfile.ZipFile(f.name, 'r')\n self.assertFalse(z2.testzip())\n os.remove(f.name)\n\n def test_writestr_pwd(self):\n z = enczipstream.ZipFile(mode='w', pwd=self.password)\n with open(SAMPLE_FILE_RTF, 'rb') as fp:\n z.writestr('sample.rtf', fp.read())\n f = tempfile.NamedTemporaryFile(suffix='zip', delete=False)\n for chunk in z:\n f.write(chunk)\n f.close()\n z2 = zipfile.ZipFile(f.name, 'r')\n z2.setpassword(self.password)\n self.assertFalse(z2.testzip())\n os.remove(f.name)\n", "method_code": " def writestr(self, arcname, data, compress_type=None):\n \"\"\"\n Writes a str into ZipFile by wrapping data as a generator\n \"\"\"\n \n def _iterable():\n yield data\n return self.write_iter(arcname, _iterable(), compress_type=compress_type)\n ", "context": "class ZipFile(zipfile.ZipFile):\n def writestr(self, arcname, data, compress_type=None): ...\n def __init__(self, fileobj=None, mode='w', compression=ZIP_STORED, allowZip64=False, pwd=None): ...\n def __iter__(self): ...\n def __enter__(self): ...\n def __exit__(self, type, value, traceback): ...\n def comment(self): ...\n def comment(self, comment): ...\n def write(self, filename, arcname=None, compress_type=None): ...\n def write_iter(self, arcname, iterable, compress_type=None): ...\n def __write(self, filename=None, iterable=None, arcname=None, compress_type=None, pwd=None): ...\n def __close(self): ...\n\n self._comment = b''\n self.paths_to_write = []\n self.pwd = pwd\n", "repository": "quarkslab/python-zipstream", "test_name": "test_writestr", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001035.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "merge_with", "tests": "import unittest\n\nclass Test_merge_with(unittest.TestCase):\n def test_merge_with_none(self):\n \"\"\"\n this method should just request a parameter.\n leaving this test there to document this behaviour, but\n it's going to change (very) soon.\n \"\"\"\n try:\n self.assertRaises(AttributeError, lambda: self.parameter_fc.merge_with())\n except:\n self.assertTrue(False)\n\n def test_merge_parameter_with_empty(self):\n self.parameter_fc.merge_with(self.default_fc)\n self.assertEqual(self.parameter_fc.config, self.parameters)\n", "method_code": " def merge_with(self, father_obj=None):\n self.__dict__ = dict(list(father_obj.config.items()) + list(self.config.items()))\n ", "context": "class FolderConfig(object):\n def merge_with(self, father_obj=None): ...\n def __init__(self, dict_config=None): ...\n def config(self): ...\n def __getitem__(self, attr_name): ...\n def __str__(self): ...\n def __repr__(self): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_merge_with_none", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001036.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "excluded_folders", "tests": "import unittest\n\nclass Test_excluded_folders(unittest.TestCase):\n def test_excluded_folders(self):\n self.assertEqual(self.defConf.excluded_folders(''), [])\n", "method_code": " def excluded_folders(self, path=''):\n try:\n return self._get_obj_from_path(path)['excluded_folders']\n except KeyError:\n return list()\n ", "context": "class ConfigHandler(object):\n def excluded_folders(self, path=''): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_files(self, path=''): ...\n def excluded_file_formats(self, filename): ...\n def _get_obj_from_path(self, path): ...\n def title(self, path): ...\n def cover_image_name(self, path): ...\n def thumbnail_size(self, path): ...\n def cover_size(self, path): ...\n def image_prefix_path(self, path): ...\n def regenerate_thumbnails(self): ...\n def template_path(self, path): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_excluded_folders", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001037.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "excluded_file_formats", "tests": "import unittest\n\nclass Test_excluded_file_formats(unittest.TestCase):\n def test_excluded_file_formats(self):\n self.assertRaises(KeyError, lambda: self.defConf.excluded_file_formats('madalby.jpg'))\n self.assertRaises(KeyError, lambda: self.defConf.excluded_file_formats(''))\n", "method_code": " def excluded_file_formats(self, filename):\n return any(map(lambda regex_format: re.match(regex_format, filename), self.config['excluded_file_formats']))\n ", "context": "class ConfigHandler(object):\n def excluded_file_formats(self, filename): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_folders(self, path=''): ...\n def excluded_files(self, path=''): ...\n def _get_obj_from_path(self, path): ...\n def title(self, path): ...\n def cover_image_name(self, path): ...\n def thumbnail_size(self, path): ...\n def cover_size(self, path): ...\n def image_prefix_path(self, path): ...\n def regenerate_thumbnails(self): ...\n def template_path(self, path): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_excluded_file_formats", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001038.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "_get_obj_from_path", "tests": "import unittest\n\nclass Test_get_obj_from_path(unittest.TestCase):\n def test_get_obj_from_path(self):\n \"\"\"\n ConfigHandler._get_obj_from_path is an internal function.\n Testing it here, but client code should not use this directly.\n B\n \"\"\"\n self.assertRaises(KeyError, lambda: self.defConf._get_obj_from_path('anime/yahari'))\n", "method_code": " def _get_obj_from_path(self, path):\n \"\"\"\n Internal\n \"\"\"\n path = path.replace(os.path.abspath(self.starting_path), '')\n obj_from_path = self.config.config\n try:\n for subpath in filter(bool, path.split(os.path.sep)):\n obj_from_path = obj_from_path['paths'][subpath]\n except KeyError:\n logging.debug('[warning] got an error while retrieving the object, path: {0}'.format(path))\n obj_from_path = dict()\n return obj_from_path\n ", "context": "class ConfigHandler(object):\n def _get_obj_from_path(self, path): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_folders(self, path=''): ...\n def excluded_files(self, path=''): ...\n def excluded_file_formats(self, filename): ...\n def title(self, path): ...\n def cover_image_name(self, path): ...\n def thumbnail_size(self, path): ...\n def cover_size(self, path): ...\n def image_prefix_path(self, path): ...\n def regenerate_thumbnails(self): ...\n def template_path(self, path): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_get_obj_from_path", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001039.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "cover_image_name", "tests": "import unittest\n\nclass Test_cover_image_name(unittest.TestCase):\n def test_cover_image_name(self):\n self.assertEqual(self.defConf.cover_image_name('tv/doctor/tennant'), '')\n", "method_code": " def cover_image_name(self, path):\n try:\n return self._get_obj_from_path(path)['cover_image']\n except KeyError:\n return ''\n ", "context": "class ConfigHandler(object):\n def cover_image_name(self, path): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_folders(self, path=''): ...\n def excluded_files(self, path=''): ...\n def excluded_file_formats(self, filename): ...\n def _get_obj_from_path(self, path): ...\n def title(self, path): ...\n def thumbnail_size(self, path): ...\n def cover_size(self, path): ...\n def image_prefix_path(self, path): ...\n def regenerate_thumbnails(self): ...\n def template_path(self, path): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_cover_image_name", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001040.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "thumbnail_size", "tests": "import unittest\n\nclass Test_thumbnail_size(unittest.TestCase):\n def test_thumbnail_size(self):\n self.assertRaises(KeyError, lambda: self.defConf.thumbnail_size('drawings/doomfest'))\n", "method_code": " def thumbnail_size(self, path):\n try:\n thumb_size_dict = self._get_obj_from_path(path)['thumbnail_size']\n except KeyError:\n thumb_size_dict = self.config['thumbnail_size']\n return (thumb_size_dict['width'], thumb_size_dict['height'])\n ", "context": "class ConfigHandler(object):\n def thumbnail_size(self, path): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_folders(self, path=''): ...\n def excluded_files(self, path=''): ...\n def excluded_file_formats(self, filename): ...\n def _get_obj_from_path(self, path): ...\n def title(self, path): ...\n def cover_image_name(self, path): ...\n def cover_size(self, path): ...\n def image_prefix_path(self, path): ...\n def regenerate_thumbnails(self): ...\n def template_path(self, path): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_thumbnail_size", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001041.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "cover_size", "tests": "import unittest\n\nclass Test_cover_size(unittest.TestCase):\n def test_cover_size(self):\n self.assertRaises(KeyError, lambda: self.defConf.cover_size('drawings/notalfa'))\n", "method_code": " def cover_size(self, path):\n try:\n cover_size_dict = self._get_obj_from_path(path)['cover_size']\n except KeyError:\n cover_size_dict = self.config['cover_size']\n return (cover_size_dict['width'], cover_size_dict['height'])\n ", "context": "class ConfigHandler(object):\n def cover_size(self, path): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_folders(self, path=''): ...\n def excluded_files(self, path=''): ...\n def excluded_file_formats(self, filename): ...\n def _get_obj_from_path(self, path): ...\n def title(self, path): ...\n def cover_image_name(self, path): ...\n def thumbnail_size(self, path): ...\n def image_prefix_path(self, path): ...\n def regenerate_thumbnails(self): ...\n def template_path(self, path): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_cover_size", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001042.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "image_prefix_path", "tests": "import unittest\n\nclass Test_image_prefix_path(unittest.TestCase):\n def test_image_prefix_path(self):\n self.assertEqual(self.defConf.image_prefix_path('drawings/doomfest'), '')\n", "method_code": " def image_prefix_path(self, path):\n \"\"\"\n fool idea: allowing links on other sites.\n it's transparent for the end user.\n \"\"\"\n try:\n return self._get_obj_from_path(path)['fspath']\n except KeyError:\n return ''\n ", "context": "class ConfigHandler(object):\n def image_prefix_path(self, path): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_folders(self, path=''): ...\n def excluded_files(self, path=''): ...\n def excluded_file_formats(self, filename): ...\n def _get_obj_from_path(self, path): ...\n def title(self, path): ...\n def cover_image_name(self, path): ...\n def thumbnail_size(self, path): ...\n def cover_size(self, path): ...\n def regenerate_thumbnails(self): ...\n def template_path(self, path): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_image_prefix_path", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001043.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": null, "focal_method": "template_path", "tests": "import unittest\n\nclass Test_template_path(unittest.TestCase):\n def test_template_path(self):\n self.assertRaises(KeyError, lambda: self.defConf.template_path('projects_logos/Teca'))\n", "method_code": " def template_path(self, path):\n try:\n return self._get_obj_from_path(path)['template_path']\n except KeyError:\n logging.debug('[warning]: got a key error retrieving template_path for {0}, using default'.format(path))\n return self.config['template_path']\n ", "context": "class ConfigHandler(object):\n def template_path(self, path): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_folders(self, path=''): ...\n def excluded_files(self, path=''): ...\n def excluded_file_formats(self, filename): ...\n def _get_obj_from_path(self, path): ...\n def title(self, path): ...\n def cover_image_name(self, path): ...\n def thumbnail_size(self, path): ...\n def cover_size(self, path): ...\n def image_prefix_path(self, path): ...\n def regenerate_thumbnails(self): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_template_path", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001044.py"} {"focal_file": "teca/ConfigHandler.py", "focal_class": "ch.ConfigHandler", "focal_method": "excluded_folders", "tests": "import unittest\n\nclass Test_ch_ConfigHandler_excluded_folders(unittest.TestCase):\n def test_excluded_folders_defaultparameter(self):\n defConf = ch.ConfigHandler()\n self.assertEqual(defConf.excluded_folders(), defConf.excluded_folders(''))\n", "method_code": " def excluded_folders(self, path=''):\n try:\n return self._get_obj_from_path(path)['excluded_folders']\n except KeyError:\n return list()\n ", "context": "class ConfigHandler(object):\n def excluded_folders(self, path=''): ...\n def __init__(self, config_json_path=None, options_from_cmd=None): ...\n def adapt(self, config_dict, father_obj=None, ind=0): ...\n def starting_path(self): ...\n def use_verbose(self): ...\n def image_formats(self): ...\n def excluded_files(self, path=''): ...\n def excluded_file_formats(self, filename): ...\n def _get_obj_from_path(self, path): ...\n def title(self, path): ...\n def cover_image_name(self, path): ...\n def thumbnail_size(self, path): ...\n def cover_size(self, path): ...\n def image_prefix_path(self, path): ...\n def regenerate_thumbnails(self): ...\n def template_path(self, path): ...\n def directories_on_a_row(self): ...\n def images_on_a_row(self): ...\n def algorithm(self): ...\n def default_image(self): ...\n def short_links(self): ...\n def is_plugin_enabled(self, feature): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_excluded_folders_defaultparameter", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001045.py"} {"focal_file": "teca/filesystem.py", "focal_class": null, "focal_method": "isDirectoryEmpty", "tests": "import unittest\n\nclass Test_isDirectoryEmpty(unittest.TestCase):\n def test_rootIsNotEmpty(self):\n res = tecafs.isDirectoryEmpty('', self.conf)\n self.assertEqual(res, False)\n", "method_code": "def isDirectoryEmpty(dir_path, cfg):\n _, dirnames, fnames = _next(walk(dir_path, cfg))\n return len(dirnames) + len(fnames) == 0", "context": "def isDirectoryEmpty(dir_path, cfg): ...\ndef walk(starting_path, cfg, deep=False): ...\ndef filterDirectories(dirpath, dirnames, cfg): ...\ndef filterFiles(dirpath, fnames, cfg): ...\ndef filterFilesIfInExcludedFileFormat(dirpath, fnames, cfg): ...\ndef filterAccordingToFunction(dirpath, items, cfg, function_): ...\ndef filesInDirectory(dir_path, cfg, deep=False): ...\ndef isDirectoryEmpty(dir_path, cfg): ...\ndef isFolderHidden(dir_path, cfg, with_starting_path=False): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_rootIsNotEmpty", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001046.py"} {"focal_file": "teca/filesystem.py", "focal_class": null, "focal_method": "filesInDirectory", "tests": "import unittest\n\nclass Test_filesInDirectory(unittest.TestCase):\n def test_noFilesInHiddenFolder(self):\n fnames = tecafs.filesInDirectory('hiddenfolder', self.conf)\n self.assertEqual(len(fnames), 0)\n fnames = tecafs.filesInDirectory('you/shall/notpass', self.conf)\n self.assertEqual(len(fnames), 0)\n\n def test_filesInNonHiddenFolder(self):\n fnames = tecafs.filesInDirectory('you/shall/pass', self.conf)\n self.assertNotEqual(len(fnames), 0)\n", "method_code": "def filesInDirectory(dir_path, cfg, deep=False):\n _, _, fnames = _next(walk(dir_path, cfg, deep))\n return fnames", "context": "def filesInDirectory(dir_path, cfg, deep=False): ...\ndef walk(starting_path, cfg, deep=False): ...\ndef filterDirectories(dirpath, dirnames, cfg): ...\ndef filterFiles(dirpath, fnames, cfg): ...\ndef filterFilesIfInExcludedFileFormat(dirpath, fnames, cfg): ...\ndef filterAccordingToFunction(dirpath, items, cfg, function_): ...\ndef filesInDirectory(dir_path, cfg, deep=False): ...\ndef isDirectoryEmpty(dir_path, cfg): ...\ndef isFolderHidden(dir_path, cfg, with_starting_path=False): ...\n", "repository": "winterthediplomat/Teca", "test_name": "test_noFilesInHiddenFolder", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001047.py"} {"focal_file": "codebase/drei/lib/database/SQLiteWrapper.py", "focal_class": null, "focal_method": "list_sounds", "tests": "import unittest\n\nclass Test_list_sounds(unittest.TestCase):\n def test_list_sounds(self):\n sound_list = self.db_wrapper.list_sounds()\n self.assertTrue(sound_list.__contains__('bla'))\n", "method_code": " def list_sounds(self):\n \"\"\"\n Provides a list of all sounds.\n :return: A list, containing the tuples (title, path).\n \"\"\"\n with sql.connect(self.db) as db_con:\n cursor = db_con.cursor()\n cursor.execute('SELECT title FROM Sounds')\n sound_list = flatten(cursor.fetchall())\n return sound_list\n ", "context": "class SQLiteWrapper(Database):\n def list_sounds(self): ...\n def __init__(self, db='test.db'): ...\n def add_user(self, user): ...\n def create_sound_title(self, filepath): ...\n def user_exists(self, cursor, user_mac): ...\n def get_song_ID(self, cursor, filepath): ...\n def create_sound_ID(self, cursor, filepath): ...\n def get_user(self, user_mac): ...\n def retrieve_users(self): ...\n def update_user(self, user_mac, user): ...\n def delete_user(self, user_mac): ...\n\n self.logger = Logger()\n", "repository": "stehrenberg/HomeAutomation", "test_name": "test_list_sounds", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001048.py"} {"focal_file": "codebase/drei/lib/database/SQLiteWrapper.py", "focal_class": null, "focal_method": "get_user", "tests": "import unittest\n\nclass Test_get_user(unittest.TestCase):\n def test_get_user(self):\n self.assertTrue(self.db_wrapper.add_user(self.testuser))\n self.assertTrue(self.db_wrapper.add_user(self.double_sound_testuser))\n user = self.db_wrapper.get_user('00:80:41:ae:fd:7f')\n self.assertEqual(self.testuser.mac, user.mac)\n self.assertEqual(self.testuser.name, user.name)\n self.assertEqual(self.testuser.sound, user.sound)\n self.assertEqual(self.testuser.light_color, user.light_color)\n", "method_code": " def get_user(self, user_mac):\n \"\"\"\n Returns the user with a given MAC address.\n :return: A user object.\n \"\"\"\n user = None\n with sql.connect(self.db) as db_con:\n cursor = db_con.cursor()\n cursor.execute(\"SELECT *, rowid FROM Users WHERE mac_address='%s'\" % user_mac)\n data = cursor.fetchone()\n if data:\n mac_add, name, light_color, sound, light_ID = data\n cursor.execute(\"SELECT * FROM Sounds WHERE sound_ID='%s'\" % sound)\n sound_ID, title, filepath = cursor.fetchone()\n user = User(mac_add, name, filepath, light_ID, light_color)\n else:\n self.logger.log(Logger.INFO, 'User with MAC %s could not be found.' % user_mac)\n return user\n ", "context": "class SQLiteWrapper(Database):\n def get_user(self, user_mac): ...\n def __init__(self, db='test.db'): ...\n def add_user(self, user): ...\n def create_sound_title(self, filepath): ...\n def user_exists(self, cursor, user_mac): ...\n def get_song_ID(self, cursor, filepath): ...\n def create_sound_ID(self, cursor, filepath): ...\n def retrieve_users(self): ...\n def update_user(self, user_mac, user): ...\n def delete_user(self, user_mac): ...\n def list_sounds(self): ...\n\n self.logger = Logger()\n", "repository": "stehrenberg/HomeAutomation", "test_name": "test_get_user", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001049.py"} {"focal_file": "codebase/drei/lib/database/SQLiteWrapper.py", "focal_class": null, "focal_method": "retrieve_users", "tests": "import unittest\n\nclass Test_retrieve_users(unittest.TestCase):\n def test_retrieve_users(self):\n self.assertTrue(self.db_wrapper.add_user(self.testuser))\n self.assertTrue(self.db_wrapper.add_user(self.double_sound_testuser))\n users = self.db_wrapper.retrieve_users()\n mac_addresses = []\n for user in users:\n mac_addresses.append(user.mac)\n self.assertTrue(mac_addresses.__contains__(self.testuser.mac))\n self.assertTrue(mac_addresses.__contains__(self.double_sound_testuser.mac))\n\n def test_retrieve_users_from_empty_db(self):\n users = self.db_wrapper.retrieve_users()\n self.assertTrue(len(users) == 0)\n print('users from empty db: ', users)\n", "method_code": " def retrieve_users(self):\n \"\"\"\n Returns a list with all users.\n :return: A list containing all users.\n \"\"\"\n users = []\n with sql.connect(self.db) as db_con:\n cursor = db_con.cursor()\n cursor.execute('SELECT mac_address FROM Users')\n mac_addresses = flatten(cursor.fetchall())\n for mac_add in mac_addresses:\n user = self.get_user(mac_add)\n users.append(user)\n return users\n ", "context": "class SQLiteWrapper(Database):\n def retrieve_users(self): ...\n def __init__(self, db='test.db'): ...\n def add_user(self, user): ...\n def create_sound_title(self, filepath): ...\n def user_exists(self, cursor, user_mac): ...\n def get_song_ID(self, cursor, filepath): ...\n def create_sound_ID(self, cursor, filepath): ...\n def get_user(self, user_mac): ...\n def update_user(self, user_mac, user): ...\n def delete_user(self, user_mac): ...\n def list_sounds(self): ...\n\n self.logger = Logger()\n", "repository": "stehrenberg/HomeAutomation", "test_name": "test_retrieve_users", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_001050.py"} {"focal_file": "codebase/drei/lib/database/SQLiteWrapper.py", "focal_class": null, "focal_method": "update_user", "tests": "import unittest\n\nclass Test_update_user(unittest.TestCase):\n def test_update_user(self):\n self.assertTrue(self.db_wrapper.add_user(self.testuser))\n self.assertTrue(self.db_wrapper.add_user(self.double_sound_testuser))\n updated_user = User(user_mac='00:80:41:ae:fd:7f', user_name='Steff', user_sound='/sounds/bla', user_light_id='None', user_light_color='#ff00ff')\n self.assertTrue(self.db_wrapper.update_user(updated_user.mac, updated_user))\n", "method_code": " def update_user(self, user_mac, user):\n \"\"\"\n Updates the user with specified user_id\n \"\"\"\n with sql.connect(self.db) as db_con:\n cursor = db_con.cursor()\n sound_ID = self.get_song_ID(cursor, user.sound)\n if not sound_ID:\n sound_ID = self.create_sound_ID(cursor, user.sound)\n cursor.execute('\\n UPDATE Users\\n SET light_color=?, sound=?\\n WHERE mac_address=?\\n ;', (user.light_color, sound_ID, user_mac))\n was_update_successful = cursor.rowcount > 0\n logger_msg = 'Nothing to update.'\n if was_update_successful:\n logger_msg = 'User data updated - new sound: %s new light color: %s.' % (user.sound, user.light_color)\n self.logger.log(Logger.INFO, logger_msg)\n return was_update_successful\n ", "context": "class SQLiteWrapper(Database):\n def update_user(self, user_mac, user): ...\n def __init__(self, db='test.db'): ...\n def add_user(self, user): ...\n def create_sound_title(self, filepath): ...\n def user_exists(self, cursor, user_mac): ...\n def get_song_ID(self, cursor, filepath): ...\n def create_sound_ID(self, cursor, filepath): ...\n def get_user(self, user_mac): ...\n def retrieve_users(self): ...\n def delete_user(self, user_mac): ...\n def list_sounds(self): ...\n\n self.logger = Logger()\n", "repository": "stehrenberg/HomeAutomation", "test_name": "test_update_user", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001051.py"} {"focal_file": "codebase/drei/lib/database/SQLiteWrapper.py", "focal_class": null, "focal_method": "delete_user", "tests": "import unittest\n\nclass Test_delete_user(unittest.TestCase):\n def test_delete_user(self):\n self.assertTrue(self.db_wrapper.add_user(self.testuser))\n self.assertTrue(self.db_wrapper.add_user(self.double_sound_testuser))\n kevins_mac = '00:80:41:00:fd:7f'\n self.assertTrue(None != self.db_wrapper.get_user(kevins_mac))\n self.db_wrapper.delete_user(kevins_mac)\n self.assertEquals(None, self.db_wrapper.get_user(kevins_mac))\n print('Users nach delete: ', self.db_wrapper.retrieve_users())\n", "method_code": " def delete_user(self, user_mac):\n \"\"\"\n Deletes the user with the specified user_mac.\n :returns True, if user was successfully deleted, otherwise false.\n \"\"\"\n with sql.connect(self.db) as db_con:\n cursor = db_con.cursor()\n cursor.execute(\"DELETE FROM Users WHERE mac_address='%s';\" % user_mac)\n deleting_successful = cursor.rowcount > 0\n logger_msg = 'Deleting user failed.'\n if deleting_successful:\n logger_msg = 'Deleted user %s' % user_mac\n self.logger.log(Logger.INFO, logger_msg)\n return deleting_successful\n ", "context": "class SQLiteWrapper(Database):\n def delete_user(self, user_mac): ...\n def __init__(self, db='test.db'): ...\n def add_user(self, user): ...\n def create_sound_title(self, filepath): ...\n def user_exists(self, cursor, user_mac): ...\n def get_song_ID(self, cursor, filepath): ...\n def create_sound_ID(self, cursor, filepath): ...\n def get_user(self, user_mac): ...\n def retrieve_users(self): ...\n def update_user(self, user_mac, user): ...\n def list_sounds(self): ...\n\n self.logger = Logger()\n", "repository": "stehrenberg/HomeAutomation", "test_name": "test_delete_user", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_001052.py"} {"focal_file": "evernotebot/bot/shortcuts.py", "focal_class": null, "focal_method": "get_cached_object", "tests": "import unittest\n\nclass Test_get_cached_object(unittest.TestCase):\n def test_get_cached_object(self):\n cache = {}\n result = get_cached_object(cache, None, constructor=lambda: {'default': 1})\n self.assertEqual(result, {'default': 1})\n result = get_cached_object(cache, 'x', constructor=lambda: {'x': 2})\n self.assertEqual(result, {'x': 2})\n result = get_cached_object(cache, 'y', constructor=lambda: {'y': 3})\n self.assertEqual(result, {'y': 3})\n self.assertEqual(len(cache), 3)\n result = get_cached_object(cache, 'x')\n self.assertEqual(len(cache), 3)\n self.assertEqual(result, {'x': 2})\n failed = False\n try:\n get_cached_object(cache, 'invalid')\n except KeyError:\n failed = True\n self.assertTrue(failed)\n", "method_code": "def get_cached_object(cache: dict, key: object, *, constructor: Callable=None):\n key = key or 'default'\n if key in cache:\n return cache[key]['object']\n if constructor is None:\n raise KeyError(f'Object with key `{key}` not found')\n new_object = constructor()\n cache[key] = {'created': time(), 'object': new_object}\n max_entries = 100\n if len(cache) > max_entries:\n oldest_key, _ = min(cache.items(), key=lambda entry: entry[1]['created'])\n del cache[oldest_key]\n return new_object", "context": "def get_cached_object(cache: dict, key: object, *, constructor: Callable=None): ...\ndef evernote_oauth_callback(bot, params: OauthParams): ...\ndef get_evernote_oauth_data(bot, bot_user: BotUser, message_text: str, access='basic') -> EvernoteOauthData: ...\ndef get_cached_object(cache: dict, key: object, *, constructor: Callable=None): ...\ndef download_telegram_file(telegram_api, file_id, dirpath='/tmp'): ...\ndef get_message_caption(message: dict) -> str: ...\ndef get_telegram_link(message: dict) -> str: ...\n", "repository": "djudman/evernote-telegram-bot", "test_name": "test_get_cached_object", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001053.py"} {"focal_file": "evernotebot/views.py", "focal_class": null, "focal_method": "telegram_hook", "tests": "import unittest\n\nclass Test_telegram_hook(unittest.TestCase):\n def test_telegram_hook_failed(self):\n request = self.create_request({'test': 'abc'})\n bot = request.app.bot\n self.assertEqual(len(list(iter(bot.failed_updates.get_all()))), 0)\n telegram_hook(request)\n failed_updates = list(iter(bot.failed_updates.get_all()))\n self.assertEqual(len(failed_updates), 1)\n self.assertEqual(failed_updates[0]['data']['test'], 'abc')\n", "method_code": "def telegram_hook(request: Request):\n data = request.json()\n bot = request.app.bot\n try:\n bot.process_update(data)\n except Exception:\n bot.fail_update(data)\n return ''", "context": "def telegram_hook(request: Request): ...\ndef telegram_hook(request: Request): ...\ndef evernote_oauth(request: Request): ...\n", "repository": "djudman/evernote-telegram-bot", "test_name": "test_telegram_hook_failed", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001054.py"} {"focal_file": "evernotebot/views.py", "focal_class": null, "focal_method": "evernote_oauth", "tests": "import unittest\n\nclass Test_evernote_oauth(unittest.TestCase):\n def test_evernote_oauth_declined_auth(self):\n callback_key = hashlib.sha1(b'xxx').hexdigest()\n request = self.create_request({'key': callback_key, 'access': 'basic'})\n bot = request.app.bot\n bot.api = mock.Mock()\n bot.api.sendMessage = mock.Mock()\n bot_user = BotUser(**self.default_user_data)\n bot_user.evernote.oauth = EvernoteOauthData(token='token', secret='secret', callback_key=callback_key)\n bot.users.create(bot_user.asdict())\n evernote_oauth(request)\n bot.api.sendMessage.assert_called_once()\n self.assertEqual(bot.api.sendMessage.call_args[0][1], 'We are sorry, but you have declined authorization.')\n", "method_code": "def evernote_oauth(request: Request):\n bot = request.app.bot\n params = request.GET\n callback_key = params['key']\n access_type = params['access']\n verifier = params.get('oauth_verifier')\n oauth_params = OauthParams(callback_key, verifier, access_type)\n evernote_oauth_callback(bot, oauth_params)\n return HTTPFound(bot.url)", "context": "def evernote_oauth(request: Request): ...\ndef telegram_hook(request: Request): ...\ndef evernote_oauth(request: Request): ...\n", "repository": "djudman/evernote-telegram-bot", "test_name": "test_evernote_oauth_declined_auth", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001055.py"} {"focal_file": "scripts/argument.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_argument(self):\n sys.argv = ['module']\n self.assertEqual('mongodb', vars(argument.parse(self.parser)).get(argument.ARG_NAME))\n", "method_code": "def parse(parser):\n args = None\n if len(sys.argv) == 1:\n args = __DEFAULT\n result = parser.parse_args(args)\n return result", "context": "def parse(parser): ...\ndef create(): ...\ndef parse(parser): ...\n", "repository": "Subarunari/SlackPostCounter", "test_name": "test_argument", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001056.py"} {"focal_file": "scripts/config.py", "focal_class": null, "focal_method": "get_logging_backup_count", "tests": "import unittest\n\nclass Test_get_logging_backup_count(unittest.TestCase):\n def test_backup_count(self):\n with patch('yaml.load', MagicMock(return_value=dict())):\n self.assertEqual(config.DEFAULT_BACKUP_COUNT, config.get_logging_backup_count())\n with patch('yaml.load', MagicMock(return_value={'logging': {'backup_count': 10}})):\n self.assertEqual(10, config.get_logging_backup_count())\n", "method_code": "def get_logging_backup_count():\n with open(CONFIG_FILE_PATH, 'r') as conf_file:\n data = yaml.safe_load(conf_file)\n backup_count = data.get('logging', dict()).get('backup_count')\n if backup_count is None:\n backup_count = DEFAULT_BACKUP_COUNT\n return backup_count", "context": "def get_logging_backup_count(): ...\ndef exists_config_file(): ...\ndef get_slack_token(): ...\ndef get_mongodb_conf(): ...\ndef get_logging_backup_count(): ...\n", "repository": "Subarunari/SlackPostCounter", "test_name": "test_backup_count", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001057.py"} {"focal_file": "scripts/driver/csv.py", "focal_class": null, "focal_method": "load_result", "tests": "import unittest\n\nclass Test_load_result(unittest.TestCase):\n def test_load_result(self):\n with patch('os.path.exists', MagicMock(return_value=False)):\n self.assertEqual(csv.load_result(), [])\n", "method_code": "def load_result():\n if not os.path.exists(RESULT_FILE_PATH):\n return []\n with open(RESULT_FILE_PATH, 'r') as csvfile:\n result = list(csv.DictReader(csvfile))\n return result", "context": "def load_result(): ...\ndef save_result(results): ...\ndef load_result(): ...\ndef save_latest_info(latest_infos): ...\ndef load_latest_info(): ...\n", "repository": "Subarunari/SlackPostCounter", "test_name": "test_load_result", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001058.py"} {"focal_file": "scripts/driver/csv.py", "focal_class": null, "focal_method": "load_latest_info", "tests": "import unittest\n\nclass Test_load_latest_info(unittest.TestCase):\n def test_load_latest_info(self):\n with patch('os.path.exists', MagicMock(return_value=False)):\n self.assertEqual(csv.load_latest_info(), [])\n", "method_code": "def load_latest_info():\n if not os.path.exists(LATEST_INFO_PATH):\n return []\n with open(LATEST_INFO_PATH, 'r') as csvfile:\n result = list(csv.DictReader(csvfile))\n return result", "context": "def load_latest_info(): ...\ndef save_result(results): ...\ndef load_result(): ...\ndef save_latest_info(latest_infos): ...\ndef load_latest_info(): ...\n", "repository": "Subarunari/SlackPostCounter", "test_name": "test_load_latest_info", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001059.py"} {"focal_file": "lib/websockets/framing.py", "focal_class": null, "focal_method": "parse_close", "tests": "import unittest\n\nclass Test_parse_close(unittest.TestCase):\n def test_parse_close_empty(self):\n self.assertEqual(parse_close(b''), (1005, ''))\n\n def test_parse_close_errors(self):\n with self.assertRaises(WebSocketProtocolError):\n parse_close(b'\\x03')\n with self.assertRaises(WebSocketProtocolError):\n parse_close(b'\\x03\\xe7')\n with self.assertRaises(UnicodeDecodeError):\n parse_close(b'\\x03\\xe8\\xff\\xff')\n", "method_code": "def parse_close(data):\n \"\"\"\n Parse the data in a close frame.\n\n Return ``(code, reason)`` when ``code`` is an :class:`int` and ``reason``\n a :class:`str`.\n\n Raise :exc:`~websockets.exceptions.WebSocketProtocolError` or\n :exc:`UnicodeDecodeError` if the data is invalid.\n\n \"\"\"\n length = len(data)\n if length == 0:\n return (1005, '')\n elif length == 1:\n raise WebSocketProtocolError('Close frame too short')\n else:\n code, = struct.unpack('!H', data[:2])\n if not (code in CLOSE_CODES or 3000 <= code < 5000):\n raise WebSocketProtocolError('Invalid status code')\n reason = data[2:].decode('utf-8')\n return (code, reason)", "context": "def parse_close(data): ...\ndef read_frame(reader, mask, *, max_size=None): ...\ndef write_frame(frame, writer, mask): ...\ndef check_frame(frame): ...\ndef parse_close(data): ...\ndef serialize_close(code, reason): ...\n", "repository": "SinnFrei/red", "test_name": "test_parse_close_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001060.py"} {"focal_file": "lib/websockets/handshake.py", "focal_class": null, "focal_method": "accept", "tests": "import unittest\n\nclass Test_accept(unittest.TestCase):\n def test_accept(self):\n key = 'dGhlIHNhbXBsZSBub25jZQ=='\n acc = 's3pPLMBiTxaQ9kYGzzhZRbK+xOo='\n self.assertEqual(accept(key), acc)\n\n def test_response_invalid_accept(self):\n with self.assert_invalid_response_headers() as headers:\n other_key = '1Eq4UDEFQYg3YspNgqxv5g=='\n headers['Sec-WebSocket-Accept'] = accept(other_key)\n", "method_code": "def accept(key):\n sha1 = hashlib.sha1((key + GUID).encode()).digest()\n return base64.b64encode(sha1).decode()", "context": "def accept(key): ...\ndef build_request(set_header): ...\ndef check_request(get_header): ...\ndef build_response(set_header, key): ...\ndef check_response(get_header, key): ...\ndef accept(key): ...\n", "repository": "SinnFrei/red", "test_name": "test_accept", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001061.py"} {"focal_file": "ImP/imageProcessing/aerocubeMarker.py", "focal_class": null, "focal_method": "raise_if_markers_invalid", "tests": "import unittest\n\nclass Test_raise_if_markers_invalid(unittest.TestCase):\n def test_raise_if_markers_invalid(self):\n try:\n AeroCube.raise_if_markers_invalid(self.VALID_MARKERS)\n except Exception:\n self.fail()\n", "method_code": " def raise_if_markers_invalid(markers):\n \"\"\"\n Tests if the given array of AeroCube Markers are a valid set to be input as\n constructor arguments for an AeroCube.\n If markers are invalid, raise an exception.\n Checks for the following condition:\n 1. Markers is non-empty (an AeroCube object should not be created if there are no markers)\n 2. Markers have identical AeroCube IDs\n :param markers: array of AeroCube Markers to be tested\n \"\"\"\n if not markers:\n raise AttributeError(AeroCube._ERR_MESSAGES[AeroCube._MARKERS_EMPTY])\n if not all((marker.aerocube_ID == markers[0].aerocube_ID for marker in markers)):\n aerocube_IDs = set([marker.aerocube_ID for marker in markers])\n raise AttributeError(AeroCube._ERR_MESSAGES[AeroCube._MARKERS_HAVE_MANY_AEROCUBES].format(aerocube_IDs))\n ", "context": "class AeroCube():\n @staticmethod\n def raise_if_markers_invalid(markers): ...\n def __init__(self, markers): ...\n def __eq__(self, other): ...\n def markers(self): ...\n def ID(self): ...\n def tvec(self): ...\n def quaternion(self): ...\n def distance(self): ...\n def to_json(self): ...\n def reduce_quaternions(markers): ...\n def reduce_translation_vectors(markers): ...\n def distance_from_tvec(tvec): ...\n\n self._markers = markers\n self._ID = markers[0].aerocube_ID\n self._tvec = self.reduce_translation_vectors(markers)\n self._quaternion = self.reduce_quaternions(markers)\n self._distance = self.distance_from_tvec(self.tvec)\n\n NUM_SIDES = 6\n STR_KEY_CUBE_IDS = 'CUBE_IDS'\n STR_KEY_QUATERNIONS = 'QUATERNIONS'\n STR_KEY_TVECS = 'TVECS'\n STR_KEY_DISTANCES = 'DISTANCES'\n STR_KEY_MARKERS_DETECTED = 'MARKERS_DETECTED'\n _MARKERS_EMPTY, _MARKERS_HAVE_MANY_AEROCUBES, _DUPLICATE_MARKERS = range(3)\n _ERR_MESSAGES = {_MARKERS_EMPTY: 'Markers for an AeroCube cannot be empty', _MARKERS_HAVE_MANY_AEROCUBES: 'AeroCube Markers do not belong to same AeroCube (IDs are {})', _DUPLICATE_MARKERS: 'Duplicate AeroCube Marker used (Fiducial ID: {})'}\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_raise_if_markers_invalid", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001062.py"} {"focal_file": "ImP/imageProcessing/aerocubeMarker.py", "focal_class": null, "focal_method": "_valid_aerocube_ID", "tests": "import unittest\n\nclass Test_valid_aerocube_ID(unittest.TestCase):\n def test_valid_aerocube_ID(self):\n valid_IDs = range(0, 7)\n for ID in valid_IDs:\n self.assertTrue(AeroCubeMarker._valid_aerocube_ID(ID), 'test_valid_aerocube_ID failed on {}'.format(ID))\n invalid_IDs = [-1, 8, 9]\n for ID in invalid_IDs:\n self.assertFalse(AeroCubeMarker._valid_aerocube_ID(ID), 'test_valid_aerocube_ID failed on {}'.format(ID))\n", "method_code": " def _valid_aerocube_ID(aerocube_id):\n return aerocube_id >= 0 and aerocube_id * AeroCube.NUM_SIDES + AeroCube.NUM_SIDES <= AeroCubeMarker.get_dictionary_size()\n ", "context": "class AeroCubeMarker(FiducialMarker):\n @staticmethod\n def _valid_aerocube_ID(aerocube_id): ...\n def __init__(self, corners, fiducial_marker_id, quaternion, tvec): ...\n def __eq__(self, other): ...\n def __str__(self): ...\n def aerocube_ID(self): ...\n def aerocube_face(self): ...\n def corners(self): ...\n def quaternion(self): ...\n def tvec(self): ...\n def distance(self): ...\n def to_jsonifiable_dict(self): ...\n def distance_from_tvec(tvec): ...\n def _get_aerocube_marker_IDs(aerocube_ID): ...\n def get_aerocube_marker_set(aerocube_ID): ...\n def identify_marker_ID(marker_ID): ...\n\n self._aerocube_ID, self._aerocube_face = self.identify_marker_ID(fiducial_marker_id)\n self._tvec = tvec\n self._distance = self.distance_from_tvec(self._tvec)\n\n MARKER_LENGTH = ImageProcessingSettings.get_marker_length()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_valid_aerocube_ID", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001063.py"} {"focal_file": "ImP/imageProcessing/aerocubeMarker.py", "focal_class": null, "focal_method": "distance_from_tvec", "tests": "import unittest\n\nclass Test_distance_from_tvec(unittest.TestCase):\n def test_distance_from_tvec(self):\n tvec = [0.08787901, -0.03494572, 0.8768408]\n np.testing.assert_allclose([AeroCubeMarker.distance_from_tvec(tvec)], [0.88192613806])\n", "method_code": " def distance_from_tvec(tvec):\n return np.linalg.norm(tvec)\n ", "context": "class AeroCubeMarker(FiducialMarker):\n @staticmethod\n def distance_from_tvec(tvec): ...\n def __init__(self, corners, fiducial_marker_id, quaternion, tvec): ...\n def __eq__(self, other): ...\n def __str__(self): ...\n def aerocube_ID(self): ...\n def aerocube_face(self): ...\n def corners(self): ...\n def quaternion(self): ...\n def tvec(self): ...\n def distance(self): ...\n def _valid_aerocube_ID(aerocube_id): ...\n def to_jsonifiable_dict(self): ...\n def _get_aerocube_marker_IDs(aerocube_ID): ...\n def get_aerocube_marker_set(aerocube_ID): ...\n def identify_marker_ID(marker_ID): ...\n\n self._aerocube_ID, self._aerocube_face = self.identify_marker_ID(fiducial_marker_id)\n self._tvec = tvec\n self._distance = self.distance_from_tvec(self._tvec)\n\n MARKER_LENGTH = ImageProcessingSettings.get_marker_length()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_distance_from_tvec", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001064.py"} {"focal_file": "ImP/imageProcessing/aerocubeMarker.py", "focal_class": null, "focal_method": "_get_aerocube_marker_IDs", "tests": "import unittest\n\nclass Test_get_aerocube_marker_IDs(unittest.TestCase):\n def test_positive_get_aerocube_marker_IDs(self):\n marker_IDs = [6, 7, 8, 9, 10, 11]\n test_marker_IDs = AeroCubeMarker._get_aerocube_marker_IDs(1)\n self.assertTrue(numpy.array_equal(marker_IDs, test_marker_IDs), '_get_aerocube_marker_IDs failed')\n", "method_code": " def _get_aerocube_marker_IDs(aerocube_ID):\n \"\"\"\n Get the list of marker IDs for a given AeroCube and it's ID\n Marker IDs are within the range [aerocube_ID*6, aerocube_ID*6 + 6],\n where aerocube IDs and marker IDs are 0 indexed\n :param aerocube_ID: ID of the AeroCube\n :return: array of marker IDs that can be used to attain marker images\n \"\"\"\n if not AeroCubeMarker._valid_aerocube_ID(aerocube_ID):\n raise IDOutOfDictionaryBoundError('Invalid AeroCube ID(s)')\n base_marker_ID = aerocube_ID * AeroCube.NUM_SIDES\n end_marker_ID = base_marker_ID + AeroCube.NUM_SIDES\n return list(range(base_marker_ID, end_marker_ID))\n ", "context": "class AeroCubeMarker(FiducialMarker):\n @staticmethod\n def _get_aerocube_marker_IDs(aerocube_ID): ...\n def __init__(self, corners, fiducial_marker_id, quaternion, tvec): ...\n def __eq__(self, other): ...\n def __str__(self): ...\n def aerocube_ID(self): ...\n def aerocube_face(self): ...\n def corners(self): ...\n def quaternion(self): ...\n def tvec(self): ...\n def distance(self): ...\n def _valid_aerocube_ID(aerocube_id): ...\n def to_jsonifiable_dict(self): ...\n def distance_from_tvec(tvec): ...\n def get_aerocube_marker_set(aerocube_ID): ...\n def identify_marker_ID(marker_ID): ...\n\n self._aerocube_ID, self._aerocube_face = self.identify_marker_ID(fiducial_marker_id)\n self._tvec = tvec\n self._distance = self.distance_from_tvec(self._tvec)\n\n MARKER_LENGTH = ImageProcessingSettings.get_marker_length()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_positive_get_aerocube_marker_IDs", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001065.py"} {"focal_file": "ImP/imageProcessing/aerocubeMarker.py", "focal_class": null, "focal_method": "get_aerocube_marker_set", "tests": "import unittest\n\nclass Test_get_aerocube_marker_set(unittest.TestCase):\n def test_positive_get_aerocube_marker_set(self):\n marker_IDs = AeroCubeMarker._get_aerocube_marker_IDs(1)\n marker_imgs = [FiducialMarker.draw_marker(ID) for ID in marker_IDs]\n self.assertTrue(numpy.array_equal(marker_imgs, AeroCubeMarker.get_aerocube_marker_set(1)), 'positive_get_aerocube_marker_set failed')\n\n def test_negative_get_aerocube_marker_set(self):\n \"\"\"\n Verify that, given two different AeroCube IDs, the two sets of marker\n images do not share any images\n \"\"\"\n marker_IDs = AeroCubeMarker._get_aerocube_marker_IDs(0)\n marker_imgs = [FiducialMarker.draw_marker(ID) for ID in marker_IDs]\n test_marker_imgs = AeroCubeMarker.get_aerocube_marker_set(1)\n for img in marker_imgs:\n for test_img in test_marker_imgs:\n self.assertFalse(numpy.array_equal(img, test_img), 'negative_get_aerocube_marker_set failed')\n", "method_code": " def get_aerocube_marker_set(aerocube_ID):\n marker_IDs = AeroCubeMarker._get_aerocube_marker_IDs(aerocube_ID)\n return [AeroCubeMarker.draw_marker(ID) for ID in marker_IDs]\n ", "context": "class AeroCubeMarker(FiducialMarker):\n @staticmethod\n def get_aerocube_marker_set(aerocube_ID): ...\n def __init__(self, corners, fiducial_marker_id, quaternion, tvec): ...\n def __eq__(self, other): ...\n def __str__(self): ...\n def aerocube_ID(self): ...\n def aerocube_face(self): ...\n def corners(self): ...\n def quaternion(self): ...\n def tvec(self): ...\n def distance(self): ...\n def _valid_aerocube_ID(aerocube_id): ...\n def to_jsonifiable_dict(self): ...\n def distance_from_tvec(tvec): ...\n def _get_aerocube_marker_IDs(aerocube_ID): ...\n def identify_marker_ID(marker_ID): ...\n\n self._aerocube_ID, self._aerocube_face = self.identify_marker_ID(fiducial_marker_id)\n self._tvec = tvec\n self._distance = self.distance_from_tvec(self._tvec)\n\n MARKER_LENGTH = ImageProcessingSettings.get_marker_length()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_positive_get_aerocube_marker_set", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001066.py"} {"focal_file": "ImP/imageProcessing/cameraCalibration.py", "focal_class": null, "focal_method": "get_charucoboard", "tests": "import unittest\n\nclass Test_get_charucoboard(unittest.TestCase):\n def test_get_charucoboard(self):\n board = CameraCalibration.get_charucoboard()\n self.assertEqual(board.getChessboardSize(), (8, 5))\n self.assertEqual(board.getMarkerLength(), 9)\n self.assertEqual(board.getSquareLength(), 10)\n self.assertTrue(AeroCubeMarker.dictionary_equal(board.dictionary, AeroCubeMarker.get_dictionary()))\n", "method_code": " def get_charucoboard():\n \"\"\"\n Create a Charuco (chessboard Aruco) board using pre-set params.\n :return board: board object created by the aruco call\n \"\"\"\n SQUARES_X = 8\n SQUARES_Y = 5\n SQUARE_LENGTH = 10\n MARKER_LENGTH = 9\n board = aruco.CharucoBoard_create(SQUARES_X, SQUARES_Y, SQUARE_LENGTH, MARKER_LENGTH, AeroCubeMarker.get_dictionary())\n return board\n ", "context": "class CameraCalibration():\n @staticmethod\n def get_charucoboard(): ...\n def get_default_calibration(): ...\n def draw_charucoboard(out_size, file_path): ...\n def get_calibration_matrices(board, img_arr): ...\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_get_charucoboard", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001067.py"} {"focal_file": "ImP/imageProcessing/cameraCalibration.py", "focal_class": null, "focal_method": "draw_charucoboard", "tests": "import unittest\n\nclass Test_draw_charucoboard(unittest.TestCase):\n def test_draw_charucoboard(self):\n fp = tempfile.NamedTemporaryFile(dir=self._test_files_path, suffix=self._img_suffix)\n print(fp.name)\n CameraCalibration.draw_charucoboard((80, 50), fp.name)\n self.assertTrue(os.stat(fp.name).st_size != 0)\n fp.close()\n", "method_code": " def draw_charucoboard(out_size, file_path):\n \"\"\"\n Draw the Charucoboard to file_path\n :param out_size: size must be tuple (x, y) such that:\n x >= SQUARES_X * SQUARE_LENGTH\n y >= SQUARES_Y * SQUARE_LENGTH\n :param file_path: path to which the board image will be drawn\n \"\"\"\n board = CameraCalibration.get_charucoboard()\n cv2.imwrite(file_path, aruco.drawPlanarBoard(board, out_size))\n ", "context": "class CameraCalibration():\n @staticmethod\n def draw_charucoboard(out_size, file_path): ...\n def get_default_calibration(): ...\n def get_charucoboard(): ...\n def get_calibration_matrices(board, img_arr): ...\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_draw_charucoboard", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_001068.py"} {"focal_file": "ImP/imageProcessing/cameraCalibration.py", "focal_class": null, "focal_method": "get_calibration_matrices", "tests": "import unittest\n\nclass Test_get_calibration_matrices(unittest.TestCase):\n def test_get_calibration_matrices(self):\n board = CameraCalibration.get_charucoboard()\n img_paths = [os.path.join(self._test_files_path, 'andrew_iphone_calibration_photo_0.jpg'), os.path.join(self._test_files_path, 'andrew_iphone_calibration_photo_1.jpg'), os.path.join(self._test_files_path, 'andrew_iphone_calibration_photo_2.jpg'), os.path.join(self._test_files_path, 'andrew_iphone_calibration_photo_3.jpg')]\n img_arr = [cv2.imread(img) for img in img_paths]\n retval = CameraCalibration.get_calibration_matrices(board, img_arr)\n self.assertEqual(len(retval), 3)\n self.assertEqual(retval[1].shape, (3, 3))\n self.assertEqual(retval[2].shape, (1, 5))\n", "method_code": " def get_calibration_matrices(board, img_arr):\n \"\"\"\n :param board: Charucoboard object to calibrate against\n :param img_arr: array of images (from different viewpoints)\n :return ret_val: unknown usage\n :return camera_matrix: 3X3 camera calibration matrix\n :return dist_coeffs: camera's distortion coefficients\n \"\"\"\n dictionary = AeroCubeMarker.get_dictionary()\n all_charuco_corners = []\n all_charuco_IDs = []\n img_size = None\n for img in img_arr:\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n corners, IDs, _ = aruco.detectMarkers(gray, dictionary)\n _, charuco_corners, charuco_IDs = aruco.interpolateCornersCharuco(corners, IDs, gray, board)\n all_charuco_corners.append(charuco_corners)\n all_charuco_IDs.append(charuco_IDs)\n img_size = gray.shape\n ret_val, camera_matrix, dist_coeffs, _, _ = aruco.calibrateCameraCharuco(all_charuco_corners, all_charuco_IDs, board, img_size, None, None)\n return (ret_val, camera_matrix, dist_coeffs)\n ", "context": "class CameraCalibration():\n @staticmethod\n def get_calibration_matrices(board, img_arr): ...\n def get_default_calibration(): ...\n def get_charucoboard(): ...\n def draw_charucoboard(out_size, file_path): ...\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_get_calibration_matrices", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001069.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "_load_image", "tests": "import unittest\n\nclass Test_ImageProcessor_load_image(unittest.TestCase):\n def test_positive_load_image(self):\n imp = ImageProcessor(self.TEST_SINGLE_MARKER.img_path)\n self.assertIsNotNone(ImageProcessor._load_image(self.TEST_SINGLE_MARKER.img_path))\n", "method_code": " def _load_image(file_path):\n \"\"\"\n Method used to load an image given the file path (static since it\n does not rely on state).\n :param file_path: path used to find the image to be processed\n :return: the image specified as a matrix\n \"\"\"\n image = cv2.imread(file_path)\n if image is None:\n raise OSError('cv2.imread returned None for path {}'.format(file_path))\n return image\n ", "context": "class ImageProcessor():\n @staticmethod\n def _load_image(file_path): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_positive_load_image", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001070.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "_find_fiducial_markers", "tests": "import unittest\n\nclass Test_ImageProcessor_find_fiducial_markers(unittest.TestCase):\n def test_find_fiducial_marker(self):\n corners, ids = ImageProcessor._simplify_fiducial_arrays(self.TEST_SINGLE_MARKER.corners, self.TEST_SINGLE_MARKER.IDs)\n imp = ImageProcessor(self.TEST_SINGLE_MARKER.img_path)\n test_corners, test_ids = imp._find_fiducial_markers()\n self.assertTrue(np.array_equal(corners, test_corners))\n self.assertTrue(np.array_equal(ids, test_ids))\n self.assertEqual(type(test_ids).__module__, np.__name__)\n output_img = imp.draw_fiducial_markers(test_corners, test_ids)\n cv2.imwrite(self.test_output_path, output_img)\n\n def test_find_fiducial_marker_multiple(self):\n imp = ImageProcessor(self.TEST_MULT_AEROCUBES.img_path)\n corners, ids = imp._simplify_fiducial_arrays(self.TEST_MULT_AEROCUBES.corners, self.TEST_MULT_AEROCUBES.IDs)\n test_corners, test_ids = imp._find_fiducial_markers()\n np.testing.assert_allclose(corners, test_corners)\n np.testing.assert_array_equal(ids, test_ids)\n\n def test_find_fiducial_marker_none(self):\n imp = ImageProcessor(self.TEST_NO_MARKER.img_path)\n corners, ids = imp._simplify_fiducial_arrays(self.TEST_NO_MARKER.corners, self.TEST_NO_MARKER.IDs)\n test_corners, test_ids = imp._find_fiducial_markers()\n np.testing.assert_allclose(corners, test_corners)\n np.testing.assert_array_equal(ids, test_ids)\n", "method_code": " def _find_fiducial_markers(self, gpu=False):\n \"\"\"\n Identify fiducial markers in _img_mat\n Serves as an abstraction of the aruco method calls\n Note that the default format of the arrays returned by Aruco are a bit cumbersome, and are being translated\n into friendlier formats before being returned.\n :param gpu: optional param to attempt to use parallelized algorithm\n :return corners: an array of 3-D arrays\n each element is of the shape (N, 4, 2), where N is the number of detected markers\n If no markers found, corners == []\n :return marker_IDs: an array of integers corresponding to the corners.\n Note that the Aruco method returns a 1D numpy array of the form [id1, id2, ...],\n and has the shape (N,)\n If no markers found, marker_IDs == None\n \"\"\"\n if gpu is True:\n corners, marker_IDs = MarkerDetectPar.detect_markers_parallel(self._img_mat, dictionary=self._DICTIONARY)\n else:\n corners, marker_IDs, _ = aruco.detectMarkers(self._img_mat, dictionary=self._DICTIONARY)\n corners, marker_IDs = self._simplify_fiducial_arrays(corners, marker_IDs)\n return (corners, marker_IDs)\n ", "context": "class ImageProcessor():\n def _find_fiducial_markers(self, gpu=False): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_find_fiducial_marker", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001071.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": null, "focal_method": "_simplify_fiducial_arrays", "tests": "import unittest\n\nclass Test_simplify_fiducial_arrays(unittest.TestCase):\n def test_simplify_fiducial_arrays(self):\n corners, ids = (self.TEST_NO_MARKER.corners, self.TEST_NO_MARKER.IDs)\n actual_corners, actual_ids = ImageProcessor._simplify_fiducial_arrays(corners, ids)\n exp_corners, exp_ids = ([], [])\n np.testing.assert_allclose(actual_corners, exp_corners)\n np.testing.assert_array_equal(actual_ids, exp_ids)\n self.assertIsInstance(actual_corners, np.ndarray)\n self.assertIsInstance(actual_ids, np.ndarray)\n corners, ids = (self.TEST_SINGLE_MARKER.corners, self.TEST_SINGLE_MARKER.IDs)\n actual_corners, actual_ids = ImageProcessor._simplify_fiducial_arrays(corners, ids)\n exp_corners, exp_ids = (np.array(corners).squeeze(axis=1), np.array(ids).squeeze())\n np.testing.assert_allclose(actual_corners, exp_corners)\n np.testing.assert_array_equal(actual_ids, exp_ids)\n self.assertEqual(np.shape(actual_corners), (1, 4, 2))\n self.assertEqual(np.shape(actual_ids), (1,))\n self.assertIsInstance(actual_corners, np.ndarray)\n self.assertIsInstance(actual_ids, np.ndarray)\n corners, ids = (self.TEST_MULT_AEROCUBES.corners, self.TEST_MULT_AEROCUBES.IDs)\n actual_corners, actual_ids = ImageProcessor._simplify_fiducial_arrays(corners, ids)\n exp_corners, exp_ids = (np.array(corners).squeeze(axis=1), np.array(ids).squeeze())\n np.testing.assert_allclose(actual_corners, exp_corners)\n np.testing.assert_array_equal(actual_ids, exp_ids)\n self.assertEqual(np.shape(actual_corners), (2, 4, 2))\n self.assertEqual(np.shape(actual_ids), (2,))\n self.assertIsInstance(actual_corners, np.ndarray)\n self.assertIsInstance(actual_ids, np.ndarray)\n", "method_code": " def _simplify_fiducial_arrays(corners, ids):\n \"\"\"\n Translates the default arrays returned by Aruco's marker detection method into a simpler format.\n Corners: (N, 1, 4, 2) --> (N, 4, 2)\n IDs: (N, 1) --> (N,), same as 1-dimensional matrix/vector\n Note that when no markers are found, Aruco returns [] for corners and None for ids. In this case,\n return empty Numpy lists for both items.\n :param corners: corners formatted as (N, 1, 4, 2)\n :param ids: IDs formatted as (N, 1)\n :return: (corners, ids)\n \"\"\"\n assert len(corners) is 0 or len(np.shape(corners)) is 4\n assert ids is None or len(np.shape(ids)) is 2\n if len(corners) == 0:\n return (np.array(corners), np.array(list()))\n else:\n return (np.array(corners).squeeze(axis=1), np.squeeze(ids, axis=1))\n ", "context": "class ImageProcessor():\n @staticmethod\n def _simplify_fiducial_arrays(corners, ids): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_simplify_fiducial_arrays", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001072.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": null, "focal_method": "_prepare_fiducial_arrays_for_aruco", "tests": "import unittest\n\nclass Test_prepare_fiducial_arrays_for_aruco(unittest.TestCase):\n def test_prepare_fiducial_arrays_for_aruco(self):\n markers = self.TEST_NO_MARKER\n corners, ids = ImageProcessor._simplify_fiducial_arrays(markers.corners, markers.IDs)\n actual_corners, actual_ids = ImageProcessor._prepare_fiducial_arrays_for_aruco(corners, ids)\n exp_corners, exp_ids = ([], None)\n np.testing.assert_allclose(actual_corners, exp_corners)\n np.testing.assert_array_equal(actual_ids, exp_ids)\n self.assertNotIsInstance(actual_ids, np.ndarray)\n markers = self.TEST_SINGLE_MARKER\n corners, ids = ImageProcessor._simplify_fiducial_arrays(markers.corners, markers.IDs)\n actual_corners, actual_ids = ImageProcessor._prepare_fiducial_arrays_for_aruco(corners, ids)\n exp_corners, exp_ids = ([corners], [ids])\n np.testing.assert_allclose(actual_corners, exp_corners)\n np.testing.assert_array_equal(actual_ids, exp_ids)\n self.assertEqual(np.shape(actual_corners), (1, 1, 4, 2))\n self.assertEqual(np.shape(actual_ids), (1, 1))\n markers = self.TEST_MULT_AEROCUBES\n corners, ids = ImageProcessor._simplify_fiducial_arrays(markers.corners, markers.IDs)\n actual_corners, actual_ids = ImageProcessor._prepare_fiducial_arrays_for_aruco(corners, ids)\n exp_corners, exp_ids = ([[corners[0]], [corners[1]]], [[ids[0]], [ids[1]]])\n np.testing.assert_allclose(actual_corners, exp_corners)\n np.testing.assert_array_equal(actual_ids, exp_ids)\n self.assertEqual(np.shape(actual_corners), (2, 1, 4, 2))\n self.assertEqual(np.shape(actual_ids), (2, 1))\n", "method_code": " def _prepare_fiducial_arrays_for_aruco(corners, ids):\n \"\"\"\n Translates simplified fiducial marker arrays to format usable by Aruco methods.\n Corners: (N, 4, 2) --> (N, 1, 4, 2)\n IDs: (N,) --> (N, 1)\n Note that when no markers are found, Aruco returns [] for corners and None for ids. Therefore, if\n params corners and ids are empty Numpy arrays, return ([], None)\n :param corners: corners formatted as (N, 4, 2)\n :param ids: IDs formatted as (N,)\n :return: (corners, ids)\n \"\"\"\n assert len(corners) is 0 or len(np.shape(corners)) is 3\n assert len(ids) is 0 or len(np.shape(ids)) is 1\n if len(corners) == 0:\n return ([], None)\n else:\n return ([np.array([c]) for c in corners], np.array([[i] for i in ids]))\n ", "context": "class ImageProcessor():\n @staticmethod\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_prepare_fiducial_arrays_for_aruco", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001073.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "_find_aerocube_markers", "tests": "import unittest\n\nclass Test_ImageProcessor_find_aerocube_markers(unittest.TestCase):\n def test_find_aerocube_marker(self):\n imp = ImageProcessor(self.AC_0_FACES_125_PATH)\n aerocube_markers = imp._find_aerocube_markers()\n [self.assertIsInstance(m, AeroCubeMarker) for m in aerocube_markers]\n\n def test_find_aerocube_markers_none(self):\n aerocube_markers = []\n imp = ImageProcessor(self.TEST_NO_MARKER.img_path)\n test_markers = imp._find_aerocube_markers()\n self.assertTrue(np.array_equal(aerocube_markers, test_markers))\n", "method_code": " def _find_aerocube_markers(self, gpu=False):\n \"\"\"\n Calls a private function to find all fiducial markers, then constructs\n AeroCubeMarker objects from those results. If there are no markers found,\n return an empty array.\n :return: array of AeroCubeMarker objects; empty if none found\n \"\"\"\n corners, ids = self._find_fiducial_markers(gpu=gpu)\n if len(ids) is 0:\n return []\n else:\n rvecs, tvecs = self._find_pose(corners)\n quaternions = [self.rodrigues_to_quaternion(r) for r in rvecs]\n return [AeroCubeMarker(corners, id, q, tvec) for corners, id, q, tvec in zip(corners, ids, quaternions, tvecs)]\n ", "context": "class ImageProcessor():\n def _find_aerocube_markers(self, gpu=False): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_find_aerocube_marker", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001074.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "_identify_aerocubes", "tests": "import unittest\n\nclass Test_ImageProcessor_identify_aerocubes(unittest.TestCase):\n def test_identify_aerocubes(self):\n aerocube_ID = 0\n aerocube_face = AeroCubeFace.ZENITH\n corners, _ = ImageProcessor._simplify_fiducial_arrays(self.TEST_SINGLE_MARKER.corners, [[aerocube_ID]])\n marker_list = [AeroCubeMarker(aerocube_ID, aerocube_face, corners[0])]\n aerocube_list = [AeroCube(marker_list)]\n imp = ImageProcessor(self.TEST_SINGLE_MARKER.img_path)\n self.assertEqual(imp._identify_aerocubes(), aerocube_list)\n\n def test_identify_aerocubes_multiple(self):\n corners, _ = ImageProcessor._simplify_fiducial_arrays(self.TEST_MULT_AEROCUBES.corners, [[2], [0]])\n aerocube_2_markers = [AeroCubeMarker(2, AeroCubeFace.ZENITH, corners[0])]\n aerocube_0_markers = [AeroCubeMarker(0, AeroCubeFace.BACK, corners[1])]\n aerocubes = [AeroCube(aerocube_2_markers), AeroCube(aerocube_0_markers)]\n imp = ImageProcessor(self.TEST_MULT_AEROCUBES.img_path)\n test_aerocubes = imp._identify_aerocubes()\n self.assertTrue(np.array_equal(aerocubes, test_aerocubes))\n\n def test_identify_aerocubes_none(self):\n imp = ImageProcessor(self.TEST_NO_MARKER.img_path)\n self.assertEqual([], imp._identify_aerocubes())\n", "method_code": " def _identify_aerocubes(self):\n \"\"\"\n Internal function called when ImP receives a ImageEventSignal.IDENTIFY_AEROCUBES signal.\n :return: array of AeroCube objects; [] if no AeroCubes found\n \"\"\"\n markers = self._find_aerocube_markers()\n markers.sort(key=lambda marker: marker.aerocube_ID)\n print('IMP: Markers sorted {}'.format(markers))\n aerocubes = list()\n for aerocube, aerocube_markers in itertools.groupby(markers, lambda m: m.aerocube_ID):\n aerocubes.append(AeroCube(list(aerocube_markers)))\n return aerocubes\n ", "context": "class ImageProcessor():\n def _identify_aerocubes(self): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_identify_aerocubes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001075.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "_find_distance", "tests": "import unittest\n\nclass Test_ImageProcessor_find_distance(unittest.TestCase):\n def test_find_distance(self):\n imp = ImageProcessor(self.TEST_JETSON_SINGLE_MARKER.img_path)\n corners, ids = imp._find_fiducial_markers()\n dist = imp._find_distance(corners)\n print(dist)\n self.assertGreater(dist[0], 0.8)\n self.assertLess(dist[0], 1.0)\n", "method_code": " def _find_distance(self, corners):\n \"\"\"\n Find the distance of an array of markers (represented by their corners).\n References:\n * http://stackoverflow.com/questions/14038002/opencv-how-to-calculate-distance-between-camera-and-object-using-image\n * http://www.pyimagesearch.com/2015/01/19/find-distance-camera-objectmarker-using-python-opencv/\n :param corners: array of markers, each represented by their four corner points\n :param cal: calibration information of the camera used for the image\n :return: distance in meters\n \"\"\"\n cal = self._cal\n m = (cal.CAMERA_MATRIX[0][0] / cal.FOCAL_LENGTH + cal.CAMERA_MATRIX[1][1] / cal.FOCAL_LENGTH) / 2\n m_for_res = self._img_mat.shape[0] * (m / cal.IMG_RES[0])\n dist_results = list()\n marker_size = ImageProcessingSettings.get_marker_length()\n for marker in corners:\n pixel_length1 = math.sqrt(math.pow(marker[0][0] - marker[1][0], 2) + math.pow(marker[0][1] - marker[1][1], 2))\n pixel_length2 = math.sqrt(math.pow(marker[2][0] - marker[3][0], 2) + math.pow(marker[2][1] - marker[3][1], 2))\n pixlength = (pixel_length1 + pixel_length2) / 2\n dist = marker_size * cal.FOCAL_LENGTH / (pixlength / m_for_res)\n dist_results.append(dist)\n return dist_results\n ", "context": "class ImageProcessor():\n def _find_distance(self, corners): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_find_distance", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_001076.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "identify_markers_for_storage", "tests": "import unittest\n\nclass Test_ImageProcessor_identify_markers_for_storage(unittest.TestCase):\n def test_identify_markers_for_storage(self):\n self.fail()\n corners, _ = ImageProcessor._simplify_fiducial_arrays(self.TEST_SINGLE_MARKER.corners, [[0]])\n marker_list = [AeroCubeMarker(0, AeroCubeFace.ZENITH, corners[0])]\n aerocube_list = [AeroCube(marker_list)]\n imp = ImageProcessor(self.TEST_SINGLE_MARKER.img_path)\n scan_results = imp.identify_markers_for_storage()\n np.testing.assert_array_equal(aerocube_list, scan_results)\n", "method_code": " def identify_markers_for_storage(self):\n cubes = self._identify_aerocubes()\n cube_ids = list()\n quaternions = dict()\n tvecs = dict()\n distances = dict()\n num_markers = dict()\n markers = list()\n for cube in cubes:\n ID = str(cube.ID)\n cube_ids.append(int(cube.ID))\n quaternions[ID] = {k: v for k, v in zip(['w', 'x', 'y', 'z'], cube.quaternion.elements)}\n tvecs[ID] = {k: v for k, v in zip(['x', 'y', 'z'], cube.tvec)}\n distances[ID] = cube.distance\n num_markers[ID] = len(cube.markers)\n markers += [m.to_jsonifiable_dict() for m in cube.markers]\n cube_json_dict = {AeroCube.STR_KEY_CUBE_IDS: cube_ids, AeroCube.STR_KEY_QUATERNIONS: quaternions, AeroCube.STR_KEY_TVECS: tvecs, AeroCube.STR_KEY_DISTANCES: distances, AeroCube.STR_KEY_MARKERS_DETECTED: num_markers}\n return (cube_json_dict, markers)\n ", "context": "class ImageProcessor():\n def identify_markers_for_storage(self): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_identify_markers_for_storage", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001077.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "draw_fiducial_markers", "tests": "import unittest\n\nclass Test_ImageProcessor_draw_fiducial_markers(unittest.TestCase):\n def test_draw_fiducial_markers(self):\n imp = ImageProcessor(self.TEST_SINGLE_MARKER.img_path)\n corners, IDs = imp._find_fiducial_markers()\n img = imp.draw_fiducial_markers(corners, IDs)\n self.assertEqual(img.shape, imp._img_mat.shape)\n", "method_code": " def draw_fiducial_markers(self, corners, marker_IDs, img=None):\n \"\"\"\n Returns an image matrix with the given corners and marker_IDs drawn onto the image\n :param corners: marker corners\n :param marker_IDs: fiducial marker IDs\n :param img:\n :return: img with marker boundaries drawn and markers IDed\n \"\"\"\n img = np.copy(self._img_mat) if img is None else img\n aruco_corners, aruco_ids = self._prepare_fiducial_arrays_for_aruco(corners, marker_IDs)\n return aruco.drawDetectedMarkers(img, aruco_corners, aruco_ids)\n ", "context": "class ImageProcessor():\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_draw_fiducial_markers", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001078.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "draw_axis", "tests": "import unittest\n\nclass Test_ImageProcessor_draw_axis(unittest.TestCase):\n def test_draw_axis(self):\n imp = ImageProcessor(self.TEST_JETSON_SINGLE_MARKER.img_path)\n rvecs, tvecs = imp._find_pose(imp._find_fiducial_markers()[0])\n img = imp.draw_axis(imp.rodrigues_to_quaternion(rvecs[0]), tvecs[0])\n self.assertIsNotNone(img)\n", "method_code": " def draw_axis(self, quaternion, tvec, img=None):\n \"\"\"\n Wrapper method that calls Aruco's draw axis method on a given marker.\n Can be used to visually verify the accuracy of pose.\n :param quaternion: pose represented as quaternion\n :param tvec: translation vector, returned by Aruco's estimatePoseSingleMarker\n :param img:\n :return: img held by this ImageProcessor with the drawn axis\n \"\"\"\n img = np.copy(self._img_mat) if img is None else img\n return aruco.drawAxis(img, self._cal.CAMERA_MATRIX, self._cal.DIST_COEFFS, self.quaternion_to_rodrigues(quaternion), tvec, ImageProcessingSettings.get_marker_length())\n ", "context": "class ImageProcessor():\n def draw_axis(self, quaternion, tvec, img=None): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_draw_axis", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001079.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": "ImageProcessor", "focal_method": "rodrigues_to_quaternion", "tests": "import unittest\n\nclass Test_ImageProcessor_rodrigues_to_quaternion(unittest.TestCase):\n def test_rodrigues_to_quaternion_has_identical_rotation(self):\n \"\"\"\n Confirms the following case:\n http://stackoverflow.com/questions/12933284/rodrigues-into-eulerangles-and-vice-versa\n \"\"\"\n imp = ImageProcessor(self.TEST_JETSON_SINGLE_MARKER.img_path)\n rvecs, _ = imp._find_pose(imp._find_fiducial_markers()[0])\n test_quat = imp.rodrigues_to_quaternion(rvecs[0])\n rot_mat_orig = cv2.Rodrigues(rvecs[0])[0]\n rot_mat_quat = test_quat.rotation_matrix\n rot_mat = cv2.multiply(rot_mat_orig, cv2.transpose(rot_mat_quat))\n self.assertTrue(np.allclose(rot_mat_orig, rot_mat_quat, rtol=0.01))\n\n def test_rodrigues_to_quaternion(self):\n imp = ImageProcessor(self.TEST_JETSON_SINGLE_MARKER.img_path)\n rvecs, _ = imp._find_pose(imp._find_fiducial_markers()[0])\n test_quat = imp.rodrigues_to_quaternion(rvecs[0])\n true_quat = pyquaternion.Quaternion(w=-0.06, x=0.746, y=-0.648, z=-0.14)\n self.assertEqual(str(test_quat), str(true_quat))\n", "method_code": " def rodrigues_to_quaternion(rodrigues):\n \"\"\"\n Converts an OpenCV rvec object (written in compact Rodrigues notation) into a quaternion.\n http://stackoverflow.com/questions/12933284/rodrigues-into-eulerangles-and-vice-versa\n :param rodrigues: rotation in compact Rodrigues notation (returned by cv2.Rodrigues) as 1x3 array\n :return: rotation represented as quaternion\n \"\"\"\n return pyquaternion.Quaternion(matrix=cv2.Rodrigues(rodrigues)[0]).normalised\n ", "context": "class ImageProcessor():\n @staticmethod\n def rodrigues_to_quaternion(rodrigues): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def quaternion_to_rodrigues(quaternion): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_rodrigues_to_quaternion_has_identical_rotation", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001080.py"} {"focal_file": "ImP/imageProcessing/imageProcessingInterface.py", "focal_class": null, "focal_method": "quaternion_to_rodrigues", "tests": "import unittest\n\nclass Test_quaternion_to_rodrigues(unittest.TestCase):\n def test_quaternion_to_rodrigues(self):\n rodr = np.array([[2.43782719, -2.1174341, -0.45808756]])\n quat = pyquaternion.Quaternion(w=-0.06, x=0.746, y=-0.648, z=-0.14)\n self.assertTrue(np.allclose(cv2.Rodrigues(rodr)[0], cv2.Rodrigues(ImageProcessor.quaternion_to_rodrigues(quat))[0], rtol=0.01))\n", "method_code": " def quaternion_to_rodrigues(quaternion):\n \"\"\"\n Converts quaternion to rvec object (written in compact Rodrigues notation)\n :param quaternion: rotation represented as quaternion\n :return: rotation represented as rvec in compact Rodrigues notation\n \"\"\"\n return cv2.Rodrigues(quaternion.rotation_matrix)[0]\n ", "context": "class ImageProcessor():\n @staticmethod\n def quaternion_to_rodrigues(quaternion): ...\n def __init__(self, file_path, cal=CameraCalibration.get_default_calibration()): ...\n def _load_image(file_path): ...\n def _find_fiducial_markers(self, gpu=False): ...\n def _simplify_fiducial_arrays(corners, ids): ...\n def _prepare_fiducial_arrays_for_aruco(corners, ids): ...\n def draw_fiducial_markers(self, corners, marker_IDs, img=None): ...\n def draw_axis(self, quaternion, tvec, img=None): ...\n def draw_aerocube_markers(self): ...\n def draw_aerocubes(self): ...\n def _find_pose(self, corners): ...\n def _find_aerocube_markers(self, gpu=False): ...\n def _identify_aerocubes(self): ...\n def identify_markers_for_storage(self): ...\n def _find_distance(self, corners): ...\n def _find_distances_from_tvec(tvecs): ...\n def rodrigues_to_quaternion(rodrigues): ...\n\n self._img_mat = self._load_image(file_path)\n self._cal = cal\n\n _DICTIONARY = AeroCubeMarker.get_dictionary()\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_quaternion_to_rodrigues", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001081.py"} {"focal_file": "externalComm/commClass.py", "focal_class": null, "focal_method": "write", "tests": "import unittest\n\nclass Test_write(unittest.TestCase):\n def test_write(self):\n self.commTest.write('test', '2', 'this is a test2')\n self.assertEqual(self.commTest.read('test', '2'), 'this is a test2')\n self.commTest.delete('test', '2')\n self.assertIsNone(self.commTest.read('test', '2'))\n", "method_code": " def write(self, location, id, data):\n pass\n ", "context": "class Comm():\n @abstractmethod\n def write(self, location, id, data): ...\n def name(self): ...\n def read(self, location, id): ...\n def delete(self, location, id): ...\n def imageStore(self, id, srcImage): ...\n def imageDownload(self, id): ...\n\n __metaclass__ = ABCMeta\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_write", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001082.py"} {"focal_file": "externalComm/commClass.py", "focal_class": null, "focal_method": "read", "tests": "import unittest\n\nclass Test_read(unittest.TestCase):\n def test_read(self):\n self.assertEqual(self.commTest.read('test', '1'), 'this is a test')\n", "method_code": " def read(self, location, id):\n pass\n ", "context": "class Comm():\n @abstractmethod\n def read(self, location, id): ...\n def name(self): ...\n def write(self, location, id, data): ...\n def delete(self, location, id): ...\n def imageStore(self, id, srcImage): ...\n def imageDownload(self, id): ...\n\n __metaclass__ = ABCMeta\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_read", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001083.py"} {"focal_file": "externalComm/commClass.py", "focal_class": null, "focal_method": "imageStore", "tests": "import unittest\n\nclass Test_imageStore(unittest.TestCase):\n def test_imageStore(self):\n self.commTest.imageStore('test', 'externalComm/testimage.jpg')\n", "method_code": " def imageStore(self, id, srcImage):\n pass\n ", "context": "class Comm():\n @abstractmethod\n def imageStore(self, id, srcImage): ...\n def name(self): ...\n def read(self, location, id): ...\n def write(self, location, id, data): ...\n def delete(self, location, id): ...\n def imageDownload(self, id): ...\n\n __metaclass__ = ABCMeta\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_imageStore", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001084.py"} {"focal_file": "externalComm/commClass.py", "focal_class": null, "focal_method": "imageDownload", "tests": "import unittest\n\nclass Test_imageDownload(unittest.TestCase):\n def test_imageDownload(self):\n self.commTest.imageDownload('test')\n self.assertTrue(os.path.isfile('externalComm/test.jpg'))\n", "method_code": " def imageDownload(self, id):\n pass\n ", "context": "class Comm():\n @abstractmethod\n def imageDownload(self, id): ...\n def name(self): ...\n def read(self, location, id): ...\n def write(self, location, id, data): ...\n def delete(self, location, id): ...\n def imageStore(self, id, srcImage): ...\n\n __metaclass__ = ABCMeta\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_imageDownload", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001085.py"} {"focal_file": "flaskServer/restEndpoint.py", "focal_class": null, "focal_method": "create_flask_app", "tests": "import unittest\n\nclass Test_create_flask_app(unittest.TestCase):\n def test_create_flask(self):\n app, api = restEndpoint.create_flask_app()\n self.assertIsNotNone(app)\n self.assertIsNotNone(api)\n self.assertEqual(app.config[restEndpoint.PhotoUpload.UPLOAD_FOLDER], FlaskServerSettings.get_static_img_dir())\n", "method_code": "def create_flask_app():\n \"\"\"\n Creates a Flask app and api. Does NOT exhibit singleton behavior -- if called after a Flask app has\n already been instantiated, it will simply create a new Flask app.\n :return: (app, api)\n \"\"\"\n app = Flask(__name__)\n api = Api(app)\n api.add_resource(PhotoUpload, '/api/uploadImage')\n CORS(app)\n app.config[PhotoUpload.UPLOAD_FOLDER] = FlaskServerSettings.get_static_img_dir()\n return (app, api)", "context": "def create_flask_app(): ...\ndef initialize_endpoint(): ...\ndef create_flask_app(): ...\ndef get_job_handler(): ...\ndef get_tcp_client(): ...\ndef on_send_event(job_handler, event): ...\ndef on_enqueue_job(job): ...\ndef on_dequeue_job(job): ...\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_create_flask", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001086.py"} {"focal_file": "flaskServer/restEndpoint.py", "focal_class": null, "focal_method": "initialize_endpoint", "tests": "import unittest\n\nclass Test_initialize_endpoint(unittest.TestCase):\n def test_initialize_endpoint(self):\n self.assertIsNone(restEndpoint._handler)\n self.assertIsNone(restEndpoint._client)\n handler, client, app, api = restEndpoint.initialize_endpoint()\n self.assertIsNotNone(restEndpoint._handler)\n self.assertIsNotNone(restEndpoint._client)\n self.assertIsNotNone(app)\n self.assertIsNotNone(api)\n", "method_code": "def initialize_endpoint():\n \"\"\"\n Initializes module members (handler, client, Flask app).\n Should only be called once.\n :return: (handler, client, app, api)\n \"\"\"\n job_handler = get_job_handler()\n job_handler.set_start_event_observer(on_send_event)\n job_handler.set_job_enqueue_observer(on_enqueue_job)\n job_handler.set_job_dequeue_observer(on_dequeue_job)\n client = get_tcp_client()\n app, api = create_flask_app()\n return (job_handler, client, app, api)", "context": "def initialize_endpoint(): ...\ndef initialize_endpoint(): ...\ndef create_flask_app(): ...\ndef get_job_handler(): ...\ndef get_tcp_client(): ...\ndef on_send_event(job_handler, event): ...\ndef on_enqueue_job(job): ...\ndef on_dequeue_job(job): ...\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_initialize_endpoint", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001087.py"} {"focal_file": "jobs/aeroCubeEvent.py", "focal_class": "StorageEvent", "focal_method": "parse_storage_keys", "tests": "import unittest\n\nclass Test_StorageEvent_parse_storage_keys(unittest.TestCase):\n def test_storage_event_parse_storage_keys(self):\n scan_id = '123456789'\n scan_corners = [[11.0, 12.0], [13.0, 14.0], [15.0, 16.0], [17.0, 18.0]]\n scan_marker_ids = [[0]]\n payload = Bundle()\n payload.insert_string(ImageEvent.SCAN_ID, scan_id)\n payload.insert_iterable(ImageEvent.SCAN_CORNERS, scan_corners)\n payload.insert_iterable(ImageEvent.SCAN_MARKER_IDS, scan_marker_ids)\n payload.insert_iterable(StorageEvent.INT_STORE_PAYLOAD_KEYS, ['strings:' + ImageEvent.SCAN_ID, 'iterables:' + ImageEvent.SCAN_CORNERS, 'iterables:' + ImageEvent.SCAN_MARKER_IDS])\n event = StorageEvent(StorageEventSignal.STORE_INTERNALLY, payload)\n self.assertEqual(event.parse_storage_keys(), [scan_id, scan_corners, scan_marker_ids])\n", "method_code": " def parse_storage_keys(self):\n type_key_pairs = None\n data = dict()\n if self.signal is StorageEventSignal.STORE_INTERNALLY:\n type_key_pairs = self.payload.iterables(self.INT_STORE_PAYLOAD_KEYS)\n elif self.signal is StorageEventSignal.STORE_EXTERNALLY:\n type_key_pairs = self.payload.iterables(self.EXT_STORE_PAYLOAD_KEYS)\n for pair in type_key_pairs:\n bundle_type, key = pair.split(':')\n data[key] = getattr(self.payload, bundle_type)(key)\n return data\n ", "context": "class StorageEvent(AeroCubeEvent):\n def parse_storage_keys(self): ...\n def __init__(self, storage_signal, bundle=None, created_at=None, id=None): ...\n def is_valid_signal(self, signal): ...\n\n INT_STORAGE_REL_PATH = 'INT_STORAGE_REL_PATH'\n INT_STORE_PAYLOAD_KEYS = 'INT_STORE_PAYLOAD_KEYS'\n EXT_STORAGE_TARGET = 'EXT_STORAGE_TARGET'\n EXT_STORE_PAYLOAD_KEYS = 'EXT_STORE_PAYLOAD_KEYS'\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_storage_event_parse_storage_keys", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001088.py"} {"focal_file": "jobs/aeroCubeJob.py", "focal_class": null, "focal_method": "update_current_node", "tests": "import unittest\n\nclass Test_update_current_node(unittest.TestCase):\n def test_update_node_updates_current_node(self):\n result_event = ResultEvent(ResultEventSignal.WARN, self._IMAGE_EVENT.uuid)\n job = AeroCubeJob(self._IMAGE_EVENT_WARN_NODE)\n job.update_current_node(result_event)\n self.assertEqual(job.current_event, self._IMAGE_EVENT_OK_NODE.event)\n second_result_event = ResultEvent(ResultEventSignal.OK, self._IMAGE_EVENT.uuid)\n job.update_current_node(second_result_event)\n self.assertEqual(job.current_event, self._IMAGE_EVENT)\n", "method_code": " def update_current_node(self, result_event, merge_payload=False):\n \"\"\"\n Updates the current node property and returns the updated node's event.\n If the current node is a leaf node, returns None\n :param result_event: the result_event corresponding to the current node\n :param merge_payload: if set to True, merges the bundle of the current bundle with the\n next node's event's bundle\n \"\"\"\n if not isinstance(result_event, ResultEvent):\n raise AttributeError('AeroCubeJob.update_and_retrieve_next_event: ERROR: resolve_event requires a ResultEvent')\n if self.current_event.uuid != result_event.payload.strings(ResultEvent.CALLING_EVENT_UUID):\n raise AttributeError('AeroCubeJob.update_and_retrieve_next_event: ERROR: result event with CALLING_EVENT_UUID:{} received not for current calling event:{}'.format(result_event.payload.strings(ResultEvent.CALLING_EVENT_UUID), self.current_event.uuid))\n self._current_node = self._current_node.next_event_node(result_event)\n if merge_payload is True and (not self.is_finished):\n self._current_node.event.merge_payload(result_event.payload)\n ", "context": "class AeroCubeJob():\n def update_current_node(self, result_event, merge_payload=False): ...\n def __init__(self, root_event_node, created_at=time.time(), id=None): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def root_event(self): ...\n def current_event(self): ...\n def created_at(self): ...\n def uuid(self): ...\n def is_finished(self): ...\n def create_image_upload_job(img_path, int_storage=False, ext_store_target=None): ...\n\n self._root_event_node = root_event_node\n self._current_node = root_event_node\n self._created_at = created_at\n self._uuid = id if id is not None else uuid.uuid5(uuid.NAMESPACE_OID, '{}-{}'.format(self.__class__.__name__, self._created_at)).hex\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_update_node_updates_current_node", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001089.py"} {"focal_file": "jobs/aeroCubeJob.py", "focal_class": null, "focal_method": "create_image_upload_job", "tests": "import unittest\n\nclass Test_create_image_upload_job(unittest.TestCase):\n def test_create_image_upload_job(self):\n img_path = 'my_phony_path'\n job = AeroCubeJob.create_image_upload_job(img_path, int_storage=True, ext_store_target='FIREBASE')\n self.assertIsNotNone(job)\n self.assertIsInstance(job.root_event, ImageEvent)\n self.assertEqual(job.root_event.payload.strings(ImageEvent.FILE_PATH), img_path)\n int_store_node = job._current_node.event_signal_map[ResultEventSignal.OK]\n self.assertIsInstance(int_store_node.event, StorageEvent)\n self.assertEqual(int_store_node.event.signal, StorageEventSignal.STORE_INTERNALLY)\n np.testing.assert_equal(int_store_node.event.payload.raws(StorageEvent.INT_STORE_PAYLOAD_KEYS), [ImageEvent.SCAN_ID, ImageEvent.SCAN_CORNERS, ImageEvent.SCAN_MARKER_IDS])\n ext_store_node = int_store_node.event_signal_map[ResultEventSignal.OK]\n self.assertIsInstance(ext_store_node.event, StorageEvent)\n self.assertEqual(ext_store_node.event.signal, StorageEventSignal.STORE_EXTERNALLY)\n self.assertEqual(ext_store_node.event.payload.strings(StorageEvent.EXT_STORAGE_TARGET), 'FIREBASE')\n", "method_code": " def create_image_upload_job(img_path, int_storage=False, ext_store_target=None):\n \"\"\"\n Sequence of events\n 1. ImageEvent - identify AeroCubes\n 2. StorageEvent - store internally\n 3. StorageEvent - store externally\n :param img_path:\n :param int_storage:\n :param ext_store_target:\n :return:\n \"\"\"\n ext_store_bundle = Bundle()\n ext_store_node = None\n if ext_store_target is not None:\n ext_store_bundle.insert_string(StorageEvent.EXT_STORAGE_TARGET, ext_store_target)\n ext_store_bundle.insert_iterable(StorageEvent.EXT_STORE_PAYLOAD_KEYS, ['strings:' + ImageEvent.SCAN_ID, 'raws:' + ImageEvent.SCAN_MARKERS, 'raws:' + AeroCube.STR_KEY_CUBE_IDS, 'raws:' + AeroCube.STR_KEY_QUATERNIONS, 'raws:' + AeroCube.STR_KEY_TVECS, 'raws:' + AeroCube.STR_KEY_DISTANCES, 'raws:' + AeroCube.STR_KEY_MARKERS_DETECTED])\n ext_store_node = AeroCubeJobEventNode(StorageEvent(StorageEventSignal.STORE_EXTERNALLY, ext_store_bundle))\n int_store_bundle = Bundle()\n int_store_node = None\n if int_storage is True:\n int_store_bundle.insert_iterable(StorageEvent.INT_STORE_PAYLOAD_KEYS, ['strings:' + ImageEvent.SCAN_ID, 'raws:' + ImageEvent.SCAN_MARKERS, 'raws:' + AeroCube.STR_KEY_CUBE_IDS, 'raws:' + AeroCube.STR_KEY_QUATERNIONS, 'raws:' + AeroCube.STR_KEY_TVECS, 'raws:' + AeroCube.STR_KEY_DISTANCES, 'raws:' + AeroCube.STR_KEY_MARKERS_DETECTED])\n int_store_event = StorageEvent(StorageEventSignal.STORE_INTERNALLY, int_store_bundle)\n if ext_store_target is not None:\n int_store_node = AeroCubeJobEventNode(int_store_event, ok_event_node=ext_store_node)\n else:\n int_store_node = AeroCubeJobEventNode(int_store_event)\n img_bundle = Bundle()\n img_bundle.insert_string(ImageEvent.FILE_PATH, img_path)\n img_event = ImageEvent(ImageEventSignal.IDENTIFY_AEROCUBES, img_bundle)\n if int_storage is True:\n img_node = AeroCubeJobEventNode(img_event, ok_event_node=int_store_node)\n else:\n img_node = AeroCubeJobEventNode(img_event)\n job = AeroCubeJob(img_node)\n if ext_store_target is not None:\n ext_store_bundle.insert_string(job_id_bundle_key, job.uuid)\n if int_storage is not None:\n int_store_bundle.insert_string(job_id_bundle_key, job.uuid)\n img_bundle.insert_string(job_id_bundle_key, job.uuid)\n return job\n ", "context": "class AeroCubeJob():\n @staticmethod\n def create_image_upload_job(img_path, int_storage=False, ext_store_target=None): ...\n def __init__(self, root_event_node, created_at=time.time(), id=None): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def root_event(self): ...\n def current_event(self): ...\n def created_at(self): ...\n def uuid(self): ...\n def is_finished(self): ...\n def update_current_node(self, result_event, merge_payload=False): ...\n\n self._root_event_node = root_event_node\n self._current_node = root_event_node\n self._created_at = created_at\n self._uuid = id if id is not None else uuid.uuid5(uuid.NAMESPACE_OID, '{}-{}'.format(self.__class__.__name__, self._created_at)).hex\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_create_image_upload_job", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001090.py"} {"focal_file": "jobs/bundle.py", "focal_class": null, "focal_method": "is_valid_key", "tests": "import unittest\n\nclass Test_is_valid_key(unittest.TestCase):\n def test_valid_key(self):\n self.assertEqual(self._bundle.is_valid_key(self._valid_key), True)\n", "method_code": " def is_valid_key(key):\n \"\"\"\n is_valid_key defines valid keys to be uppercase characters and underscores only\n :param key: a potential key\n :return: validity of the key\n \"\"\"\n for c in key:\n if c != '_' and (not c.isalpha()):\n return False\n return key.isupper()\n ", "context": "class Bundle(object):\n @staticmethod\n def is_valid_key(key): ...\n def __init__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __str__(self): ...\n def to_json(self): ...\n def construct_from_json(bundle_json_string): ...\n def merge_from_bundle(self, other_bundle): ...\n def strings(self, key=None): ...\n def numbers(self, key=None): ...\n def raws(self, key=None): ...\n def iterables(self, key=None): ...\n def insert_string(self, key, value): ...\n def insert_number(self, key, value): ...\n def insert_raw(self, key, value): ...\n def insert_iterable(self, key, value): ...\n\n self._strings = {}\n self._numbers = {}\n self._raws = {}\n self._iterables = {}\n\n _IMPROPER_KEY_FORMAT_STRING = '{} is not properly formatted'\n _INCORRECT_TYPE_STRING = 'Not a string'\n _INCORRECT_TYPE_NUMBER = 'Not a number'\n _INCORRECT_TYPE_ITERABLE = 'Not an iterable'\n _INCORRECT_TYPE_RAW_IS_STRING = 'Not raw data, found string'\n _INCORRECT_TYPE_RAW_IS_NUMBER = 'Not raw data, found number'\n _ERROR_MESSAGES = (_IMPROPER_KEY_FORMAT_STRING, _INCORRECT_TYPE_STRING, _INCORRECT_TYPE_NUMBER, _INCORRECT_TYPE_ITERABLE, _INCORRECT_TYPE_RAW_IS_NUMBER, _INCORRECT_TYPE_RAW_IS_STRING)\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_valid_key", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001091.py"} {"focal_file": "jobs/bundle.py", "focal_class": null, "focal_method": "insert_number", "tests": "import unittest\n\nclass Test_insert_number(unittest.TestCase):\n def test_bundle_invalid_number_set(self):\n with self.assertRaises(AttributeError):\n self._bundle.insert_number(self._valid_key, self._invalid_num)\n\n def test_bundle_valid_number(self):\n self._bundle.insert_number(self._valid_key, self._valid_num)\n self.assertEqual(self._bundle.numbers(self._valid_key), self._valid_num)\n", "method_code": " def insert_number(self, key, value):\n \"\"\"\n Insert a string value with a given key\n :raises AttributeError: if the key is invalid\n :raises AttributeError: if the value is not a number\n :param key: a valid key\n :param value: a number\n \"\"\"\n if not Bundle.is_valid_key(key):\n raise AttributeError(self._IMPROPER_KEY_FORMAT_STRING.format(key))\n if isinstance(value, Number):\n self._numbers[key] = value\n else:\n raise AttributeError(self._INCORRECT_TYPE_NUMBER)\n ", "context": "class Bundle(object):\n def insert_number(self, key, value): ...\n def __init__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __str__(self): ...\n def to_json(self): ...\n def construct_from_json(bundle_json_string): ...\n def is_valid_key(key): ...\n def merge_from_bundle(self, other_bundle): ...\n def strings(self, key=None): ...\n def numbers(self, key=None): ...\n def raws(self, key=None): ...\n def iterables(self, key=None): ...\n def insert_string(self, key, value): ...\n def insert_raw(self, key, value): ...\n def insert_iterable(self, key, value): ...\n\n self._strings = {}\n self._numbers = {}\n self._raws = {}\n self._iterables = {}\n\n _IMPROPER_KEY_FORMAT_STRING = '{} is not properly formatted'\n _INCORRECT_TYPE_STRING = 'Not a string'\n _INCORRECT_TYPE_NUMBER = 'Not a number'\n _INCORRECT_TYPE_ITERABLE = 'Not an iterable'\n _INCORRECT_TYPE_RAW_IS_STRING = 'Not raw data, found string'\n _INCORRECT_TYPE_RAW_IS_NUMBER = 'Not raw data, found number'\n _ERROR_MESSAGES = (_IMPROPER_KEY_FORMAT_STRING, _INCORRECT_TYPE_STRING, _INCORRECT_TYPE_NUMBER, _INCORRECT_TYPE_ITERABLE, _INCORRECT_TYPE_RAW_IS_NUMBER, _INCORRECT_TYPE_RAW_IS_STRING)\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_bundle_invalid_number_set", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001092.py"} {"focal_file": "jobs/bundle.py", "focal_class": null, "focal_method": "strings", "tests": "import unittest\n\nclass Test_strings(unittest.TestCase):\n def test_bundle_valid_string(self):\n self._bundle.insert_string(self._valid_key, self._valid_string)\n self.assertEqual(self._bundle.strings(self._valid_key), self._valid_string)\n", "method_code": " def strings(self, key=None):\n \"\"\"\n Accessor for a specific key or the entire strings dict\n :raises BundleKeyError if the key is not none, is valid, and no key-value pair is found\n :raises AttributeError if the key is invalid\n :param key: optional\n :return: the value in the key-value pair for a given key if not None, or the entire strings dict\n \"\"\"\n if key is not None and (not Bundle.is_valid_key(key)):\n raise AttributeError(self._IMPROPER_KEY_FORMAT_STRING.format(key))\n if key is not None:\n try:\n return self._strings[key]\n except KeyError as err:\n raise BundleKeyError(str(err))\n else:\n return self._strings\n ", "context": "class Bundle(object):\n def strings(self, key=None): ...\n def __init__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __str__(self): ...\n def to_json(self): ...\n def construct_from_json(bundle_json_string): ...\n def is_valid_key(key): ...\n def merge_from_bundle(self, other_bundle): ...\n def numbers(self, key=None): ...\n def raws(self, key=None): ...\n def iterables(self, key=None): ...\n def insert_string(self, key, value): ...\n def insert_number(self, key, value): ...\n def insert_raw(self, key, value): ...\n def insert_iterable(self, key, value): ...\n\n self._strings = {}\n self._numbers = {}\n self._raws = {}\n self._iterables = {}\n\n _IMPROPER_KEY_FORMAT_STRING = '{} is not properly formatted'\n _INCORRECT_TYPE_STRING = 'Not a string'\n _INCORRECT_TYPE_NUMBER = 'Not a number'\n _INCORRECT_TYPE_ITERABLE = 'Not an iterable'\n _INCORRECT_TYPE_RAW_IS_STRING = 'Not raw data, found string'\n _INCORRECT_TYPE_RAW_IS_NUMBER = 'Not raw data, found number'\n _ERROR_MESSAGES = (_IMPROPER_KEY_FORMAT_STRING, _INCORRECT_TYPE_STRING, _INCORRECT_TYPE_NUMBER, _INCORRECT_TYPE_ITERABLE, _INCORRECT_TYPE_RAW_IS_NUMBER, _INCORRECT_TYPE_RAW_IS_STRING)\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_bundle_valid_string", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001093.py"} {"focal_file": "jobs/bundle.py", "focal_class": null, "focal_method": "insert_raw", "tests": "import unittest\n\nclass Test_insert_raw(unittest.TestCase):\n def test_bundle_valid_raw(self):\n self._bundle.insert_raw(self._valid_key, self._valid_raw)\n bundled_val = self._bundle.raws(self._valid_key)\n self.assertEqual(bundled_val, self._valid_raw)\n", "method_code": " def insert_raw(self, key, value):\n \"\"\"\n Insert a string value with a given key\n :raises AttributeError: if the key is invalid\n :raises AttributeError: if the value is not a raw\n :param key: a valid key\n :param value: a raw\n \"\"\"\n if not Bundle.is_valid_key(key):\n raise AttributeError(self._IMPROPER_KEY_FORMAT_STRING.format(key))\n if isinstance(value, str):\n raise AttributeError(self._INCORRECT_TYPE_RAW_IS_STRING)\n elif isinstance(value, Number):\n raise AttributeError(self._INCORRECT_TYPE_RAW_IS_NUMBER)\n else:\n self._raws[key] = value\n ", "context": "class Bundle(object):\n def insert_raw(self, key, value): ...\n def __init__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __str__(self): ...\n def to_json(self): ...\n def construct_from_json(bundle_json_string): ...\n def is_valid_key(key): ...\n def merge_from_bundle(self, other_bundle): ...\n def strings(self, key=None): ...\n def numbers(self, key=None): ...\n def raws(self, key=None): ...\n def iterables(self, key=None): ...\n def insert_string(self, key, value): ...\n def insert_number(self, key, value): ...\n def insert_iterable(self, key, value): ...\n\n self._strings = {}\n self._numbers = {}\n self._raws = {}\n self._iterables = {}\n\n _IMPROPER_KEY_FORMAT_STRING = '{} is not properly formatted'\n _INCORRECT_TYPE_STRING = 'Not a string'\n _INCORRECT_TYPE_NUMBER = 'Not a number'\n _INCORRECT_TYPE_ITERABLE = 'Not an iterable'\n _INCORRECT_TYPE_RAW_IS_STRING = 'Not raw data, found string'\n _INCORRECT_TYPE_RAW_IS_NUMBER = 'Not raw data, found number'\n _ERROR_MESSAGES = (_IMPROPER_KEY_FORMAT_STRING, _INCORRECT_TYPE_STRING, _INCORRECT_TYPE_NUMBER, _INCORRECT_TYPE_ITERABLE, _INCORRECT_TYPE_RAW_IS_NUMBER, _INCORRECT_TYPE_RAW_IS_STRING)\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_bundle_valid_raw", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001094.py"} {"focal_file": "jobs/bundle.py", "focal_class": null, "focal_method": "insert_iterable", "tests": "import unittest\n\nclass Test_insert_iterable(unittest.TestCase):\n def test_bundle_insert_iterable(self):\n self._bundle.insert_iterable(self._valid_key, self._valid_iterable)\n self.assertEqual(self._bundle.iterables(self._valid_key), self._valid_iterable)\n\n def test_bundle_insert_non_iterable(self):\n with self.assertRaises(AttributeError):\n self._bundle.insert_iterable(self._valid_key, self._invalid_iterable)\n\n def test_bundle_insert_string_counts_as_iterable(self):\n self._bundle.insert_iterable(self._valid_key, self._valid_iterable)\n self.assertEqual(self._bundle.iterables(self._valid_key), self._valid_iterable)\n", "method_code": " def insert_iterable(self, key, value):\n \"\"\"\n Insert a string value with a given key\n :raises AttributeError: if the key is invalid\n :raises AttributeError: if the value is not an iterable\n :param key: a valid key\n :param value: an iterable\n \"\"\"\n if not Bundle.is_valid_key(key):\n raise AttributeError(self._IMPROPER_KEY_FORMAT_STRING.format(key))\n if isinstance(value, collections.Iterable):\n self._iterables[key] = value\n else:\n raise AttributeError(self._INCORRECT_TYPE_ITERABLE)\n ", "context": "class Bundle(object):\n def insert_iterable(self, key, value): ...\n def __init__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __str__(self): ...\n def to_json(self): ...\n def construct_from_json(bundle_json_string): ...\n def is_valid_key(key): ...\n def merge_from_bundle(self, other_bundle): ...\n def strings(self, key=None): ...\n def numbers(self, key=None): ...\n def raws(self, key=None): ...\n def iterables(self, key=None): ...\n def insert_string(self, key, value): ...\n def insert_number(self, key, value): ...\n def insert_raw(self, key, value): ...\n\n self._strings = {}\n self._numbers = {}\n self._raws = {}\n self._iterables = {}\n\n _IMPROPER_KEY_FORMAT_STRING = '{} is not properly formatted'\n _INCORRECT_TYPE_STRING = 'Not a string'\n _INCORRECT_TYPE_NUMBER = 'Not a number'\n _INCORRECT_TYPE_ITERABLE = 'Not an iterable'\n _INCORRECT_TYPE_RAW_IS_STRING = 'Not raw data, found string'\n _INCORRECT_TYPE_RAW_IS_NUMBER = 'Not raw data, found number'\n _ERROR_MESSAGES = (_IMPROPER_KEY_FORMAT_STRING, _INCORRECT_TYPE_STRING, _INCORRECT_TYPE_NUMBER, _INCORRECT_TYPE_ITERABLE, _INCORRECT_TYPE_RAW_IS_NUMBER, _INCORRECT_TYPE_RAW_IS_STRING)\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_bundle_insert_iterable", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001095.py"} {"focal_file": "jobs/bundle.py", "focal_class": null, "focal_method": "iterables", "tests": "import unittest\n\nclass Test_iterables(unittest.TestCase):\n def test_bundle_update_iterable(self):\n self._bundle.insert_iterable(self._valid_key, self._valid_iterable)\n self.assertEqual(self._bundle.iterables(self._valid_key), self._valid_iterable)\n updated_iterable = self._valid_iterable\n updated_iterable.append('item')\n self._bundle.insert_iterable(self._valid_key, updated_iterable)\n self.assertEqual(self._bundle.iterables(self._valid_key), self._valid_iterable)\n", "method_code": " def iterables(self, key=None):\n \"\"\"\n Accessor for a specific key or the entire iterables dict\n :raises BundleKeyError if the key is not none, is valid, and no key-value pair is found\n :raises AttributeError if the key is invalid\n :param key: optional\n :return: the value in the key-value pair for a given key if not None, or the entire iterables dict\n \"\"\"\n if key is not None and (not Bundle.is_valid_key(key)):\n raise AttributeError(self._IMPROPER_KEY_FORMAT_STRING.format(key))\n if key is not None:\n try:\n return self._iterables[key]\n except KeyError as err:\n raise BundleKeyError(str(err))\n else:\n return self._iterables\n ", "context": "class Bundle(object):\n def iterables(self, key=None): ...\n def __init__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __str__(self): ...\n def to_json(self): ...\n def construct_from_json(bundle_json_string): ...\n def is_valid_key(key): ...\n def merge_from_bundle(self, other_bundle): ...\n def strings(self, key=None): ...\n def numbers(self, key=None): ...\n def raws(self, key=None): ...\n def insert_string(self, key, value): ...\n def insert_number(self, key, value): ...\n def insert_raw(self, key, value): ...\n def insert_iterable(self, key, value): ...\n\n self._strings = {}\n self._numbers = {}\n self._raws = {}\n self._iterables = {}\n\n _IMPROPER_KEY_FORMAT_STRING = '{} is not properly formatted'\n _INCORRECT_TYPE_STRING = 'Not a string'\n _INCORRECT_TYPE_NUMBER = 'Not a number'\n _INCORRECT_TYPE_ITERABLE = 'Not an iterable'\n _INCORRECT_TYPE_RAW_IS_STRING = 'Not raw data, found string'\n _INCORRECT_TYPE_RAW_IS_NUMBER = 'Not raw data, found number'\n _ERROR_MESSAGES = (_IMPROPER_KEY_FORMAT_STRING, _INCORRECT_TYPE_STRING, _INCORRECT_TYPE_NUMBER, _INCORRECT_TYPE_ITERABLE, _INCORRECT_TYPE_RAW_IS_NUMBER, _INCORRECT_TYPE_RAW_IS_STRING)\n", "repository": "UCSB-CS189-2016-17-Aerospace/Aerocube", "test_name": "test_bundle_update_iterable", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001096.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "data_changed", "tests": "import unittest\n\nclass Test_data_changed(unittest.TestCase):\n def test_date_changed(self):\n mock_aju = mock.MagicMock()\n mock_aju.received = {'network_manager': 'nm'}\n self.cr._all_joined_units = mock_aju\n self.cr.data_changed()\n self.set_flag.assert_called_once_with('some-relation.available')\n", "method_code": " def data_changed(self):\n \"\"\"Set flag to indicate to charm relation data has changed.\"\"\"\n if self.all_joined_units.received.get('network_manager'):\n set_flag(self.expand_name('{endpoint_name}.available'))\n ", "context": "class CellRequires(Endpoint):\n @when('endpoint.{endpoint_name}.changed')\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_date_changed", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001097.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "broken", "tests": "import unittest\n\nclass Test_broken(unittest.TestCase):\n def test_broken(self):\n self.cr.broken()\n self.clear_flag.assert_called_once_with('some-relation.available')\n", "method_code": " def broken(self):\n \"\"\"Remove flag to indicate to charm relation has gone..\"\"\"\n clear_flag(self.expand_name('{endpoint_name}.available'))\n ", "context": "class CellRequires(Endpoint):\n @when_not('endpoint.{endpoint_name}.joined')\n def broken(self): ...\n def data_changed(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_broken", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001098.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "joined", "tests": "import unittest\n\nclass Test_joined(unittest.TestCase):\n def test_joined(self):\n self.cr.joined()\n self.set_flag.assert_called_once_with('some-relation.connected')\n", "method_code": " def joined(self):\n \"\"\"Set flag to indicate to charm relation has been joined.\"\"\"\n set_flag(self.expand_name('{endpoint_name}.connected'))\n ", "context": "class CellRequires(Endpoint):\n @when('endpoint.{endpoint_name}.joined')\n def joined(self): ...\n def data_changed(self): ...\n def broken(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_joined", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001099.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "send_cell_data", "tests": "import unittest\n\nclass Test_send_cell_data(unittest.TestCase):\n def test_send_cell_data(self):\n mock_rel1 = _relation_mock()\n mock_rel2 = _relation_mock()\n self.cr._relations = [mock_rel1, mock_rel2]\n self.cr.send_cell_data('cell2', 'rabbitmq-server-cell2', 'mysql-cell2')\n expect = {'amqp-service': 'rabbitmq-server-cell2', 'db-service': 'mysql-cell2', 'cell-name': 'cell2'}\n self.assertEqual(mock_rel1.to_publish_raw, expect)\n self.assertEqual(mock_rel2.to_publish_raw, expect)\n", "method_code": " def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name):\n \"\"\"Send compute nodes data relating to network setup.\n \n :param cell_name: Name of the cell this controller is associated with.\n :type cell_name: str\n :param amqp_svc_name: URL for this cells nova message broker.\n :type amqp_svc_name: str\n :param db_svc_name: URL for this cells nova db.\n :type db_svc_name: str\n \"\"\"\n for relation in self.relations:\n relation.to_publish_raw['amqp-service'] = amqp_svc_name\n relation.to_publish_raw['db-service'] = db_svc_name\n relation.to_publish_raw['cell-name'] = cell_name\n ", "context": "class CellRequires(Endpoint):\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_send_cell_data", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001100.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "get_settings", "tests": "import unittest\n\nclass Test_get_settings(unittest.TestCase):\n def test_get_settings(self):\n mock_aju = mock.MagicMock()\n mock_aju.received = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n self.cr._all_joined_units = mock_aju\n self.assertEqual(self.cr.get_settings(['key1', 'key3']), {'key1': 'value1', 'key3': 'value3'})\n", "method_code": " def get_settings(self, keys):\n \"\"\"Retrieve setting(s) from remote units.\n \n :param keys: List of keys and their vaules to retrieve.\n :type keys: str\n :returns: Requested key value pairs.\n :rtype: dict\n \"\"\"\n settings = {}\n for key in keys:\n settings[key] = self.all_joined_units.received.get(key)\n return settings\n ", "context": "class CellRequires(Endpoint):\n def get_settings(self, keys): ...\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_get_settings", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001101.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "get_console_data", "tests": "import unittest\n\nclass Test_get_console_data(unittest.TestCase):\n def test_get_console_data(self):\n self.setup_rdata()\n self.assertEqual(self.cr.get_console_data(), {'enable_serial_console': True, 'serial_console_base_url': 'http://serialconsole'})\n", "method_code": " def get_console_data(self):\n \"\"\"Retrieve console settings from remote application.\n \n :returns: console settings\n :rtype: dict\n \"\"\"\n return self.get_settings(['enable_serial_console', 'serial_console_base_url'])\n ", "context": "class CellRequires(Endpoint):\n def get_console_data(self): ...\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_get_console_data", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001102.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "get_network_data", "tests": "import unittest\n\nclass Test_get_network_data(unittest.TestCase):\n def test_get_network_data(self):\n self.setup_rdata()\n self.assertEqual(self.cr.get_network_data(), {'network_manager': 'vTRManager', 'quantum_plugin': 'vTokenRing', 'quantum_security_groups': 'no', 'quantum_url': 'http://bob:345/dddd/'})\n", "method_code": " def get_network_data(self):\n \"\"\"Retrieve network settings from remote application.\n \n :returns: network settings\n :rtype: dict\n \"\"\"\n return self.get_settings(['network_manager', 'quantum_plugin', 'quantum_security_groups', 'quantum_url'])\n ", "context": "class CellRequires(Endpoint):\n def get_network_data(self): ...\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_get_network_data", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001103.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "get_region", "tests": "import unittest\n\nclass Test_get_region(unittest.TestCase):\n def test_get_region(self):\n self.setup_rdata()\n self.assertEqual(self.cr.get_region(), {'region': 'Region12'})\n", "method_code": " def get_region(self):\n \"\"\"Retrieve region settings from remote application.\n \n :returns: region settings\n :rtype: dict\n \"\"\"\n return self.get_settings(['region'])\n ", "context": "class CellRequires(Endpoint):\n def get_region(self): ...\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_get_region", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001104.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "get_volume_data", "tests": "import unittest\n\nclass Test_get_volume_data(unittest.TestCase):\n def test_get_volume_data(self):\n self.setup_rdata()\n self.assertEqual(self.cr.get_volume_data(), {'volume_service': 'cinder'})\n", "method_code": " def get_volume_data(self):\n \"\"\"Retrieve volume settings from remote application.\n \n :returns: volume settings\n :rtype: dict\n \"\"\"\n return self.get_settings(['volume_service'])\n ", "context": "class CellRequires(Endpoint):\n def get_volume_data(self): ...\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_ec2_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_get_volume_data", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001105.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "get_ec2_data", "tests": "import unittest\n\nclass Test_get_ec2_data(unittest.TestCase):\n def test_get_ec2_data(self):\n self.setup_rdata()\n self.assertEqual(self.cr.get_ec2_data(), {'ec2_host': 'http://ec2host'})\n", "method_code": " def get_ec2_data(self):\n \"\"\"Retrieve ec2 settings from remote application.\n \n :returns: ec2 settings\n :rtype: dict\n \"\"\"\n return self.get_settings(['ec2_host'])\n ", "context": "class CellRequires(Endpoint):\n def get_ec2_data(self): ...\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_restart_trigger(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_get_ec2_data", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001106.py"} {"focal_file": "requires.py", "focal_class": null, "focal_method": "get_restart_trigger", "tests": "import unittest\n\nclass Test_get_restart_trigger(unittest.TestCase):\n def test_get_restart_trigger(self):\n self.setup_rdata()\n self.assertEqual(self.cr.get_restart_trigger(), {'restart_trigger': 'a-uuid'})\n", "method_code": " def get_restart_trigger(self):\n \"\"\"Retrieve restart trigger from remote application.\n \n :returns: restart trigger\n :rtype: dict\n \"\"\"\n return self.get_settings(['restart_trigger'])\n ", "context": "class CellRequires(Endpoint):\n def get_restart_trigger(self): ...\n def data_changed(self): ...\n def broken(self): ...\n def joined(self): ...\n def send_cell_data(self, cell_name, amqp_svc_name, db_svc_name): ...\n def get_settings(self, keys): ...\n def get_console_data(self): ...\n def get_network_data(self): ...\n def get_region(self): ...\n def get_volume_data(self): ...\n def get_ec2_data(self): ...\n", "repository": "openstack/charm-interface-nova-cell", "test_name": "test_get_restart_trigger", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001107.py"} {"focal_file": "artiq/wavesynth/coefficients.py", "focal_class": null, "focal_method": "get_segment_data", "tests": "import unittest\n\nclass Test_get_segment_data(unittest.TestCase):\n def test_get_segment(self):\n return list(self.s.get_segment_data(start=1.5, stop=3.2, scale=0.01))\n", "method_code": " def get_segment_data(self, start, stop, scale, *, cutoff=1e-12, target='bias', variable='amplitude'):\n \"\"\"Build wavesynth segment data.\n \n :param start: see `crop_x()`.\n :param stop: see `crop_x()`.\n :param scale: see `scale_x()`.\n :param cutoff: coefficient cutoff towards zero to compress data.\n \"\"\"\n x = self.crop_x(start, stop)\n x_sample, durations = self.scale_x(x, scale)\n coefficients = self(x_sample)\n if len(x_sample) == 1 and start == stop:\n coefficients = coefficients[:1]\n coefficients *= (scale * np.sign(durations)) ** np.arange(coefficients.shape[0])[:, None, None]\n if cutoff:\n coefficients[np.fabs(coefficients) < cutoff] = 0\n return build_segment(durations, coefficients, target=target, variable=variable)\n ", "context": "class CoefficientSource():\n def get_segment_data(self, start, stop, scale, *, cutoff=1e-12, target='bias', variable='amplitude'): ...\n def crop_x(self, start, stop, num=2): ...\n def scale_x(self, x, scale): ...\n def __call__(self, x, **kwargs): ...\n def extend_segment(self, segment, trigger=True, *args, **kwargs): ...\n", "repository": "kgilmo/penning_artiq", "test_name": "test_get_segment", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001108.py"} {"focal_file": "artiq/devices/lda/driver.py", "focal_class": null, "focal_method": "set_attenuation", "tests": "import unittest\n\nclass Test_set_attenuation(unittest.TestCase):\n def test_attenuation(self):\n step = self.cont.get_att_step_size()\n attmax = self.cont.get_att_max()\n test_vector = [i * step * dB for i in range(0, int(attmax * int(1 / step) + 1))]\n for i in test_vector:\n with self.subTest(i=i):\n self.cont.set_attenuation(i)\n self.assertEqual(i, self.cont.get_attenuation())\n", "method_code": " def set_attenuation(self, attenuation):\n \"\"\"Stores the new attenuation value.\n \n :param attenuation: The attenuation value in dB.\n \"\"\"\n step = self.get_att_step_size()\n att = round(attenuation / step) * step\n if att > self.get_att_max():\n raise ValueError('Cannot set attenuation {} > {}'.format(att, self.get_att_max()))\n elif att < 0 * dB:\n raise ValueError('Cannot set attenuation {} < 0'.format(att))\n else:\n att = round(att * 4) / 4.0 * dB\n self._attenuation = att\n ", "context": "class Ldasim():\n def set_attenuation(self, attenuation): ...\n def __init__(self): ...\n def get_att_max(self): ...\n def get_att_step_size(self): ...\n def close(self): ...\n def get_attenuation(self): ...\n def ping(self): ...\n\n self._attenuation = None\n self._att_max = 63 * dB\n self._att_step_size = 0.25 * dB\n", "repository": "kgilmo/penning_artiq", "test_name": "test_attenuation", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001109.py"} {"focal_file": "artiq/devices/pdq2/driver.py", "focal_class": null, "focal_method": "program", "tests": "import unittest\n\nclass Test_program(unittest.TestCase):\n def test_program(self):\n self.dev.program(_test_program)\n\n def test_cmd_program(self):\n self.dev.cmd('ARM', False)\n self.dev.cmd('START', False)\n self.dev.program(_test_program)\n self.dev.cmd('START', True)\n self.dev.cmd('ARM', True)\n return self.dev.dev.getvalue()\n", "method_code": " def program(self, program):\n self.clear_all()\n for frame_data in program:\n self.program_frame(frame_data)\n self.write_all()\n ", "context": "class Pdq2():\n def program(self, program): ...\n def __init__(self, url=None, dev=None, num_boards=3): ...\n def close(self): ...\n def clear_all(self): ...\n def write(self, data): ...\n def cmd(self, cmd, enable): ...\n def write_mem(self, channel, data, start_addr=0): ...\n def write_channel(self, channel): ...\n def write_all(self): ...\n def write_table(self, channel): ...\n def write_segment(self, channel, segment): ...\n def program_frame(self, frame_data): ...\n def ping(self): ...\n\n self.dev = dev\n self.num_boards = num_boards\n self.num_channels = self.num_dacs * self.num_boards\n self.channels = [Channel() for i in range(self.num_channels)]\n\n num_dacs = 3\n _escape = b'\\xa5'\n _commands = 'RESET TRIGGER ARM DCM START'.split()\n", "repository": "kgilmo/penning_artiq", "test_name": "test_program", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001110.py"} {"focal_file": "artiq/devices/pxi6733/driver.py", "focal_class": null, "focal_method": "load_sample_values", "tests": "import unittest\n\nclass Test_load_sample_values(unittest.TestCase):\n def test_load_sample_values(self):\n test_vector = np.array([1.0, 2.0, 3.0, 4.0], dtype=float)\n self.cont.load_sample_values(test_vector)\n", "method_code": " def load_sample_values(self, values):\n pass\n ", "context": "class DAQmxSim():\n def load_sample_values(self, values): ...\n def close(self): ...\n def ping(self): ...\n", "repository": "kgilmo/penning_artiq", "test_name": "test_load_sample_values", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001111.py"} {"focal_file": "artiq/devices/pxi6733/driver.py", "focal_class": null, "focal_method": "close", "tests": "import unittest\n\nclass Test_close(unittest.TestCase):\n def test_close_1(self):\n self.cont.close()\n\n def test_close_2(self):\n test_vector = np.array([1.0, 2.0, 3.0, 4.0], dtype=float)\n self.cont.load_sample_values(test_vector)\n self.cont.close()\n", "method_code": " def close(self):\n pass\n ", "context": "class DAQmxSim():\n def close(self): ...\n def load_sample_values(self, values): ...\n def ping(self): ...\n", "repository": "kgilmo/penning_artiq", "test_name": "test_close_1", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001112.py"} {"focal_file": "packages/cherrypy/lib/httputil.py", "focal_class": null, "focal_method": "urljoin", "tests": "import unittest\n\nclass Test_urljoin(unittest.TestCase):\n def test_urljoin(self):\n self.assertEqual(httputil.urljoin('/sn/', '/pi/'), '/sn/pi/')\n self.assertEqual(httputil.urljoin('/sn/', '/pi'), '/sn/pi')\n self.assertEqual(httputil.urljoin('/sn/', '/'), '/sn/')\n self.assertEqual(httputil.urljoin('/sn/', ''), '/sn/')\n self.assertEqual(httputil.urljoin('/sn', '/pi/'), '/sn/pi/')\n self.assertEqual(httputil.urljoin('/sn', '/pi'), '/sn/pi')\n self.assertEqual(httputil.urljoin('/sn', '/'), '/sn/')\n self.assertEqual(httputil.urljoin('/sn', ''), '/sn')\n self.assertEqual(httputil.urljoin('/', '/pi/'), '/pi/')\n self.assertEqual(httputil.urljoin('/', '/pi'), '/pi')\n self.assertEqual(httputil.urljoin('/', '/'), '/')\n self.assertEqual(httputil.urljoin('/', ''), '/')\n self.assertEqual(httputil.urljoin('', '/pi/'), '/pi/')\n self.assertEqual(httputil.urljoin('', '/pi'), '/pi')\n self.assertEqual(httputil.urljoin('', '/'), '/')\n self.assertEqual(httputil.urljoin('', ''), '/')\n", "method_code": "def urljoin(*atoms):\n \"\"\"Return the given path \\\\*atoms, joined into a single URL.\n\n This will correctly join a SCRIPT_NAME and PATH_INFO into the\n original URL, even if either atom is blank.\n \"\"\"\n url = '/'.join([x for x in atoms if x])\n while '//' in url:\n url = url.replace('//', '/')\n return url or '/'", "context": "def urljoin(*atoms): ...\ndef urljoin(*atoms): ...\ndef urljoin_bytes(*atoms): ...\ndef protocol_from_http(protocol_str): ...\ndef get_ranges(headervalue, content_length): ...\ndef header_elements(fieldname, fieldvalue): ...\ndef decode_TEXT(value): ...\ndef valid_status(status): ...\ndef _parse_qs(qs, keep_blank_values=0, strict_parsing=0, encoding='utf-8'): ...\ndef parse_query_string(query_string, keep_blank_values=True, encoding='utf-8'): ...\n", "repository": "craighiller/hackfsm", "test_name": "test_urljoin", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001113.py"} {"focal_file": "packages/cherrypy/process/servers.py", "focal_class": null, "focal_method": "start", "tests": "import unittest\n\nclass Test_start(unittest.TestCase):\n def test_1_Restart(self):\n cherrypy.server.start()\n engine.start()\n self.assertEqual(db_connection.running, True)\n grace = db_connection.gracecount\n self.getPage('/')\n self.assertBody('Hello World')\n self.assertEqual(len(db_connection.threads), 1)\n engine.graceful()\n self.assertEqual(engine.state, engine.states.STARTED)\n self.getPage('/')\n self.assertBody('Hello World')\n self.assertEqual(db_connection.running, True)\n self.assertEqual(db_connection.gracecount, grace + 1)\n self.assertEqual(len(db_connection.threads), 1)\n self.getPage('/graceful')\n self.assertEqual(engine.state, engine.states.STARTED)\n self.assertBody('app was (gracefully) restarted succesfully')\n self.assertEqual(db_connection.running, True)\n self.assertEqual(db_connection.gracecount, grace + 2)\n self.assertEqual(len(db_connection.threads), 0)\n engine.stop()\n self.assertEqual(engine.state, engine.states.STOPPED)\n self.assertEqual(db_connection.running, False)\n self.assertEqual(len(db_connection.threads), 0)\n", "method_code": " def start(self):\n \"\"\"Start the HTTP server.\"\"\"\n if self.bind_addr is None:\n on_what = 'unknown interface (dynamic?)'\n elif isinstance(self.bind_addr, tuple):\n host, port = self.bind_addr\n on_what = '%s:%s' % (host, port)\n else:\n on_what = 'socket file: %s' % self.bind_addr\n if self.running:\n self.bus.log('Already serving on %s' % on_what)\n return\n self.interrupt = None\n if not self.httpserver:\n raise ValueError('No HTTP server has been created.')\n if isinstance(self.bind_addr, tuple):\n wait_for_free_port(*self.bind_addr)\n import threading\n t = threading.Thread(target=self._start_http_thread)\n t.setName('HTTPServer ' + t.getName())\n t.start()\n self.wait()\n self.running = True\n self.bus.log('Serving on %s' % on_what)\n ", "context": "class ServerAdapter(object):\n def start(self): ...\n def __init__(self, bus, httpserver=None, bind_addr=None): ...\n def subscribe(self): ...\n def unsubscribe(self): ...\n def _start_http_thread(self): ...\n def wait(self): ...\n def stop(self): ...\n def restart(self): ...\n\n self.bus = bus\n self.httpserver = httpserver\n self.bind_addr = bind_addr\n self.interrupt = None\n self.running = False\n\n start.priority = 75\n stop.priority = 25\n", "repository": "craighiller/hackfsm", "test_name": "test_1_Restart", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001114.py"} {"focal_file": "packages/cherrypy/process/servers.py", "focal_class": null, "focal_method": "wait_for_occupied_port", "tests": "import unittest\n\nclass Test_wait_for_occupied_port(unittest.TestCase):\n def test_wait_for_occupied_port_INADDR_ANY(self):\n \"\"\"\n Wait on INADDR_ANY should not raise IOError\n\n In cases where the loopback interface does not exist, CherryPy cannot\n effectively determine if a port binding to INADDR_ANY was effected.\n In this situation, CherryPy should assume that it failed to detect\n the binding (not that the binding failed) and only warn that it could\n not verify it.\n \"\"\"\n free_port = self.find_free_port()\n servers = cherrypy.process.servers\n\n def with_shorter_timeouts(func):\n \"\"\"\n A context where occupied_port_timeout is much smaller to speed\n test runs.\n \"\"\"\n orig_timeout = servers.occupied_port_timeout\n servers.occupied_port_timeout = 0.07\n try:\n func()\n finally:\n servers.occupied_port_timeout = orig_timeout\n\n def do_waiting():\n servers.wait_for_occupied_port('0.0.0.0', free_port)\n self.assertRaises(IOError, servers.wait_for_occupied_port, '127.0.0.1', free_port)\n with_shorter_timeouts(do_waiting)\n", "method_code": "def wait_for_occupied_port(host, port, timeout=None):\n \"\"\"Wait for the specified port to become active (receive requests).\"\"\"\n if not host:\n raise ValueError(\"Host values of '' or None are not allowed.\")\n if timeout is None:\n timeout = occupied_port_timeout\n for trial in range(50):\n try:\n check_port(host, port, timeout=timeout)\n except IOError:\n return\n else:\n time.sleep(timeout)\n if host == client_host(host):\n raise IOError('Port %r not bound on %r' % (port, host))\n msg = 'Unable to verify that the server is bound on %r' % port\n warnings.warn(msg)", "context": "def wait_for_occupied_port(host, port, timeout=None): ...\ndef client_host(server_host): ...\ndef check_port(host, port, timeout=1.0): ...\ndef wait_for_free_port(host, port, timeout=None): ...\ndef wait_for_occupied_port(host, port, timeout=None): ...\n", "repository": "craighiller/hackfsm", "test_name": "test_wait_for_occupied_port_INADDR_ANY", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001115.py"} {"focal_file": "packages/cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "start", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_start(unittest.TestCase):\n def test_start(self):\n b = wspbus.Bus()\n self.log(b)\n self.responses = []\n num = 3\n for index in range(num):\n b.subscribe('start', self.get_listener('start', index))\n b.start()\n try:\n self.assertEqual(set(self.responses), set([msg % (i, 'start', None) for i in range(num)]))\n self.assertEqual(b.state, b.states.STARTED)\n self.assertLog(['Bus STARTING', 'Bus STARTED'])\n finally:\n b.exit()\n", "method_code": " def start(self):\n \"\"\"Start all services.\"\"\"\n atexit.register(self._clean_exit)\n self.state = states.STARTING\n self.log('Bus STARTING')\n try:\n self.publish('start')\n self.state = states.STARTED\n self.log('Bus STARTED')\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n self.log('Shutting down due to error in start listener:', level=40, traceback=True)\n e_info = sys.exc_info()[1]\n try:\n self.exit()\n except:\n pass\n raise e_info\n ", "context": "class Bus(object):\n def start(self): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "craighiller/hackfsm", "test_name": "test_start", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001116.py"} {"focal_file": "packages/cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "stop", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_stop(unittest.TestCase):\n def test_stop(self):\n b = wspbus.Bus()\n self.log(b)\n self.responses = []\n num = 3\n for index in range(num):\n b.subscribe('stop', self.get_listener('stop', index))\n b.stop()\n self.assertEqual(set(self.responses), set([msg % (i, 'stop', None) for i in range(num)]))\n self.assertEqual(b.state, b.states.STOPPED)\n self.assertLog(['Bus STOPPING', 'Bus STOPPED'])\n", "method_code": " def stop(self):\n \"\"\"Stop all services.\"\"\"\n self.state = states.STOPPING\n self.log('Bus STOPPING')\n self.publish('stop')\n self.state = states.STOPPED\n self.log('Bus STOPPED')\n ", "context": "class Bus(object):\n def stop(self): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "craighiller/hackfsm", "test_name": "test_stop", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001117.py"} {"focal_file": "packages/cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "graceful", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_graceful(unittest.TestCase):\n def test_graceful(self):\n b = wspbus.Bus()\n self.log(b)\n self.responses = []\n num = 3\n for index in range(num):\n b.subscribe('graceful', self.get_listener('graceful', index))\n b.graceful()\n self.assertEqual(set(self.responses), set([msg % (i, 'graceful', None) for i in range(num)]))\n self.assertLog(['Bus graceful'])\n", "method_code": " def graceful(self):\n \"\"\"Advise all services to reload.\"\"\"\n self.log('Bus graceful')\n self.publish('graceful')\n ", "context": "class Bus(object):\n def graceful(self): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "craighiller/hackfsm", "test_name": "test_graceful", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001118.py"} {"focal_file": "packages/cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "exit", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_exit(unittest.TestCase):\n def test_exit(self):\n b = wspbus.Bus()\n self.log(b)\n self.responses = []\n num = 3\n for index in range(num):\n b.subscribe('stop', self.get_listener('stop', index))\n b.subscribe('exit', self.get_listener('exit', index))\n b.exit()\n self.assertEqual(set(self.responses), set([msg % (i, 'stop', None) for i in range(num)] + [msg % (i, 'exit', None) for i in range(num)]))\n self.assertEqual(b.state, b.states.EXITING)\n self.assertLog(['Bus STOPPING', 'Bus STOPPED', 'Bus EXITING', 'Bus EXITED'])\n", "method_code": " def exit(self):\n \"\"\"Stop all services and prepare to exit the process.\"\"\"\n exitstate = self.state\n try:\n self.stop()\n self.state = states.EXITING\n self.log('Bus EXITING')\n self.publish('exit')\n self.log('Bus EXITED')\n except:\n os._exit(70)\n if exitstate == states.STARTING:\n os._exit(70)\n ", "context": "class Bus(object):\n def exit(self): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "craighiller/hackfsm", "test_name": "test_exit", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001119.py"} {"focal_file": "packages/cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "wait", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_wait(unittest.TestCase):\n def test_wait(self):\n b = wspbus.Bus()\n\n def f(method):\n time.sleep(0.2)\n getattr(b, method)()\n for method, states in [('start', [b.states.STARTED]), ('stop', [b.states.STOPPED]), ('start', [b.states.STARTING, b.states.STARTED]), ('exit', [b.states.EXITING])]:\n threading.Thread(target=f, args=(method,)).start()\n b.wait(states)\n if b.state not in states:\n self.fail('State %r not in %r' % (b.state, states))\n", "method_code": " def wait(self, state, interval=0.1, channel=None):\n \"\"\"Poll for the given state(s) at intervals; publish to channel.\"\"\"\n if isinstance(state, (tuple, list)):\n states = state\n else:\n states = [state]\n \n def _wait():\n while self.state not in states:\n time.sleep(interval)\n self.publish(channel)\n try:\n sys.modules['psyco'].cannotcompile(_wait)\n except (KeyError, AttributeError):\n pass\n _wait()\n ", "context": "class Bus(object):\n def wait(self, state, interval=0.1, channel=None): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "craighiller/hackfsm", "test_name": "test_wait", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001120.py"} {"focal_file": "packages/cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "block", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_block(unittest.TestCase):\n def test_block(self):\n b = wspbus.Bus()\n self.log(b)\n\n def f():\n time.sleep(0.2)\n b.exit()\n\n def g():\n time.sleep(0.4)\n threading.Thread(target=f).start()\n threading.Thread(target=g).start()\n threads = [t for t in threading.enumerate() if not get_daemon(t)]\n self.assertEqual(len(threads), 3)\n b.block()\n self.assertEqual(b.state, b.states.EXITING)\n threads = [t for t in threading.enumerate() if not get_daemon(t)]\n self.assertEqual(len(threads), 1)\n self.assertEqual(self._log_entries[:-1], ['Bus STOPPING', 'Bus STOPPED', 'Bus EXITING', 'Bus EXITED', 'Waiting for child threads to terminate...'])\n", "method_code": " def block(self, interval=0.1):\n \"\"\"Wait for the EXITING state, KeyboardInterrupt or SystemExit.\n \n This function is intended to be called only by the main thread.\n After waiting for the EXITING state, it also waits for all threads\n to terminate, and then calls os.execv if self.execv is True. This\n design allows another thread to call bus.restart, yet have the main\n thread perform the actual execv call (required on some platforms).\n \"\"\"\n try:\n self.wait(states.EXITING, interval=interval, channel='main')\n except (KeyboardInterrupt, IOError):\n self.log('Keyboard Interrupt: shutting down bus')\n self.exit()\n except SystemExit:\n self.log('SystemExit raised: shutting down bus')\n self.exit()\n raise\n self.log('Waiting for child threads to terminate...')\n for t in threading.enumerate():\n if t != threading.currentThread() and t.isAlive():\n if hasattr(threading.Thread, 'daemon'):\n d = t.daemon\n else:\n d = t.isDaemon()\n if not d:\n self.log('Waiting for thread %s.' % t.getName())\n t.join()\n if self.execv:\n self._do_execv()\n ", "context": "class Bus(object):\n def block(self, interval=0.1): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "craighiller/hackfsm", "test_name": "test_block", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001121.py"} {"focal_file": "packages/cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "start_with_callback", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_start_with_callback(unittest.TestCase):\n def test_start_with_callback(self):\n b = wspbus.Bus()\n self.log(b)\n try:\n events = []\n\n def f(*args, **kwargs):\n events.append(('f', args, kwargs))\n\n def g():\n events.append('g')\n b.subscribe('start', g)\n b.start_with_callback(f, (1, 3, 5), {'foo': 'bar'})\n time.sleep(0.2)\n self.assertEqual(b.state, b.states.STARTED)\n self.assertEqual(events, ['g', ('f', (1, 3, 5), {'foo': 'bar'})])\n finally:\n b.exit()\n", "method_code": " def start_with_callback(self, func, args=None, kwargs=None):\n \"\"\"Start 'func' in a new thread T, then start self (and return T).\"\"\"\n if args is None:\n args = ()\n if kwargs is None:\n kwargs = {}\n args = (func,) + args\n \n def _callback(func, *a, **kw):\n self.wait(states.STARTED)\n func(*a, **kw)\n t = threading.Thread(target=_callback, args=args, kwargs=kwargs)\n t.setName('Bus Callback ' + t.getName())\n t.start()\n self.start()\n return t\n ", "context": "class Bus(object):\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "craighiller/hackfsm", "test_name": "test_start_with_callback", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001122.py"} {"focal_file": "packages/cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "log", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_log(unittest.TestCase):\n def test_log(self):\n b = wspbus.Bus()\n self.log(b)\n self.assertLog([])\n expected = []\n for msg in [\"O mah darlin'\"] * 3 + ['Clementiiiiiiiine']:\n b.log(msg)\n expected.append(msg)\n self.assertLog(expected)\n try:\n foo\n except NameError:\n b.log('You are lost and gone forever', traceback=True)\n lastmsg = self._log_entries[-1]\n if 'Traceback' not in lastmsg or 'NameError' not in lastmsg:\n self.fail('Last log message %r did not contain the expected traceback.' % lastmsg)\n else:\n self.fail('NameError was not raised as expected.')\n", "method_code": " def log(self, msg='', level=20, traceback=False):\n \"\"\"Log the given message. Append the last traceback if requested.\"\"\"\n if traceback:\n msg += '\\n' + ''.join(_traceback.format_exception(*sys.exc_info()))\n self.publish('log', msg, level)\n ", "context": "class Bus(object):\n def log(self, msg='', level=20, traceback=False): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "craighiller/hackfsm", "test_name": "test_log", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001123.py"} {"focal_file": "src/charm.py", "focal_class": null, "focal_method": "_on_database_master_changed", "tests": "import unittest\n\nclass Test_on_database_master_changed(unittest.TestCase):\n @mock.patch('charm.HelloJujuCharm._render_settings_file')\n @mock.patch('charm.HelloJujuCharm._create_database_tables')\n @mock.patch('charm.check_call')\n @mock.patch('pgsql.opslib.pgsql.client._leader_get')\n @mock.patch('pgsql.opslib.pgsql.client._leader_set')\n def test_on_database_master_changed(self, _leader_set, _leader_get, _call, _createdb, _render):\n _leader_get.return_value = {}\n _leader_set.return_value = None\n self.harness.set_leader(True)\n relation = self.harness.add_relation('db', 'postgresql')\n self.harness.add_relation_unit(relation, 'postgresql/0')\n test_event = Mock()\n test_event.database = 'hello-juju'\n test_event.master.uri = 'postgresql://TEST'\n self.harness.charm._on_database_master_changed(test_event)\n self.assertEqual(self.harness.charm._stored.conn_str, 'postgresql+pg8000://TEST')\n _render.assert_called_once()\n _createdb.assert_called_once()\n _call.assert_called_with(['systemctl', 'restart', 'hello-juju'])\n self.assertEqual(self.harness.charm.unit.status, ActiveStatus())\n _render.reset_mock()\n test_event = Mock()\n self.harness.charm._on_database_master_changed(test_event)\n _render.assert_not_called()\n _call.reset_mock()\n test_event = Mock()\n test_event.database = 'hello-juju'\n test_event.master = None\n self.harness.charm._on_database_master_changed(test_event)\n _call.assert_not_called()\n", "method_code": " def _on_database_master_changed(self, event):\n \"\"\"Handler the case where a new PostgreSQL DB master is available\"\"\"\n if event.database != self.app.name:\n return\n if event.master:\n self.unit.status = MaintenanceStatus('configuring database settings')\n self._stored.conn_str = event.master.uri.replace('postgresql://', 'postgresql+pg8000://')\n self._render_settings_file()\n self._create_database_tables()\n check_call(['systemctl', 'restart', 'hello-juju'])\n self.unit.status = ActiveStatus()\n else:\n event.defer()\n return\n ", "context": "class HelloJujuCharm(CharmBase):\n def _on_database_master_changed(self, event): ...\n def __init__(self, *args): ...\n def _on_install(self, _): ...\n def _on_start(self, _): ...\n def _on_config_changed(self, _): ...\n def _on_database_relation_joined(self, event): ...\n def _setup_application(self): ...\n def _install_apt_packages(self, packages: list): ...\n def _render_systemd_unit(self): ...\n def _render_settings_file(self): ...\n def _create_database_tables(self): ...\n\n self.db = pgsql.PostgreSQLClient(self, 'db')\n\n _stored = StoredState()\n", "repository": "juju/hello-juju-charm", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001124.py"} {"focal_file": "src/charm.py", "focal_class": null, "focal_method": "_create_database_tables", "tests": "import unittest\n\nclass Test_create_database_tables(unittest.TestCase):\n @mock.patch('subprocess.call')\n def test_create_database_tables(self, _mock):\n args = ['sudo', '-u', 'www-data', f'{VENV_ROOT}/bin/python3', f'{APP_PATH}/init.py']\n _mock.return_value = 0\n self.harness.charm._create_database_tables()\n _mock.assert_called_once_with(args)\n self.assertEqual(self.harness.charm.unit.status, MaintenanceStatus('creating database tables'))\n", "method_code": " def _create_database_tables(self):\n \"\"\"Initialise the database and populate with initial tables required\"\"\"\n self.unit.status = MaintenanceStatus('creating database tables')\n check_call(['sudo', '-u', 'www-data', f'{VENV_ROOT}/bin/python3', f'{APP_PATH}/init.py'])\n ", "context": "class HelloJujuCharm(CharmBase):\n def _create_database_tables(self): ...\n def __init__(self, *args): ...\n def _on_install(self, _): ...\n def _on_start(self, _): ...\n def _on_config_changed(self, _): ...\n def _on_database_relation_joined(self, event): ...\n def _on_database_master_changed(self, event): ...\n def _setup_application(self): ...\n def _install_apt_packages(self, packages: list): ...\n def _render_systemd_unit(self): ...\n def _render_settings_file(self): ...\n\n self.db = pgsql.PostgreSQLClient(self, 'db')\n\n _stored = StoredState()\n", "repository": "juju/hello-juju-charm", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001125.py"} {"focal_file": "src/charm.py", "focal_class": null, "focal_method": "_render_settings_file", "tests": "import unittest\n\nclass Test_render_settings_file(unittest.TestCase):\n @mock.patch('os.chmod')\n @mock.patch('os.chown')\n @mock.patch('pwd.getpwnam')\n def test_render_settings_file(self, _pwnam, _chown, _chmod):\n self.harness.charm._stored.conn_str = 'postgresql://test_connection_string'\n with open('templates/settings.py.j2', 'r') as f:\n m = mock_open(read_data=f.read())\n with patch('builtins.open', m, create=True):\n _pwnam.return_value.pw_uid = 35\n _pwnam.return_value.pw_gid = 35\n self.harness.charm._render_settings_file()\n self.assertEqual(m.call_args_list[0][0], ('templates/settings.py.j2', 'r'))\n self.assertEqual(m.call_args_list[1][0], (f'{APP_PATH}/settings.py', 'w+'))\n m.return_value.write.assert_called_with(RENDERED_SETTINGS)\n _pwnam.assert_called_with('www-data')\n _chmod.assert_called_with(f'{APP_PATH}/settings.py', 420)\n _chown.assert_called_with(f'{APP_PATH}/settings.py', uid=35, gid=35)\n", "method_code": " def _render_settings_file(self):\n \"\"\"Render the application settings file with database connection details\"\"\"\n with open('templates/settings.py.j2', 'r') as t:\n template = Template(t.read())\n rendered = template.render(conn_str=self._stored.conn_str)\n with open(f'{APP_PATH}/settings.py', 'w+') as t:\n t.write(rendered)\n os.chmod(f'{APP_PATH}/settings.py', 420)\n u = pwd.getpwnam('www-data')\n os.chown(f'{APP_PATH}/settings.py', uid=u.pw_uid, gid=u.pw_gid)\n ", "context": "class HelloJujuCharm(CharmBase):\n def _render_settings_file(self): ...\n def __init__(self, *args): ...\n def _on_install(self, _): ...\n def _on_start(self, _): ...\n def _on_config_changed(self, _): ...\n def _on_database_relation_joined(self, event): ...\n def _on_database_master_changed(self, event): ...\n def _setup_application(self): ...\n def _install_apt_packages(self, packages: list): ...\n def _render_systemd_unit(self): ...\n def _create_database_tables(self): ...\n\n self.db = pgsql.PostgreSQLClient(self, 'db')\n\n _stored = StoredState()\n", "repository": "juju/hello-juju-charm", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001126.py"} {"focal_file": "src/charm.py", "focal_class": null, "focal_method": "_render_systemd_unit", "tests": "import unittest\n\nclass Test_render_systemd_unit(unittest.TestCase):\n @mock.patch('charm.check_call')\n @mock.patch('os.chmod')\n def test_render_systemd_unit(self, _chmod, _call):\n with open('templates/hello-juju.service.j2', 'r') as f:\n m = mock_open(read_data=f.read())\n with patch('builtins.open', m, create=True):\n self.harness.charm._stored.port = ''\n _call.return_value = 0\n self.harness.charm._render_systemd_unit()\n self.assertEqual(UNIT_PATH, Path('/etc/systemd/system/hello-juju.service'))\n self.assertEqual(self.harness.charm._stored.port, self.harness.charm.config['port'])\n self.assertEqual(m.call_args_list[0][0], ('templates/hello-juju.service.j2', 'r'))\n self.assertEqual(m.call_args_list[1][0], (UNIT_PATH, 'w+'))\n m.return_value.write.assert_called_with(RENDERED_SYSTEMD_UNIT)\n _chmod.assert_called_with(UNIT_PATH, 493)\n _call.assert_called_with(['systemctl', 'daemon-reload'])\n with patch('builtins.open', m, create=True):\n self.harness.charm._stored.port = 8080\n _call.return_value = 0\n self.harness.charm._render_systemd_unit()\n m.return_value.write.assert_called_with(RENDERED_SYSTEMD_UNIT.replace(':80', ':8080'))\n self.assertEqual(self.harness.charm._stored.port, 8080)\n", "method_code": " def _render_systemd_unit(self):\n \"\"\"Render the systemd unit for Gunicorn to a file\"\"\"\n with open('templates/hello-juju.service.j2', 'r') as t:\n template = Template(t.read())\n if not self._stored.port:\n self._stored.port = self.config['port']\n rendered = template.render(port=self._stored.port, project_root=APP_PATH, user='www-data', group='www-data')\n with open(UNIT_PATH, 'w+') as t:\n t.write(rendered)\n os.chmod(UNIT_PATH, 493)\n check_call(['systemctl', 'daemon-reload'])\n ", "context": "class HelloJujuCharm(CharmBase):\n def _render_systemd_unit(self): ...\n def __init__(self, *args): ...\n def _on_install(self, _): ...\n def _on_start(self, _): ...\n def _on_config_changed(self, _): ...\n def _on_database_relation_joined(self, event): ...\n def _on_database_master_changed(self, event): ...\n def _setup_application(self): ...\n def _install_apt_packages(self, packages: list): ...\n def _render_settings_file(self): ...\n def _create_database_tables(self): ...\n\n self.db = pgsql.PostgreSQLClient(self, 'db')\n\n _stored = StoredState()\n", "repository": "juju/hello-juju-charm", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001127.py"} {"focal_file": "src/charm.py", "focal_class": null, "focal_method": "_install_apt_packages", "tests": "import unittest\n\nclass Test_install_apt_packages(unittest.TestCase):\n @mock.patch('charm.check_output')\n def test_install_apt_packages(self, _call: Mock):\n _call.return_code = 0\n self.harness.charm._install_apt_packages(['curl', 'vim'])\n self.assertEqual(_call.call_args_list, [call(['apt-get', 'update']), call(['apt-get', 'install', '-y', 'curl', 'vim'])])\n _call.reset_mock()\n _call.return_value = 1\n _call.side_effect = subprocess.CalledProcessError(1, 'apt')\n self.harness.charm._install_apt_packages(['curl', 'vim'])\n self.assertEqual(self.harness.charm.unit.status, BlockedStatus('Failed to install packages'))\n", "method_code": " def _install_apt_packages(self, packages: list):\n \"\"\"Simple wrapper around 'apt-get install -y\"\"\"\n try:\n logger.debug('updating apt cache')\n check_output(['apt-get', 'update'])\n logger.debug('installing apt packages: %s', ', '.join(packages))\n check_output(['apt-get', 'install', '-y'] + packages)\n except CalledProcessError as e:\n logger.error('failed to install packages: %s', ', '.join(packages))\n logger.debug('apt error: %s', e.output)\n self.unit.status = BlockedStatus('Failed to install packages')\n ", "context": "class HelloJujuCharm(CharmBase):\n def _install_apt_packages(self, packages: list): ...\n def __init__(self, *args): ...\n def _on_install(self, _): ...\n def _on_start(self, _): ...\n def _on_config_changed(self, _): ...\n def _on_database_relation_joined(self, event): ...\n def _on_database_master_changed(self, event): ...\n def _setup_application(self): ...\n def _render_systemd_unit(self): ...\n def _render_settings_file(self): ...\n def _create_database_tables(self): ...\n\n self.db = pgsql.PostgreSQLClient(self, 'db')\n\n _stored = StoredState()\n", "repository": "juju/hello-juju-charm", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001128.py"} {"focal_file": "src/charm.py", "focal_class": null, "focal_method": "_setup_application", "tests": "import unittest\n\nclass Test_setup_application(unittest.TestCase):\n @mock.patch('charm.HelloJujuCharm._create_database_tables')\n @mock.patch('charm.HelloJujuCharm._render_settings_file')\n @mock.patch('charm.check_output')\n @mock.patch('charm.Repo.clone_from')\n @mock.patch('charm.Path')\n @mock.patch('shutil.rmtree')\n def test_setup_application(self, _rmtree, _path, _clone, _check_output, _render, _createdb):\n _path.return_value.is_dir.return_value = True\n self.harness.charm._stored.conn_str = 'my_connection_string'\n self.harness.charm._setup_application()\n self.assertEqual(APP_PATH, Path('/srv/app'))\n self.assertEqual(VENV_ROOT, Path(f'{APP_PATH}/venv'))\n self.assertEqual(self.harness.charm.unit.status, MaintenanceStatus('fetching application code'))\n _rmtree.assert_called_with('/srv/app')\n self.assertEqual(self.harness.charm._stored.repo, 'https://github.com/juju/hello-juju')\n _clone.assert_called_with('https://github.com/juju/hello-juju', APP_PATH)\n self.assertEqual(_check_output.call_args_list, [call(['python3', '-m', 'virtualenv', f'{VENV_ROOT}']), call([f'{VENV_ROOT}/bin/pip3', 'install', 'gunicorn']), call([f'{VENV_ROOT}/bin/pip3', 'install', '-r', f'{APP_PATH}/requirements.txt', '--force'])])\n _render.assert_called_once()\n _createdb.assert_called_once()\n _path.return_value.is_dir.return_value = False\n self.harness.charm._stored.repo = 'https://myrepo'\n self.harness.charm._stored.conn_str = ''\n _rmtree.reset_mock()\n _render.reset_mock()\n self.harness.charm._setup_application()\n _render.assert_not_called()\n _rmtree.assert_not_called()\n self.assertEqual(self.harness.charm._stored.repo, 'https://myrepo')\n", "method_code": " def _setup_application(self):\n \"\"\"Clone a Flask application into place and setup it's dependencies\"\"\"\n self.unit.status = MaintenanceStatus('fetching application code')\n if Path(APP_PATH).is_dir():\n shutil.rmtree('/srv/app')\n if not self._stored.repo:\n self._stored.repo = self.config['application-repo']\n Repo.clone_from(self._stored.repo, APP_PATH)\n check_output(['python3', '-m', 'virtualenv', f'{VENV_ROOT}'])\n check_output([f'{VENV_ROOT}/bin/pip3', 'install', 'gunicorn'])\n check_output([f'{VENV_ROOT}/bin/pip3', 'install', '-r', f'{APP_PATH}/requirements.txt', '--force'])\n if self._stored.conn_str:\n self._render_settings_file()\n self._create_database_tables()\n ", "context": "class HelloJujuCharm(CharmBase):\n def _setup_application(self): ...\n def __init__(self, *args): ...\n def _on_install(self, _): ...\n def _on_start(self, _): ...\n def _on_config_changed(self, _): ...\n def _on_database_relation_joined(self, event): ...\n def _on_database_master_changed(self, event): ...\n def _install_apt_packages(self, packages: list): ...\n def _render_systemd_unit(self): ...\n def _render_settings_file(self): ...\n def _create_database_tables(self): ...\n\n self.db = pgsql.PostgreSQLClient(self, 'db')\n\n _stored = StoredState()\n", "repository": "juju/hello-juju-charm", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001129.py"} {"focal_file": "regcore/db/es.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n @patch('regcore.db.es.ElasticSearch')\n def test_get_404(self, es):\n es.return_value.get.side_effect = ElasticHttpNotFoundError\n eds = ESDiffs()\n self.assertEqual(None, eds.get('lablab', 'oldold', 'newnew'))\n self.assertEqual('diff', es.return_value.get.call_args[0][1])\n self.assertEqual('lablab/oldold/newnew', es.return_value.get.call_args[0][2])\n", "method_code": " def get(self, label, version):\n \"\"\"Find the regulation label + version\"\"\"\n try:\n result = self.es.get(settings.ELASTIC_SEARCH_INDEX, 'reg_tree', version + '/' + label)\n reg_node = result['_source']\n del reg_node['regulation']\n del reg_node['version']\n del reg_node['label_string']\n del reg_node['id']\n return reg_node\n except ElasticHttpNotFoundError:\n return None\n ", "context": "class ESRegulations(object):\n def get(self, label, version): ...\n def __init__(self): ...\n def _transform(self, reg, version): ...\n def bulk_put(self, regs, version, root_label): ...\n def listing(self, label=None): ...\n\n self.es = ElasticSearch(settings.ELASTIC_SEARCH_URLS)\n", "repository": "cfpb/regulations-core", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001130.py"} {"focal_file": "regcore/db/es.py", "focal_class": null, "focal_method": "bulk_put", "tests": "import unittest\n\nclass Test_bulk_put(unittest.TestCase):\n @patch('regcore.db.es.ElasticSearch')\n def test_bulk_put(self, es):\n esl = ESLayers()\n layers = [{'111-22': [], '111-22-a': [], 'label': '111-22'}, {'111-23': [], 'label': '111-23'}]\n esl.bulk_put(layers, 'verver', 'name', '111')\n self.assertTrue(es.return_value.bulk_index.called)\n args = es.return_value.bulk_index.call_args[0]\n self.assertEqual(3, len(args))\n self.assertEqual('layer', args[1])\n del layers[0]['label']\n del layers[1]['label']\n transformed = [{'id': 'verver/name/111-22', 'version': 'verver', 'name': 'name', 'label': '111-22', 'layer': layers[0]}, {'id': 'verver/name/111-23', 'version': 'verver', 'name': 'name', 'label': '111-23', 'layer': layers[1]}]\n self.assertEqual(transformed, args[2])\n", "method_code": " def bulk_put(self, regs, version, root_label):\n \"\"\"Store all reg objects\"\"\"\n self.es.bulk_index(settings.ELASTIC_SEARCH_INDEX, 'reg_tree', map(lambda r: self._transform(r, version), regs))\n ", "context": "class ESRegulations(object):\n def bulk_put(self, regs, version, root_label): ...\n def __init__(self): ...\n def get(self, label, version): ...\n def _transform(self, reg, version): ...\n def listing(self, label=None): ...\n\n self.es = ElasticSearch(settings.ELASTIC_SEARCH_URLS)\n", "repository": "cfpb/regulations-core", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001131.py"} {"focal_file": "regcore/db/es.py", "focal_class": null, "focal_method": "listing", "tests": "import unittest\n\nclass Test_listing(unittest.TestCase):\n @patch('regcore.db.es.ElasticSearch')\n def test_listing(self, es):\n es.return_value.search.return_value = {'hits': {'hits': [{'_id': 22, '_somethingelse': 5, 'fields': {'effective_on': '2005-05-05'}}, {'_id': 9, '_somethingelse': 'blue', 'fields': {}}]}}\n esn = ESNotices()\n self.assertEqual([{'document_number': 22, 'effective_on': '2005-05-05'}, {'document_number': 9}], esn.listing())\n self.assertEqual('notice', es.return_value.search.call_args[1]['doc_type'])\n self.assertEqual([{'document_number': 22, 'effective_on': '2005-05-05'}, {'document_number': 9}], esn.listing('876'))\n self.assertEqual('notice', es.return_value.search.call_args[1]['doc_type'])\n self.assertTrue('876' in str(es.return_value.search.call_args[0][0]))\n", "method_code": " def listing(self, label=None):\n \"\"\"List regulation version-label pairs that match this label (or are\n root, if label is None)\"\"\"\n if label is None:\n query = {'match': {'root': True}}\n else:\n query = {'match': {'label_string': label}}\n query = {'fields': ['label_string', 'version'], 'query': query}\n result = self.es.search(query, index=settings.ELASTIC_SEARCH_INDEX, doc_type='reg_tree', size=100)\n return sorted(((res['fields']['version'], res['fields']['label_string']) for res in result['hits']['hits']))\n ", "context": "class ESRegulations(object):\n def listing(self, label=None): ...\n def __init__(self): ...\n def get(self, label, version): ...\n def _transform(self, reg, version): ...\n def bulk_put(self, regs, version, root_label): ...\n\n self.es = ElasticSearch(settings.ELASTIC_SEARCH_URLS)\n", "repository": "cfpb/regulations-core", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001132.py"} {"focal_file": "regcore/db/es.py", "focal_class": null, "focal_method": "put", "tests": "import unittest\n\nclass Test_put(unittest.TestCase):\n @patch('regcore.db.es.ElasticSearch')\n def test_put(self, es):\n eds = ESDiffs()\n eds.put('lablab', 'oldold', 'newnew', {'some': 'structure'})\n self.assertTrue(es.return_value.index.called)\n args, kwargs = es.return_value.index.call_args\n self.assertEqual(3, len(args))\n self.assertEqual('diff', args[1])\n self.assertEqual('lablab/oldold/newnew', kwargs['id'])\n self.assertEqual({'label': 'lablab', 'old_version': 'oldold', 'new_version': 'newnew', 'diff': {'some': 'structure'}}, args[2])\n", "method_code": " def put(self, doc_number, notice):\n \"\"\"Store a single notice\"\"\"\n self.es.index(settings.ELASTIC_SEARCH_INDEX, 'notice', notice, id=doc_number)\n ", "context": "class ESNotices(object):\n def put(self, doc_number, notice): ...\n def __init__(self): ...\n def get(self, doc_number): ...\n def listing(self, part=None): ...\n\n self.es = ElasticSearch(settings.ELASTIC_SEARCH_URLS)\n", "repository": "cfpb/regulations-core", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001133.py"} {"focal_file": "regcore/index.py", "focal_class": null, "focal_method": "init_schema", "tests": "import unittest\n\nclass Test_init_schema(unittest.TestCase):\n @patch('regcore.index.ElasticSearch')\n def test_init_schema(self, es):\n init_schema()\n self.assertTrue(es.called)\n self.assertTrue(es.return_value.create_index.called)\n self.assertTrue(es.return_value.put_mapping.called)\n\n @patch('regcore.index.ElasticSearch')\n def test_init_schema_index_exists(self, es):\n es.return_value.create_index.side_effect = IndexAlreadyExistsError()\n init_schema()\n self.assertTrue(es.return_value.put_mapping.called)\n", "method_code": "def init_schema():\n \"\"\"Should be called at application startup. Makes sure the mappings and\n index exist.\"\"\"\n es = ElasticSearch(settings.ELASTIC_SEARCH_URLS)\n try:\n es.create_index(settings.ELASTIC_SEARCH_INDEX)\n except IndexAlreadyExistsError:\n pass\n es.put_mapping(settings.ELASTIC_SEARCH_INDEX, 'reg_tree', {'reg_tree': {'properties': NODE_SEARCH_SCHEMA}})\n es.put_mapping(settings.ELASTIC_SEARCH_INDEX, 'layer', {'layer': {'properties': LAYER_SCHEMA}})\n es.put_mapping(settings.ELASTIC_SEARCH_INDEX, 'notice', {'notice': {'properties': LAYER_SCHEMA}})\n es.put_mapping(settings.ELASTIC_SEARCH_INDEX, 'diff', {'diff': {'properties': DIFF_SCHEMA}})", "context": "def init_schema(): ...\ndef init_schema(): ...\n", "repository": "cfpb/regulations-core", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001134.py"} {"focal_file": "regcore/responses.py", "focal_class": null, "focal_method": "user_error", "tests": "import unittest\n\nclass Test_user_error(unittest.TestCase):\n def test_user_error(self):\n response = user_error('my reason')\n self.assertEqual(400, response.status_code)\n self.assertEqual('application/json', response['Content-type'])\n self.assertTrue('my reason' in response.content)\n json.loads(response.content)\n", "method_code": "def user_error(reason):\n \"\"\"Silly user, you get a 400\"\"\"\n obj = json.dumps({'reason': reason})\n return HttpResponse(obj, 'application/json', 400)", "context": "def user_error(reason): ...\ndef user_error(reason): ...\ndef success(ret_value=None): ...\ndef four_oh_four(): ...\n", "repository": "cfpb/regulations-core", "test_name": "test_user_error", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001135.py"} {"focal_file": "regcore/responses.py", "focal_class": null, "focal_method": "success", "tests": "import unittest\n\nclass Test_success(unittest.TestCase):\n def test_success_empty(self):\n response = success()\n self.assertEqual(204, response.status_code)\n self.assertEqual(0, len(response.content))\n\n def test_success_full(self):\n structure = {'some': {'structure': 1}}\n response = success(structure)\n self.assertEqual(200, response.status_code)\n self.assertEqual('application/json', response['Content-type'])\n self.assertEqual(structure, json.loads(response.content))\n", "method_code": "def success(ret_value=None):\n \"\"\"Respond with either a JSON message or empty body\"\"\"\n if ret_value is not None:\n return HttpResponse(json.dumps(ret_value), 'application/json')\n else:\n return HttpResponse('', status=204)", "context": "def success(ret_value=None): ...\ndef user_error(reason): ...\ndef success(ret_value=None): ...\ndef four_oh_four(): ...\n", "repository": "cfpb/regulations-core", "test_name": "test_success_empty", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001136.py"} {"focal_file": "regcore_write/views/layer.py", "focal_class": null, "focal_method": "child_layers", "tests": "import unittest\n\nclass Test_child_layers(unittest.TestCase):\n @patch('regcore_write.views.layer.db')\n def test_child_layers_no_results(self, db):\n db.Regulations.return_value.get.return_value = None\n self.assertEqual([], child_layers('layname', 'lll', 'vvv', {}))\n self.assertTrue(db.Regulations.return_value.get.called)\n self.assertEqual('lll', db.Regulations.return_value.get.call_args[0][0])\n self.assertEqual('vvv', db.Regulations.return_value.get.call_args[0][1])\n", "method_code": "def child_layers(layer_name, root_label, version, root_layer):\n \"\"\"We are generally given a layer corresponding to an entire regulation.\n We need to split that layer up and store it per node within the\n regulation. If a reg has 100 nodes, but the layer only has 3 entries, it\n will still store 100 layer models -- many may be empty\"\"\"\n root = db.Regulations().get(root_label, version)\n if not root:\n return []\n to_save = []\n\n def find_labels(node):\n child_labels = []\n for child in node['children']:\n child_labels.extend(find_labels(child))\n label_id = '-'.join(node['label'])\n sub_layer = {'label': label_id}\n for key in root_layer:\n if key == label_id or key in child_labels or key == 'referenced':\n sub_layer[key] = root_layer[key]\n to_save.append(sub_layer)\n return child_labels + [label_id]\n find_labels(root)\n return to_save", "context": "def child_layers(layer_name, root_label, version, root_layer): ...\ndef child_label_of(lhs, rhs): ...\ndef add(request, name, label_id, version): ...\ndef child_layers(layer_name, root_label, version, root_layer): ...\n", "repository": "cfpb/regulations-core", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001137.py"} {"focal_file": "regcore_write/views/layer.py", "focal_class": null, "focal_method": "child_label_of", "tests": "import unittest\n\nclass Test_child_label_of(unittest.TestCase):\n def test_child_label_of(self):\n self.assertTrue(child_label_of('1005-5-a-1-Interp-1', '1005-5-Interp'))\n", "method_code": "def child_label_of(lhs, rhs):\n \"\"\"Is the lhs label a child of the rhs label\"\"\"\n if 'Interp' in lhs and 'Interp' in rhs:\n lhs_reg, lhs_comment = lhs.split('Interp')\n rhs_reg, rhs_comment = rhs.split('Interp')\n if lhs_reg.startswith(rhs_reg):\n return True\n if lhs.startswith(rhs):\n return True\n return False", "context": "def child_label_of(lhs, rhs): ...\ndef child_label_of(lhs, rhs): ...\ndef add(request, name, label_id, version): ...\ndef child_layers(layer_name, root_label, version, root_layer): ...\n", "repository": "cfpb/regulations-core", "test_name": "test_child_label_of", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001138.py"} {"focal_file": "bpython/inspection.py", "focal_class": null, "focal_method": "is_callable", "tests": "import unittest\n\nclass Test_is_callable(unittest.TestCase):\n def test_is_callable(self):\n\n class OldCallable:\n\n def __call__(self):\n pass\n\n class Callable(object):\n\n def __call__(self):\n pass\n\n class OldNoncallable:\n pass\n\n class Noncallable(object):\n pass\n\n def spam():\n pass\n self.assertTrue(inspection.is_callable(spam))\n self.assertTrue(inspection.is_callable(Callable))\n self.assertTrue(inspection.is_callable(Callable()))\n self.assertTrue(inspection.is_callable(OldCallable))\n self.assertTrue(inspection.is_callable(OldCallable()))\n self.assertFalse(inspection.is_callable(Noncallable()))\n self.assertFalse(inspection.is_callable(OldNoncallable()))\n self.assertFalse(inspection.is_callable(None))\n", "method_code": "def is_callable(obj):\n if has_instance_type and isinstance(obj, types.InstanceType):\n return isinstance(obj, collections.Callable)\n elif has_collections_callable:\n return isinstance(obj, collections.Callable)\n else:\n return isinstance(obj, collections.Callable)", "context": "def is_callable(obj): ...\ndef parsekeywordpairs(signature): ...\ndef fixlongargs(f, argspec): ...\ndef getpydocspec(f, func): ...\ndef getargspec(func, f): ...\ndef is_eval_safe_name(string): ...\ndef is_callable(obj): ...\n", "repository": "fenhl/bpython-blessings", "test_name": "test_is_callable", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001139.py"} {"focal_file": "bpython/config.py", "focal_class": "bpython.config.Struct", "focal_method": "load_theme", "tests": "import unittest\n\nclass Test_bpython_config_Struct_load_theme(unittest.TestCase):\n def test_load_theme(self):\n struct = config.Struct()\n struct.color_scheme = dict()\n config.load_theme(struct, TEST_THEME_PATH, struct.color_scheme, dict())\n expected = {'keyword': 'y'}\n self.assertEquals(struct.color_scheme, expected)\n defaults = {'name': 'c'}\n expected.update(defaults)\n config.load_theme(struct, TEST_THEME_PATH, struct.color_scheme, defaults)\n self.assertEquals(struct.color_scheme, expected)\n", "method_code": "def load_theme(struct, path, colors, default_colors):\n theme = ConfigParser()\n with open(path, 'r') as f:\n theme.readfp(f)\n for k, v in chain(theme.items('syntax'), theme.items('interface')):\n if theme.has_option('syntax', k):\n colors[k] = theme.get('syntax', k)\n else:\n colors[k] = theme.get('interface', k)\n for k, v in default_colors.items():\n if k not in colors:\n colors[k] = v\n f.close()", "context": "def load_theme(struct, path, colors, default_colors): ...\ndef get_config_home(): ...\ndef default_config_path(): ...\ndef fill_config_with_default_values(config, default_values): ...\ndef loadini(struct, configfile): ...\ndef load_theme(struct, path, colors, default_colors): ...\n", "repository": "fenhl/bpython-blessings", "test_name": "test_load_theme", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001140.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "first", "tests": "import unittest\n\nclass Test_first(unittest.TestCase):\n def test_first(self):\n self.history.first()\n self.assertFalse(self.history.is_at_start)\n self.assertTrue(self.history.is_at_end)\n", "method_code": " def first(self):\n \"\"\"Move back to the beginning of the history.\"\"\"\n if not self.is_at_end:\n self.index = len(self.entries)\n return self.entries[-self.index]\n ", "context": "class History(object):\n def first(self): ...\n def __init__(self, entries=None, duplicates=False): ...\n def append(self, line): ...\n def back(self, start=True, search=False): ...\n def find_match_backward(self, search_term): ...\n def find_partial_match_backward(self, search_term): ...\n def forward(self, start=True, search=False): ...\n def find_match_forward(self, search_term): ...\n def find_partial_match_forward(self, search_term): ...\n def last(self): ...\n def is_at_end(self): ...\n def is_at_start(self): ...\n def enter(self, line): ...\n def from_filename(cls, filename): ...\n def load(self, filename, encoding): ...\n def reset(self): ...\n def save(self, filename, encoding, lines=0): ...\n\n self.index = 0\n self.saved_line = ''\n self.duplicates = duplicates\n", "repository": "fenhl/bpython-blessings", "test_name": "test_first", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001141.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "last", "tests": "import unittest\n\nclass Test_last(unittest.TestCase):\n def test_last(self):\n self.history.last()\n self.assertTrue(self.history.is_at_start)\n self.assertFalse(self.history.is_at_end)\n", "method_code": " def last(self):\n \"\"\"Move forward to the end of the history.\"\"\"\n if not self.is_at_start:\n self.index = 0\n return self.entries[0]\n ", "context": "class History(object):\n def last(self): ...\n def __init__(self, entries=None, duplicates=False): ...\n def append(self, line): ...\n def first(self): ...\n def back(self, start=True, search=False): ...\n def find_match_backward(self, search_term): ...\n def find_partial_match_backward(self, search_term): ...\n def forward(self, start=True, search=False): ...\n def find_match_forward(self, search_term): ...\n def find_partial_match_forward(self, search_term): ...\n def is_at_end(self): ...\n def is_at_start(self): ...\n def enter(self, line): ...\n def from_filename(cls, filename): ...\n def load(self, filename, encoding): ...\n def reset(self): ...\n def save(self, filename, encoding, lines=0): ...\n\n self.index = 0\n self.saved_line = ''\n self.duplicates = duplicates\n", "repository": "fenhl/bpython-blessings", "test_name": "test_last", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001142.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "back", "tests": "import unittest\n\nclass Test_back(unittest.TestCase):\n def test_back(self):\n self.assertEqual(self.history.back(), '#999')\n self.assertNotEqual(self.history.back(), '#999')\n self.assertEqual(self.history.back(), '#997')\n for x in range(997):\n self.history.back()\n self.assertEqual(self.history.back(), '#0')\n", "method_code": " def back(self, start=True, search=False):\n \"\"\"Move one step back in the history.\"\"\"\n if not self.is_at_end:\n if search:\n self.index += self.find_partial_match_backward(self.saved_line)\n elif start:\n self.index += self.find_match_backward(self.saved_line)\n else:\n self.index += 1\n return self.entries[-self.index] if self.index else self.saved_line\n ", "context": "class History(object):\n def back(self, start=True, search=False): ...\n def __init__(self, entries=None, duplicates=False): ...\n def append(self, line): ...\n def first(self): ...\n def find_match_backward(self, search_term): ...\n def find_partial_match_backward(self, search_term): ...\n def forward(self, start=True, search=False): ...\n def find_match_forward(self, search_term): ...\n def find_partial_match_forward(self, search_term): ...\n def last(self): ...\n def is_at_end(self): ...\n def is_at_start(self): ...\n def enter(self, line): ...\n def from_filename(cls, filename): ...\n def load(self, filename, encoding): ...\n def reset(self): ...\n def save(self, filename, encoding, lines=0): ...\n\n self.index = 0\n self.saved_line = ''\n self.duplicates = duplicates\n", "repository": "fenhl/bpython-blessings", "test_name": "test_back", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001143.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "forward", "tests": "import unittest\n\nclass Test_forward(unittest.TestCase):\n def test_forward(self):\n self.history.first()\n self.assertEqual(self.history.forward(), '#1')\n self.assertNotEqual(self.history.forward(), '#1')\n self.assertEqual(self.history.forward(), '#3')\n for x in range(1000 - 4 - 1):\n self.history.forward()\n self.assertEqual(self.history.forward(), '#999')\n", "method_code": " def forward(self, start=True, search=False):\n \"\"\"Move one step forward in the history.\"\"\"\n if self.index > 1:\n if search:\n self.index -= self.find_partial_match_forward(self.saved_line)\n elif start:\n self.index -= self.find_match_forward(self.saved_line)\n else:\n self.index -= 1\n return self.entries[-self.index] if self.index else self.saved_line\n else:\n self.index = 0\n return self.saved_line\n ", "context": "class History(object):\n def forward(self, start=True, search=False): ...\n def __init__(self, entries=None, duplicates=False): ...\n def append(self, line): ...\n def first(self): ...\n def back(self, start=True, search=False): ...\n def find_match_backward(self, search_term): ...\n def find_partial_match_backward(self, search_term): ...\n def find_match_forward(self, search_term): ...\n def find_partial_match_forward(self, search_term): ...\n def last(self): ...\n def is_at_end(self): ...\n def is_at_start(self): ...\n def enter(self, line): ...\n def from_filename(cls, filename): ...\n def load(self, filename, encoding): ...\n def reset(self): ...\n def save(self, filename, encoding, lines=0): ...\n\n self.index = 0\n self.saved_line = ''\n self.duplicates = duplicates\n", "repository": "fenhl/bpython-blessings", "test_name": "test_forward", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001144.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "append", "tests": "import unittest\n\nclass Test_append(unittest.TestCase):\n def test_append(self):\n self.history.append('print \"foo\\n\"\\n')\n self.history.append('\\n')\n self.assertEqual(self.history.back(), 'print \"foo\\n\"')\n", "method_code": " def append(self, line):\n line = line.rstrip('\\n')\n if line:\n if not self.duplicates:\n try:\n while True:\n self.entries.remove(line)\n except ValueError:\n pass\n self.entries.append(line)\n ", "context": "class History(object):\n def append(self, line): ...\n def __init__(self, entries=None, duplicates=False): ...\n def first(self): ...\n def back(self, start=True, search=False): ...\n def find_match_backward(self, search_term): ...\n def find_partial_match_backward(self, search_term): ...\n def forward(self, start=True, search=False): ...\n def find_match_forward(self, search_term): ...\n def find_partial_match_forward(self, search_term): ...\n def last(self): ...\n def is_at_end(self): ...\n def is_at_start(self): ...\n def enter(self, line): ...\n def from_filename(cls, filename): ...\n def load(self, filename, encoding): ...\n def reset(self): ...\n def save(self, filename, encoding, lines=0): ...\n\n self.index = 0\n self.saved_line = ''\n self.duplicates = duplicates\n", "repository": "fenhl/bpython-blessings", "test_name": "test_append", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001145.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "enter", "tests": "import unittest\n\nclass Test_enter(unittest.TestCase):\n def test_enter(self):\n self.history.enter('#lastnumber!')\n self.assertEqual(self.history.back(), '#999')\n self.assertEqual(self.history.forward(), '#lastnumber!')\n", "method_code": " def enter(self, line):\n if self.index == 0:\n self.saved_line = line\n ", "context": "class History(object):\n def enter(self, line): ...\n def __init__(self, entries=None, duplicates=False): ...\n def append(self, line): ...\n def first(self): ...\n def back(self, start=True, search=False): ...\n def find_match_backward(self, search_term): ...\n def find_partial_match_backward(self, search_term): ...\n def forward(self, start=True, search=False): ...\n def find_match_forward(self, search_term): ...\n def find_partial_match_forward(self, search_term): ...\n def last(self): ...\n def is_at_end(self): ...\n def is_at_start(self): ...\n def from_filename(cls, filename): ...\n def load(self, filename, encoding): ...\n def reset(self): ...\n def save(self, filename, encoding, lines=0): ...\n\n self.index = 0\n self.saved_line = ''\n self.duplicates = duplicates\n", "repository": "fenhl/bpython-blessings", "test_name": "test_enter", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001146.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "reset", "tests": "import unittest\n\nclass Test_reset(unittest.TestCase):\n def test_reset(self):\n self.history.enter('#lastnumber!')\n self.history.reset()\n self.assertEqual(self.history.back(), '#999')\n self.assertEqual(self.history.forward(), '')\n", "method_code": " def reset(self):\n self.index = 0\n self.saved_line = ''\n ", "context": "class History(object):\n def reset(self): ...\n def __init__(self, entries=None, duplicates=False): ...\n def append(self, line): ...\n def first(self): ...\n def back(self, start=True, search=False): ...\n def find_match_backward(self, search_term): ...\n def find_partial_match_backward(self, search_term): ...\n def forward(self, start=True, search=False): ...\n def find_match_forward(self, search_term): ...\n def find_partial_match_forward(self, search_term): ...\n def last(self): ...\n def is_at_end(self): ...\n def is_at_start(self): ...\n def enter(self, line): ...\n def from_filename(cls, filename): ...\n def load(self, filename, encoding): ...\n def save(self, filename, encoding, lines=0): ...\n\n self.index = 0\n self.saved_line = ''\n self.duplicates = duplicates\n", "repository": "fenhl/bpython-blessings", "test_name": "test_reset", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001147.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "previous", "tests": "import unittest\n\nclass Test_previous(unittest.TestCase):\n def test_previous(self):\n self.assertEqual(self.matches_iterator.previous(), self.matches[2])\n for x in range(len(self.matches) - 1):\n self.matches_iterator.previous()\n self.assertNotEqual(self.matches_iterator.previous(), self.matches[0])\n self.assertEqual(self.matches_iterator.previous(), self.matches[1])\n self.assertEqual(self.matches_iterator.previous(), self.matches[0])\n", "method_code": " def previous(self):\n if self.index <= 0:\n self.index = len(self.matches)\n self.index -= 1\n return self.matches[self.index]\n ", "context": "class MatchesIterator(object):\n def previous(self): ...\n def __init__(self, current_word='', matches=[]): ...\n def __bool__(self): ...\n def __iter__(self): ...\n def current(self): ...\n def __next__(self): ...\n def update(self, current_word='', matches=[]): ...\n\n self.current_word = current_word\n self.matches = list(matches)\n self.index = -1\n", "repository": "fenhl/bpython-blessings", "test_name": "test_previous", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001148.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "current", "tests": "import unittest\n\nclass Test_current(unittest.TestCase):\n def test_current(self):\n self.assertRaises(ValueError, self.matches_iterator.current)\n next(self.matches_iterator)\n self.assertEqual(self.matches_iterator.current(), self.matches[0])\n", "method_code": " def current(self):\n if self.index == -1:\n raise ValueError('No current match.')\n return self.matches[self.index]\n ", "context": "class MatchesIterator(object):\n def current(self): ...\n def __init__(self, current_word='', matches=[]): ...\n def __bool__(self): ...\n def __iter__(self): ...\n def __next__(self): ...\n def previous(self): ...\n def update(self, current_word='', matches=[]): ...\n\n self.current_word = current_word\n self.matches = list(matches)\n self.index = -1\n", "repository": "fenhl/bpython-blessings", "test_name": "test_current", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001149.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "update", "tests": "import unittest\n\nclass Test_update(unittest.TestCase):\n def test_update(self):\n slice = islice(self.matches_iterator, 0, 3)\n self.assertEqual(list(slice), self.matches)\n newmatches = ['string', 'str', 'set']\n self.matches_iterator.update('s', newmatches)\n newslice = islice(newmatches, 0, 3)\n self.assertNotEqual(list(slice), self.matches)\n self.assertEqual(list(newslice), newmatches)\n", "method_code": " def update(self, current_word='', matches=[]):\n if current_word != self.current_word:\n self.current_word = current_word\n self.matches = list(matches)\n self.index = -1\n ", "context": "class MatchesIterator(object):\n def update(self, current_word='', matches=[]): ...\n def __init__(self, current_word='', matches=[]): ...\n def __bool__(self): ...\n def __iter__(self): ...\n def current(self): ...\n def __next__(self): ...\n def previous(self): ...\n\n self.current_word = current_word\n self.matches = list(matches)\n self.index = -1\n", "repository": "fenhl/bpython-blessings", "test_name": "test_update", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001150.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "current_string", "tests": "import unittest\n\nclass Test_current_string(unittest.TestCase):\n def test_current_string(self):\n self.repl.input_line = 'a = \"2\"'\n self.assertEqual(self.repl.current_string(), '\"2\"')\n self.repl.input_line = 'a = \"2\" + 2'\n self.assertEqual(self.repl.current_string(), '')\n", "method_code": " def current_string(self, concatenate=False):\n \"\"\"If the line ends in a string get it, otherwise return ''\"\"\"\n tokens = self.tokenize(self.current_line())\n string_tokens = list(takewhile(token_is_any_of([Token.String, Token.Text]), reversed(tokens)))\n if not string_tokens:\n return ''\n opening = string_tokens.pop()[1]\n string = list()\n for token, value in reversed(string_tokens):\n if token is Token.Text:\n continue\n elif opening is None:\n opening = value\n elif token is Token.String.Doc:\n string.append(value[3:-3])\n opening = None\n elif value == opening:\n opening = None\n if not concatenate:\n string = list()\n else:\n string.append(value)\n if opening is None:\n return ''\n return ''.join(string)\n ", "context": "class Repl(object):\n def current_string(self, concatenate=False): ...\n def __init__(self, interp, config): ...\n def startup(self): ...\n def get_object(self, name): ...\n def get_args(self): ...\n def get_source_of_current_name(self): ...\n def complete(self, tab=False): ...\n def format_docstring(self, docstring, width, height): ...\n def next_indentation(self): ...\n def formatforfile(self, s): ...\n def write2file(self): ...\n def pastebin(self, s=None): ...\n def do_pastebin(self, s): ...\n def do_pastebin_xmlrpc(self, s): ...\n def do_pastebin_helper(self, s): ...\n def push(self, s, insert_into_history=True): ...\n def insert_into_history(self, s): ...\n def undo(self, n=1): ...\n def flush(self): ...\n def close(self): ...\n def tokenize(self, s, newline=False): ...\n def clear_current_line(self): ...\n\n self.config = config\n self.cut_buffer = ''\n self.buffer = []\n self.interp = interp\n self.interp.syntaxerror_callback = self.clear_current_line\n self.match = False\n self.rl_history = History(duplicates=config.hist_duplicates)\n self.s_hist = []\n self.history = []\n self.evaluating = False\n self.completer = Autocomplete(self.interp.locals, config)\n self.matches = []\n self.matches_iter = MatchesIterator()\n self.argspec = None\n self.current_func = None\n self.highlighted_paren = None\n self.list_win_visible = False\n self._C = {}\n self.prev_block_finished = 0\n self.interact = Interaction(self.config)\n self.ps1 = '>>> '\n self.ps2 = '... '\n self.prev_pastebin_content = ''\n self.prev_pastebin_url = ''\n self.closed = False\n", "repository": "fenhl/bpython-blessings", "test_name": "test_current_string", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001151.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "push", "tests": "import unittest\n\nclass Test_push(unittest.TestCase):\n @skip('not working yet')\n def test_push(self):\n self.repl = FakeRepl()\n self.repl.push('foobar = 2')\n self.repl.push('\"foobar\" in globals().keys()')\n", "method_code": " def push(self, s, insert_into_history=True):\n \"\"\"Push a line of code onto the buffer so it can process it all\n at once when a code block ends\"\"\"\n s = s.rstrip('\\n')\n self.buffer.append(s)\n if insert_into_history:\n self.insert_into_history(s)\n more = self.interp.runsource('\\n'.join(self.buffer))\n if not more:\n self.buffer = []\n return more\n ", "context": "class Repl(object):\n def push(self, s, insert_into_history=True): ...\n def __init__(self, interp, config): ...\n def startup(self): ...\n def current_string(self, concatenate=False): ...\n def get_object(self, name): ...\n def get_args(self): ...\n def get_source_of_current_name(self): ...\n def complete(self, tab=False): ...\n def format_docstring(self, docstring, width, height): ...\n def next_indentation(self): ...\n def formatforfile(self, s): ...\n def write2file(self): ...\n def pastebin(self, s=None): ...\n def do_pastebin(self, s): ...\n def do_pastebin_xmlrpc(self, s): ...\n def do_pastebin_helper(self, s): ...\n def insert_into_history(self, s): ...\n def undo(self, n=1): ...\n def flush(self): ...\n def close(self): ...\n def tokenize(self, s, newline=False): ...\n def clear_current_line(self): ...\n\n self.config = config\n self.cut_buffer = ''\n self.buffer = []\n self.interp = interp\n self.interp.syntaxerror_callback = self.clear_current_line\n self.match = False\n self.rl_history = History(duplicates=config.hist_duplicates)\n self.s_hist = []\n self.history = []\n self.evaluating = False\n self.completer = Autocomplete(self.interp.locals, config)\n self.matches = []\n self.matches_iter = MatchesIterator()\n self.argspec = None\n self.current_func = None\n self.highlighted_paren = None\n self.list_win_visible = False\n self._C = {}\n self.prev_block_finished = 0\n self.interact = Interaction(self.config)\n self.ps1 = '>>> '\n self.ps2 = '... '\n self.prev_pastebin_content = ''\n self.prev_pastebin_url = ''\n self.closed = False\n", "repository": "fenhl/bpython-blessings", "test_name": "", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001152.py"} {"focal_file": "bpython/repl.py", "focal_class": null, "focal_method": "complete", "tests": "import unittest\n\nclass Test_complete(unittest.TestCase):\n def test_simple_global_complete(self):\n self.repl = FakeRepl({'autocomplete_mode': autocomplete.SIMPLE})\n self.repl.input_line = 'd'\n self.repl.current_word = 'd'\n self.assertTrue(self.repl.complete())\n self.assertTrue(hasattr(self.repl.completer, 'matches'))\n self.assertEqual(self.repl.completer.matches, ['def', 'del', 'delattr(', 'dict(', 'dir(', 'divmod('])\n\n def test_substring_global_complete(self):\n self.repl = FakeRepl({'autocomplete_mode': autocomplete.SUBSTRING})\n self.repl.input_line = 'time'\n self.repl.current_word = 'time'\n self.assertTrue(self.repl.complete())\n self.assertTrue(hasattr(self.repl.completer, 'matches'))\n self.assertEqual(self.repl.completer.matches, ['RuntimeError(', 'RuntimeWarning('])\n\n def test_fuzzy_global_complete(self):\n self.repl = FakeRepl({'autocomplete_mode': autocomplete.FUZZY})\n self.repl.input_line = 'doc'\n self.repl.current_word = 'doc'\n self.assertTrue(self.repl.complete())\n self.assertTrue(hasattr(self.repl.completer, 'matches'))\n self.assertEqual(self.repl.completer.matches, ['UnboundLocalError(', '__doc__'])\n\n def test_simple_attribute_complete(self):\n self.repl = FakeRepl({'autocomplete_mode': autocomplete.SIMPLE})\n self.repl.input_line = 'Foo.b'\n self.repl.current_word = 'Foo.b'\n code = 'class Foo():\\n\\tdef bar(self):\\n\\t\\tpass\\n'\n for line in code.split('\\n'):\n self.repl.push(line)\n self.assertTrue(self.repl.complete())\n self.assertTrue(hasattr(self.repl.completer, 'matches'))\n self.assertEqual(self.repl.completer.matches, ['Foo.bar'])\n\n def test_substring_attribute_complete(self):\n self.repl = FakeRepl({'autocomplete_mode': autocomplete.SUBSTRING})\n self.repl.input_line = 'Foo.az'\n self.repl.current_word = 'Foo.az'\n code = 'class Foo():\\n\\tdef baz(self):\\n\\t\\tpass\\n'\n for line in code.split('\\n'):\n self.repl.push(line)\n self.assertTrue(self.repl.complete())\n self.assertTrue(hasattr(self.repl.completer, 'matches'))\n self.assertEqual(self.repl.completer.matches, ['Foo.baz'])\n\n def test_fuzzy_attribute_complete(self):\n self.repl = FakeRepl({'autocomplete_mode': autocomplete.FUZZY})\n self.repl.input_line = 'Foo.br'\n self.repl.current_word = 'Foo.br'\n code = 'class Foo():\\n\\tdef bar(self):\\n\\t\\tpass\\n'\n for line in code.split('\\n'):\n self.repl.push(line)\n self.assertTrue(self.repl.complete())\n self.assertTrue(hasattr(self.repl.completer, 'matches'))\n self.assertEqual(self.repl.completer.matches, ['Foo.bar'])\n\n def test_updating_namespace_complete(self):\n self.repl = FakeRepl({'autocomplete_mode': autocomplete.SIMPLE})\n self.repl.input_line = 'foo'\n self.repl.current_word = 'foo'\n self.repl.push('foobar = 2')\n self.assertTrue(self.repl.complete())\n self.assertTrue(hasattr(self.repl.completer, 'matches'))\n self.assertEqual(self.repl.completer.matches, ['foobar'])\n\n def test_file_should_not_appear_in_complete(self):\n self.repl = FakeRepl({'autocomplete_mode': autocomplete.SIMPLE})\n self.repl.input_line = '_'\n self.repl.current_word = '_'\n self.assertTrue(self.repl.complete())\n self.assertTrue(hasattr(self.repl.completer, 'matches'))\n self.assertTrue('__file__' not in self.repl.completer.matches)\n", "method_code": " def complete(self, tab=False):\n \"\"\"Construct a full list of possible completions and construct and\n display them in a window. Also check if there's an available argspec\n (via the inspect module) and bang that on top of the completions too.\n The return value is whether the list_win is visible or not.\"\"\"\n self.docstring = None\n if not self.get_args():\n self.argspec = None\n elif self.current_func is not None:\n try:\n self.docstring = pydoc.getdoc(self.current_func)\n except IndexError:\n self.docstring = None\n else:\n if not self.docstring:\n self.docstring = None\n cw = self.cw()\n cs = self.current_string()\n if not cw:\n self.matches = []\n self.matches_iter.update()\n if not (cw or cs):\n return bool(self.argspec)\n if cs and tab:\n self.matches = list()\n username = cs.split(os.path.sep, 1)[0]\n user_dir = os.path.expanduser(username)\n for filename in glob(os.path.expanduser(cs + '*')):\n if os.path.isdir(filename):\n filename += os.path.sep\n if cs.startswith('~'):\n filename = username + filename[len(user_dir):]\n self.matches.append(filename)\n self.matches_iter.update(cs, self.matches)\n return bool(self.matches)\n elif cs:\n self.matches_iter.update()\n return False\n e = False\n matches = importcompletion.complete(self.current_line(), cw)\n if matches is not None and (not matches):\n self.matches = []\n self.matches_iter.update()\n return False\n if matches is None:\n try:\n self.completer.complete(cw, 0)\n except Exception:\n e = True\n else:\n matches = self.completer.matches\n if self.config.complete_magic_methods and self.buffer and self.buffer[0].startswith('class ') and self.current_line().lstrip().startswith('def '):\n matches.extend((name for name in self.config.magic_methods if name.startswith(cw)))\n if not e and self.argspec:\n matches.extend((name + '=' for name in self.argspec[1][0] if isinstance(name, str) and name.startswith(cw)))\n if py3:\n matches.extend((name + '=' for name in self.argspec[1][4] if name.startswith(cw)))\n if not e and (not cw.split('.')[-1].startswith('_')):\n matches = [match for match in matches if not match.split('.')[-1].startswith('_')]\n if e or not matches:\n self.matches = []\n self.matches_iter.update()\n if not self.argspec:\n return False\n else:\n self.matches = sorted(set(matches))\n if len(self.matches) == 1 and (not self.config.auto_display_list):\n self.list_win_visible = True\n self.tab()\n return False\n self.matches_iter.update(cw, self.matches)\n return True\n ", "context": "class Repl(object):\n def complete(self, tab=False): ...\n def __init__(self, interp, config): ...\n def startup(self): ...\n def current_string(self, concatenate=False): ...\n def get_object(self, name): ...\n def get_args(self): ...\n def get_source_of_current_name(self): ...\n def format_docstring(self, docstring, width, height): ...\n def next_indentation(self): ...\n def formatforfile(self, s): ...\n def write2file(self): ...\n def pastebin(self, s=None): ...\n def do_pastebin(self, s): ...\n def do_pastebin_xmlrpc(self, s): ...\n def do_pastebin_helper(self, s): ...\n def push(self, s, insert_into_history=True): ...\n def insert_into_history(self, s): ...\n def undo(self, n=1): ...\n def flush(self): ...\n def close(self): ...\n def tokenize(self, s, newline=False): ...\n def clear_current_line(self): ...\n\n self.config = config\n self.cut_buffer = ''\n self.buffer = []\n self.interp = interp\n self.interp.syntaxerror_callback = self.clear_current_line\n self.match = False\n self.rl_history = History(duplicates=config.hist_duplicates)\n self.s_hist = []\n self.history = []\n self.evaluating = False\n self.completer = Autocomplete(self.interp.locals, config)\n self.matches = []\n self.matches_iter = MatchesIterator()\n self.argspec = None\n self.current_func = None\n self.highlighted_paren = None\n self.list_win_visible = False\n self._C = {}\n self.prev_block_finished = 0\n self.interact = Interaction(self.config)\n self.ps1 = '>>> '\n self.ps2 = '... '\n self.prev_pastebin_content = ''\n self.prev_pastebin_url = ''\n self.closed = False\n", "repository": "fenhl/bpython-blessings", "test_name": "test_simple_global_complete", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001153.py"} {"focal_file": "maskrcnn_benchmark/structures/segmentation_mask.py", "focal_class": null, "focal_method": "convert", "tests": "import unittest\n\nclass Test_convert(unittest.TestCase):\n def test_convert(self):\n M_hat = self.M.convert('poly').convert('mask')\n P_hat = self.P.convert('mask').convert('poly')\n diff_mask = self.L1(self.M, M_hat)\n diff_poly = self.L1(self.P, P_hat)\n self.assertTrue(diff_mask == diff_poly)\n self.assertTrue(diff_mask <= 8169.0)\n self.assertTrue(diff_poly <= 8169.0)\n", "method_code": " def convert(self, mode):\n if mode == self.mode:\n return self\n if mode == 'poly':\n converted_instances = self.instances.convert_to_polygon()\n elif mode == 'mask':\n converted_instances = self.instances.convert_to_binarymask()\n else:\n raise NotImplementedError('Unknown mode: %s' % str(mode))\n return SegmentationMask(converted_instances, self.size, mode)\n ", "context": "class SegmentationMask(object):\n def convert(self, mode): ...\n def __init__(self, instances, size, mode='poly'): ...\n def transpose(self, method): ...\n def crop(self, box): ...\n def resize(self, size, *args, **kwargs): ...\n def to(self, *args, **kwargs): ...\n def get_mask_tensor(self): ...\n def __len__(self): ...\n def __getitem__(self, item): ...\n def __iter__(self): ...\n def __next__(self): ...\n def __repr__(self): ...\n\n self.mode = mode\n self.size = tuple(size)\n\n next = __next__\n", "repository": "KelvinCPChiu/Mask-RCNN-Tless", "test_name": "test_convert", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001154.py"} {"focal_file": "maskrcnn_benchmark/structures/segmentation_mask.py", "focal_class": null, "focal_method": "crop", "tests": "import unittest\n\nclass Test_crop(unittest.TestCase):\n def test_crop(self):\n box = [400, 250, 500, 300]\n diff = self.L1(self.M.crop(box), self.P.crop(box))\n self.assertTrue(diff <= 1.0)\n", "method_code": " def crop(self, box):\n assert isinstance(box, (list, tuple, torch.Tensor)), str(type(box))\n current_width, current_height = self.size\n xmin, ymin, xmax, ymax = [round(float(b)) for b in box]\n assert xmin <= xmax and ymin <= ymax, str(box)\n xmin = min(max(xmin, 0), current_width - 1)\n ymin = min(max(ymin, 0), current_height - 1)\n xmax = min(max(xmax, 0), current_width)\n ymax = min(max(ymax, 0), current_height)\n xmax = max(xmax, xmin + 1)\n ymax = max(ymax, ymin + 1)\n width, height = (xmax - xmin, ymax - ymin)\n cropped_masks = self.masks[:, ymin:ymax, xmin:xmax]\n cropped_size = (width, height)\n return BinaryMaskList(cropped_masks, cropped_size)\n ", "context": "class BinaryMaskList(object):\n def crop(self, box): ...\n def __init__(self, masks, size): ...\n def transpose(self, method): ...\n def resize(self, size): ...\n def convert_to_polygon(self): ...\n def to(self, *args, **kwargs): ...\n def _findContours(self): ...\n def __len__(self): ...\n def __getitem__(self, index): ...\n def __iter__(self): ...\n def __repr__(self): ...\n\n self.masks = masks\n self.size = tuple(size)\n", "repository": "KelvinCPChiu/Mask-RCNN-Tless", "test_name": "test_crop", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001155.py"} {"focal_file": "maskrcnn_benchmark/structures/segmentation_mask.py", "focal_class": null, "focal_method": "resize", "tests": "import unittest\n\nclass Test_resize(unittest.TestCase):\n def test_resize(self):\n new_size = (50, 25)\n M_hat = self.M.resize(new_size)\n P_hat = self.P.resize(new_size)\n diff = self.L1(M_hat, P_hat)\n self.assertTrue(self.M.size == self.P.size)\n self.assertTrue(M_hat.size == P_hat.size)\n self.assertTrue(self.M.size != M_hat.size)\n self.assertTrue(diff <= 255.0)\n", "method_code": " def resize(self, size):\n try:\n iter(size)\n except TypeError:\n assert isinstance(size, (int, float))\n size = (size, size)\n width, height = map(int, size)\n assert width > 0\n assert height > 0\n resized_masks = interpolate(input=self.masks[None].float(), size=(height, width), mode='bilinear', align_corners=False)[0].type_as(self.masks)\n resized_size = (width, height)\n return BinaryMaskList(resized_masks, resized_size)\n ", "context": "class BinaryMaskList(object):\n def resize(self, size): ...\n def __init__(self, masks, size): ...\n def transpose(self, method): ...\n def crop(self, box): ...\n def convert_to_polygon(self): ...\n def to(self, *args, **kwargs): ...\n def _findContours(self): ...\n def __len__(self): ...\n def __getitem__(self, index): ...\n def __iter__(self): ...\n def __repr__(self): ...\n\n self.masks = masks\n self.size = tuple(size)\n", "repository": "KelvinCPChiu/Mask-RCNN-Tless", "test_name": "test_resize", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001156.py"} {"focal_file": "maskrcnn_benchmark/structures/segmentation_mask.py", "focal_class": null, "focal_method": "transpose", "tests": "import unittest\n\nclass Test_transpose(unittest.TestCase):\n def test_transpose(self):\n FLIP_LEFT_RIGHT = 0\n FLIP_TOP_BOTTOM = 1\n diff_hor = self.L1(self.M.transpose(FLIP_LEFT_RIGHT), self.P.transpose(FLIP_LEFT_RIGHT))\n diff_ver = self.L1(self.M.transpose(FLIP_TOP_BOTTOM), self.P.transpose(FLIP_TOP_BOTTOM))\n self.assertTrue(diff_hor <= 53250.0)\n self.assertTrue(diff_ver <= 42494.0)\n", "method_code": " def transpose(self, method):\n dim = 1 if method == FLIP_TOP_BOTTOM else 2\n flipped_masks = self.masks.flip(dim)\n return BinaryMaskList(flipped_masks, self.size)\n ", "context": "class BinaryMaskList(object):\n def transpose(self, method): ...\n def __init__(self, masks, size): ...\n def crop(self, box): ...\n def resize(self, size): ...\n def convert_to_polygon(self): ...\n def to(self, *args, **kwargs): ...\n def _findContours(self): ...\n def __len__(self): ...\n def __getitem__(self, index): ...\n def __iter__(self): ...\n def __repr__(self): ...\n\n self.masks = masks\n self.size = tuple(size)\n", "repository": "KelvinCPChiu/Mask-RCNN-Tless", "test_name": "test_transpose", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001157.py"} {"focal_file": "maskrcnn_benchmark/modeling/box_coder.py", "focal_class": "BoxCoder", "focal_method": "decode", "tests": "import unittest\n\nclass Test_BoxCoder_decode(unittest.TestCase):\n def test_box_decoder(self):\n \"\"\" Match unit test UtilsBoxesTest.TestBboxTransformRandom in\n caffe2/operators/generate_proposals_op_util_boxes_test.cc\n \"\"\"\n box_coder = BoxCoder(weights=(1.0, 1.0, 1.0, 1.0))\n bbox = torch.from_numpy(np.array([175.62031555, 20.91103172, 253.352005, 155.0145874, 169.24636841, 4.85241556, 228.8605957, 105.02092743, 181.77426147, 199.82876587, 192.88427734, 214.0255127, 174.36262512, 186.75761414, 296.19091797, 231.27906799, 22.73153877, 92.02596283, 135.5695343, 208.80291748]).astype(np.float32).reshape(-1, 4))\n deltas = torch.from_numpy(np.array([0.47861834, 0.13992102, 0.14961673, 0.71495209, 0.29915856, -0.35664671, 0.89018666, 0.70815367, -0.03852064, 0.44466892, 0.49492538, 0.71409376, 0.28052918, 0.02184832, 0.65289006, 1.05060139, -0.38172557, -0.08533806, -0.60335309, 0.79052375]).astype(np.float32).reshape(-1, 4))\n gt_bbox = np.array([206.949539, -30.715202, 297.387665, 244.448486, 143.871216, -83.342888, 290.502289, 121.053398, 177.430283, 198.666245, 196.295273, 228.703079, 152.251892, 145.431564, 387.215454, 274.594238, 5.06242, 11.040955, 66.328903, 269.686218]).astype(np.float32).reshape(-1, 4)\n results = box_coder.decode(deltas, bbox)\n np.testing.assert_allclose(results.detach().numpy(), gt_bbox, atol=0.0001)\n", "method_code": " def decode(self, rel_codes, boxes):\n \"\"\"\n From a set of original boxes and encoded relative box offsets,\n get the decoded boxes.\n \n Arguments:\n rel_codes (Tensor): encoded boxes\n boxes (Tensor): reference boxes.\n \"\"\"\n boxes = boxes.to(rel_codes.dtype)\n TO_REMOVE = 1\n widths = boxes[:, 2] - boxes[:, 0] + TO_REMOVE\n heights = boxes[:, 3] - boxes[:, 1] + TO_REMOVE\n ctr_x = boxes[:, 0] + 0.5 * widths\n ctr_y = boxes[:, 1] + 0.5 * heights\n wx, wy, ww, wh = self.weights\n dx = rel_codes[:, 0::4] / wx\n dy = rel_codes[:, 1::4] / wy\n dw = rel_codes[:, 2::4] / ww\n dh = rel_codes[:, 3::4] / wh\n dw = torch.clamp(dw, max=self.bbox_xform_clip)\n dh = torch.clamp(dh, max=self.bbox_xform_clip)\n pred_ctr_x = dx * widths[:, None] + ctr_x[:, None]\n pred_ctr_y = dy * heights[:, None] + ctr_y[:, None]\n pred_w = torch.exp(dw) * widths[:, None]\n pred_h = torch.exp(dh) * heights[:, None]\n pred_boxes = torch.zeros_like(rel_codes)\n pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w\n pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h\n pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w - 1\n pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h - 1\n return pred_boxes\n ", "context": "class BoxCoder(object):\n def decode(self, rel_codes, boxes): ...\n def __init__(self, weights, bbox_xform_clip=math.log(1000.0 / 16)): ...\n def encode(self, reference_boxes, proposals): ...\n\n self.weights = weights\n self.bbox_xform_clip = bbox_xform_clip\n", "repository": "KelvinCPChiu/Mask-RCNN-Tless", "test_name": "test_box_decoder", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001158.py"} {"focal_file": "maskrcnn_benchmark/utils/metric_logger.py", "focal_class": "MetricLogger", "focal_method": "update", "tests": "import unittest\n\nclass Test_MetricLogger_update(unittest.TestCase):\n def test_update(self):\n meter = MetricLogger()\n for i in range(10):\n meter.update(metric=float(i))\n m = meter.meters['metric']\n self.assertEqual(m.count, 10)\n self.assertEqual(m.total, 45)\n self.assertEqual(m.median, 4)\n self.assertEqual(m.avg, 4.5)\n", "method_code": " def update(self, value):\n self.deque.append(value)\n self.series.append(value)\n self.count += 1\n self.total += value\n ", "context": "class SmoothedValue(object):\n def update(self, value): ...\n def __init__(self, window_size=20): ...\n def median(self): ...\n def avg(self): ...\n def global_avg(self): ...\n\n self.deque = deque(maxlen=window_size)\n self.series = []\n self.total = 0.0\n self.count = 0\n", "repository": "KelvinCPChiu/Mask-RCNN-Tless", "test_name": "test_update", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001159.py"} {"focal_file": "maskrcnn_benchmark/utils/checkpoint.py", "focal_class": "Checkpointer", "focal_method": "load", "tests": "import unittest\n\nclass Test_Checkpointer_load(unittest.TestCase):\n def test_from_last_checkpoint_model(self):\n for trained_model, fresh_model in [(self.create_model(), self.create_model()), (nn.DataParallel(self.create_model()), self.create_model()), (self.create_model(), nn.DataParallel(self.create_model())), (nn.DataParallel(self.create_model()), nn.DataParallel(self.create_model()))]:\n with TemporaryDirectory() as f:\n checkpointer = Checkpointer(trained_model, save_dir=f, save_to_disk=True)\n checkpointer.save('checkpoint_file')\n fresh_checkpointer = Checkpointer(fresh_model, save_dir=f)\n self.assertTrue(fresh_checkpointer.has_checkpoint())\n self.assertEqual(fresh_checkpointer.get_checkpoint_file(), os.path.join(f, 'checkpoint_file.pth'))\n _ = fresh_checkpointer.load()\n for trained_p, loaded_p in zip(trained_model.parameters(), fresh_model.parameters()):\n self.assertFalse(id(trained_p) == id(loaded_p))\n self.assertTrue(trained_p.equal(loaded_p))\n", "method_code": " def load(self, f=None):\n if self.has_checkpoint():\n f = self.get_checkpoint_file()\n if not f:\n self.logger.info('No checkpoint found. Initializing model from scratch')\n return {}\n self.logger.info('Loading checkpoint from {}'.format(f))\n checkpoint = self._load_file(f)\n self._load_model(checkpoint)\n if 'optimizer' in checkpoint and self.optimizer:\n self.logger.info('Loading optimizer from {}'.format(f))\n self.optimizer.load_state_dict(checkpoint.pop('optimizer'))\n if 'scheduler' in checkpoint and self.scheduler:\n self.logger.info('Loading scheduler from {}'.format(f))\n self.scheduler.load_state_dict(checkpoint.pop('scheduler'))\n return checkpoint\n ", "context": "class Checkpointer(object):\n def load(self, f=None): ...\n def __init__(self, model, optimizer=None, scheduler=None, save_dir='', save_to_disk=None, logger=None): ...\n def save(self, name, **kwargs): ...\n def has_checkpoint(self): ...\n def get_checkpoint_file(self): ...\n def tag_last_checkpoint(self, last_filename): ...\n def _load_file(self, f): ...\n def _load_model(self, checkpoint): ...\n\n self.model = model\n self.optimizer = optimizer\n self.scheduler = scheduler\n self.save_dir = save_dir\n self.save_to_disk = save_to_disk\n self.logger = logger\n", "repository": "KelvinCPChiu/Mask-RCNN-Tless", "test_name": "test_from_last_checkpoint_model", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001160.py"} {"focal_file": "qml/python/bs4/element.py", "focal_class": null, "focal_method": "decode", "tests": "import unittest\n\nclass Test_decode(unittest.TestCase):\n def test_real_shift_jis_document(self):\n shift_jis_html = b'
\\x82\\xb1\\x82\\xea\\x82\\xcdShift-JIS\\x82\\xc5\\x83R\\x81[\\x83f\\x83B\\x83\\x93\\x83O\\x82\\xb3\\x82\\xea\\x82\\xbd\\x93\\xfa\\x96{\\x8c\\xea\\x82\\xcc\\x83t\\x83@\\x83C\\x83\\x8b\\x82\\xc5\\x82\\xb7\\x81B
'\n unicode_html = shift_jis_html.decode('shift-jis')\n soup = self.soup(unicode_html)\n self.assertEqual(soup.encode('utf-8'), unicode_html.encode('utf-8'))\n self.assertEqual(soup.encode('euc_jp'), unicode_html.encode('euc_jp'))\n\n def test_real_hebrew_document(self):\n hebrew_document = b'Hebrew (ISO 8859-8) in Visual Directionality

Hebrew (ISO 8859-8) in Visual Directionality

\\xed\\xe5\\xec\\xf9'\n soup = self.soup(hebrew_document, from_encoding='iso8859-8')\n assert soup.original_encoding in ('iso8859-8', 'iso-8859-8')\n self.assertEqual(soup.encode('utf-8'), hebrew_document.decode('iso8859-8').encode('utf-8'))\n", "method_code": " def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):\n \"\"\"Returns a Unicode representation of this tag and its contents.\n \n :param eventual_encoding: The tag is destined to be\n encoded into this encoding. This method is _not_\n responsible for performing that encoding. This information\n is passed in so that it can be substituted in if the\n document contains a tag that mentions the document's\n encoding.\n \"\"\"\n if not isinstance(formatter, Formatter) and (not callable(formatter)):\n formatter = self._formatter_for_name(formatter)\n attrs = []\n if self.attrs:\n for key, val in sorted(self.attrs.items()):\n if val is None:\n decoded = key\n else:\n if isinstance(val, list) or isinstance(val, tuple):\n val = ' '.join(val)\n elif not isinstance(val, str):\n val = str(val)\n elif isinstance(val, AttributeValueWithCharsetSubstitution) and eventual_encoding is not None:\n val = val.encode(eventual_encoding)\n text = self.format_string(val, formatter)\n decoded = str(key) + '=' + EntitySubstitution.quoted_attribute_value(text)\n attrs.append(decoded)\n close = ''\n closeTag = ''\n prefix = ''\n if self.prefix:\n prefix = self.prefix + ':'\n if self.is_empty_element:\n close = ''\n if isinstance(formatter, Formatter):\n close = formatter.void_element_close_prefix or close\n else:\n closeTag = '' % (prefix, self.name)\n pretty_print = self._should_pretty_print(indent_level)\n space = ''\n indent_space = ''\n if indent_level is not None:\n indent_space = ' ' * (indent_level - 1)\n if pretty_print:\n space = indent_space\n indent_contents = indent_level + 1\n else:\n indent_contents = None\n contents = self.decode_contents(indent_contents, eventual_encoding, formatter)\n if self.hidden:\n s = contents\n else:\n s = []\n attribute_string = ''\n if attrs:\n attribute_string = ' ' + ' '.join(attrs)\n if indent_level is not None:\n s.append(indent_space)\n s.append('<%s%s%s%s>' % (prefix, self.name, attribute_string, close))\n if pretty_print:\n s.append('\\n')\n s.append(contents)\n if pretty_print and contents and (contents[-1] != '\\n'):\n s.append('\\n')\n if pretty_print and closeTag:\n s.append(space)\n s.append(closeTag)\n if indent_level is not None and closeTag and self.next_sibling:\n s.append('\\n')\n s = ''.join(s)\n return s\n ", "context": "class Tag(PageElement):\n def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None, is_xml=None): ...\n def __copy__(self): ...\n def is_empty_element(self): ...\n def string(self): ...\n def string(self, string): ...\n def _all_strings(self, strip=False, types=(NavigableString, CData)): ...\n def stripped_strings(self): ...\n def get_text(self, separator='', strip=False, types=(NavigableString, CData)): ...\n def decompose(self): ...\n def clear(self, decompose=False): ...\n def index(self, element): ...\n def get(self, key, default=None): ...\n def get_attribute_list(self, key, default=None): ...\n def has_attr(self, key): ...\n def __hash__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __contains__(self, x): ...\n def __bool__(self): ...\n def __setitem__(self, key, value): ...\n def __delitem__(self, key): ...\n def __call__(self, *args, **kwargs): ...\n def __getattr__(self, tag): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __repr__(self, encoding='unicode-escape'): ...\n def __unicode__(self): ...\n def __str__(self): ...\n def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, indent_level=None, formatter='minimal', errors='xmlcharrefreplace'): ...\n def _should_pretty_print(self, indent_level): ...\n def prettify(self, encoding=None, formatter='minimal'): ...\n def decode_contents(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def encode_contents(self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): ...\n def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): ...\n def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): ...\n def children(self): ...\n def descendants(self): ...\n def select_one(self, selector): ...\n def select(self, selector, _candidate_generator=None, limit=None): ...\n def childGenerator(self): ...\n def recursiveChildGenerator(self): ...\n def has_key(self, key): ...\n\n self.name = name\n self.namespace = namespace\n self.prefix = prefix\n self.preserve_whitespace_tags = preserve_whitespace_tags\n self.attrs = attrs\n self.contents = []\n self.hidden = False\n\n parserClass = _alias('parser_class')\n isSelfClosing = is_empty_element\n strings = property(_all_strings)\n getText = get_text\n text = property(get_text)\n findChild = find\n findAll = find_all\n findChildren = find_all\n _selector_combinators = ['>', '+', '~']\n _select_debug = False\n quoted_colon = re.compile('\"[^\"]*:[^\"]*\"')\n", "repository": "0312birdzhang/harbour-weblogin-demo", "test_name": "test_real_shift_jis_document", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001161.py"} {"focal_file": "qml/py/bs4/element.py", "focal_class": null, "focal_method": "decode", "tests": "import unittest\n\nclass Test_decode(unittest.TestCase):\n def test_real_shift_jis_document(self):\n shift_jis_html = b'
\\x82\\xb1\\x82\\xea\\x82\\xcdShift-JIS\\x82\\xc5\\x83R\\x81[\\x83f\\x83B\\x83\\x93\\x83O\\x82\\xb3\\x82\\xea\\x82\\xbd\\x93\\xfa\\x96{\\x8c\\xea\\x82\\xcc\\x83t\\x83@\\x83C\\x83\\x8b\\x82\\xc5\\x82\\xb7\\x81B
'\n unicode_html = shift_jis_html.decode('shift-jis')\n soup = self.soup(unicode_html)\n self.assertEqual(soup.encode('utf-8'), unicode_html.encode('utf-8'))\n self.assertEqual(soup.encode('euc_jp'), unicode_html.encode('euc_jp'))\n\n def test_real_hebrew_document(self):\n hebrew_document = b'Hebrew (ISO 8859-8) in Visual Directionality

Hebrew (ISO 8859-8) in Visual Directionality

\\xed\\xe5\\xec\\xf9'\n soup = self.soup(hebrew_document, from_encoding='iso8859-8')\n assert soup.original_encoding in ('iso8859-8', 'iso-8859-8')\n self.assertEqual(soup.encode('utf-8'), hebrew_document.decode('iso8859-8').encode('utf-8'))\n", "method_code": " def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):\n \"\"\"Returns a Unicode representation of this tag and its contents.\n \n :param eventual_encoding: The tag is destined to be\n encoded into this encoding. This method is _not_\n responsible for performing that encoding. This information\n is passed in so that it can be substituted in if the\n document contains a tag that mentions the document's\n encoding.\n \"\"\"\n if not isinstance(formatter, collections.Callable):\n formatter = self._formatter_for_name(formatter)\n attrs = []\n if self.attrs:\n for key, val in sorted(self.attrs.items()):\n if val is None:\n decoded = key\n else:\n if isinstance(val, list) or isinstance(val, tuple):\n val = ' '.join(val)\n elif not isinstance(val, str):\n val = str(val)\n elif isinstance(val, AttributeValueWithCharsetSubstitution) and eventual_encoding is not None:\n val = val.encode(eventual_encoding)\n text = self.format_string(val, formatter)\n decoded = str(key) + '=' + EntitySubstitution.quoted_attribute_value(text)\n attrs.append(decoded)\n close = ''\n closeTag = ''\n prefix = ''\n if self.prefix:\n prefix = self.prefix + ':'\n if self.is_empty_element:\n close = '/'\n else:\n closeTag = '' % (prefix, self.name)\n pretty_print = self._should_pretty_print(indent_level)\n space = ''\n indent_space = ''\n if indent_level is not None:\n indent_space = ' ' * (indent_level - 1)\n if pretty_print:\n space = indent_space\n indent_contents = indent_level + 1\n else:\n indent_contents = None\n contents = self.decode_contents(indent_contents, eventual_encoding, formatter)\n if self.hidden:\n s = contents\n else:\n s = []\n attribute_string = ''\n if attrs:\n attribute_string = ' ' + ' '.join(attrs)\n if indent_level is not None:\n s.append(indent_space)\n s.append('<%s%s%s%s>' % (prefix, self.name, attribute_string, close))\n if pretty_print:\n s.append('\\n')\n s.append(contents)\n if pretty_print and contents and (contents[-1] != '\\n'):\n s.append('\\n')\n if pretty_print and closeTag:\n s.append(space)\n s.append(closeTag)\n if indent_level is not None and closeTag and self.next_sibling:\n s.append('\\n')\n s = ''.join(s)\n return s\n ", "context": "class Tag(PageElement):\n def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None, is_xml=None): ...\n def __copy__(self): ...\n def is_empty_element(self): ...\n def string(self): ...\n def string(self, string): ...\n def _all_strings(self, strip=False, types=(NavigableString, CData)): ...\n def stripped_strings(self): ...\n def get_text(self, separator='', strip=False, types=(NavigableString, CData)): ...\n def decompose(self): ...\n def clear(self, decompose=False): ...\n def index(self, element): ...\n def get(self, key, default=None): ...\n def get_attribute_list(self, key, default=None): ...\n def has_attr(self, key): ...\n def __hash__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __contains__(self, x): ...\n def __bool__(self): ...\n def __setitem__(self, key, value): ...\n def __delitem__(self, key): ...\n def __call__(self, *args, **kwargs): ...\n def __getattr__(self, tag): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __repr__(self, encoding='unicode-escape'): ...\n def __unicode__(self): ...\n def __str__(self): ...\n def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, indent_level=None, formatter='minimal', errors='xmlcharrefreplace'): ...\n def _should_pretty_print(self, indent_level): ...\n def prettify(self, encoding=None, formatter='minimal'): ...\n def decode_contents(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def encode_contents(self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): ...\n def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): ...\n def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): ...\n def children(self): ...\n def descendants(self): ...\n def select_one(self, selector): ...\n def select(self, selector, _candidate_generator=None, limit=None): ...\n def childGenerator(self): ...\n def recursiveChildGenerator(self): ...\n def has_key(self, key): ...\n\n self.name = name\n self.namespace = namespace\n self.prefix = prefix\n self.preserve_whitespace_tags = preserve_whitespace_tags\n self.attrs = attrs\n self.contents = []\n self.hidden = False\n\n parserClass = _alias('parser_class')\n isSelfClosing = is_empty_element\n strings = property(_all_strings)\n getText = get_text\n text = property(get_text)\n findChild = find\n findAll = find_all\n findChildren = find_all\n _selector_combinators = ['>', '+', '~']\n _select_debug = False\n quoted_colon = re.compile('\"[^\"]*:[^\"]*\"')\n", "repository": "0312birdzhang/harbour-aitizhijia", "test_name": "test_real_shift_jis_document", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001162.py"} {"focal_file": "yaphc/cookies.py", "focal_class": null, "focal_method": "update_from_response", "tests": "import unittest\n\nclass Test_update_from_response(unittest.TestCase):\n def test_update_from_response(self):\n response = {'set-cookie': 'mycookie=myvalue'}\n request_url = 'https://some.domain.com:1234/some/path?some=query'\n self.jar.update_from_response(response, request_url)\n cookie_list = self.jar.cookies\n cookie = cookie_list[0]\n self.assertFalse(self.jar.empty)\n self.assertEqual(len(cookie_list), 1)\n self.assertEqual(cookie.name, 'mycookie')\n self.assertEqual(cookie.value, 'myvalue')\n\n def test_update_from_response_changes_existing_cookie(self):\n response = {'set-cookie': 'cookie=newvalue'}\n request_url = 'http://some.domain.com/some/path'\n self.jar.update_from_response(response, request_url)\n cookie_list = self.jar.cookies\n cookie = cookie_list[0]\n self.assertFalse(self.jar.empty)\n self.assertEqual(len(cookie_list), 1)\n self.assertEqual(cookie.name, 'cookie')\n self.assertEqual(cookie.value, 'newvalue')\n", "method_code": " def update_from_response(self, response, request_url):\n cookie_header = response.get('set-cookie')\n if not cookie_header:\n return\n cookies = self.parser.parse_header(cookie_header, request_url)\n self.add_cookies(cookies)\n ", "context": "class CookieJar(object):\n def update_from_response(self, response, request_url): ...\n def __init__(self, cookies=None, persister=NullPersister()): ...\n def empty(self): ...\n def find_cookie(self, cookie): ...\n def add_cookies(self, cookies): ...\n def should_send_cookie(self, cookie, scheme, domain, path): ...\n def cookies_to_send_header(self, request_url): ...\n def cookies_to_send(self, request_url): ...\n def cookies(self): ...\n def save(self): ...\n def load(self): ...\n\n self.parser = CookieParser()\n self._cookies = []\n self.persister = persister\n", "repository": "muccg/yaphc", "test_name": "test_update_from_response", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001163.py"} {"focal_file": "yaphc/cookies.py", "focal_class": null, "focal_method": "cookies_to_send", "tests": "import unittest\n\nclass Test_cookies_to_send(unittest.TestCase):\n def test_cookies_to_send_no_cookie(self):\n cookie_list = self.jar.cookies_to_send('http://some.domain.com/some/path')\n self.assertEqual(len(cookie_list), 0)\n\n def test_cookies_to_send_everything_matches(self):\n cookie_list = self.jar.cookies_to_send('http://some.domain.com/some/path')\n self.assertEqual(len(cookie_list), 1)\n cookie = cookie_list[0]\n self.assertEquals(cookie.name, 'cookie')\n self.assertEquals(cookie.value, 'value')\n\n def test_cookies_to_send_other_domain(self):\n cookie_list = self.jar.cookies_to_send('http://other.domain.com/some/path')\n self.assertEqual(len(cookie_list), 0)\n\n def test_cookies_to_send_other_path(self):\n cookie_list = self.jar.cookies_to_send('http://some.domain.com/someother/path')\n self.assertEqual(len(cookie_list), 0)\n\n def test_cookies_to_send_root_path(self):\n cookie_list = self.jar.cookies_to_send('http://some.domain.com')\n self.assertEqual(len(cookie_list), 0)\n\n def test_cookies_to_send_cookie_expired(self):\n past_time = time.gmtime(time.time() - 1)\n jar = self.build_jar(expires_on=past_time)\n cookie_list = jar.cookies_to_send('http://some.domain.com/some/path')\n self.assertEqual(len(cookie_list), 0)\n", "method_code": " def cookies_to_send(self, request_url):\n url = urlparse(request_url)\n domain = url.hostname\n \n def most_specific_paths_first(cookie1, cookie2):\n return cmp(cookie2.path, cookie1.path)\n return sorted([cookie for cookie in self._cookies if self.should_send_cookie(cookie, url.scheme, domain, url.path)], cmp=most_specific_paths_first)\n ", "context": "class CookieJar(object):\n def cookies_to_send(self, request_url): ...\n def __init__(self, cookies=None, persister=NullPersister()): ...\n def empty(self): ...\n def find_cookie(self, cookie): ...\n def add_cookies(self, cookies): ...\n def update_from_response(self, response, request_url): ...\n def should_send_cookie(self, cookie, scheme, domain, path): ...\n def cookies_to_send_header(self, request_url): ...\n def cookies(self): ...\n def save(self): ...\n def load(self): ...\n\n self.parser = CookieParser()\n self._cookies = []\n self.persister = persister\n", "repository": "muccg/yaphc", "test_name": "test_cookies_to_send_no_cookie", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001164.py"} {"focal_file": "yaphc/cookies.py", "focal_class": null, "focal_method": "cookies_to_send_header", "tests": "import unittest\n\nclass Test_cookies_to_send_header(unittest.TestCase):\n def test_cookies_to_send_header_no_cookies(self):\n headers_map = self.jar.cookies_to_send_header('http://some.otherdomain.com')\n self.assertEqual(len(headers_map), 0)\n\n def test_cookies_to_send_header_2_cookies(self):\n headers_map = self.jar.cookies_to_send_header('http://some.domain.com/some/path/something')\n self.assertEqual(len(headers_map), 1)\n self.assertEqual(headers_map['Cookie'], 'othercookie=value; cookie=value')\n", "method_code": " def cookies_to_send_header(self, request_url):\n cookies = self.cookies_to_send(request_url)\n if not cookies:\n return {}\n return {'Cookie': self.parser.write_header_value(cookies)}\n ", "context": "class CookieJar(object):\n def cookies_to_send_header(self, request_url): ...\n def __init__(self, cookies=None, persister=NullPersister()): ...\n def empty(self): ...\n def find_cookie(self, cookie): ...\n def add_cookies(self, cookies): ...\n def update_from_response(self, response, request_url): ...\n def should_send_cookie(self, cookie, scheme, domain, path): ...\n def cookies_to_send(self, request_url): ...\n def cookies(self): ...\n def save(self): ...\n def load(self): ...\n\n self.parser = CookieParser()\n self._cookies = []\n self.persister = persister\n", "repository": "muccg/yaphc", "test_name": "test_cookies_to_send_header_no_cookies", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001165.py"} {"focal_file": "tests/test_service.py", "focal_class": null, "focal_method": "_get_test", "tests": "import unittest\n\nclass Test_get_test(unittest.TestCase):\n def test_get_objects(self):\n \"\"\" Create objects and get it from spv with different filter \"\"\"\n objects = self.imp.call('spv.services', 'create_objects', [{'address': 'test/get_objects/1'}, {'address': 'test/get_objects/2', 'infos': {'key_toto': 'toto'}}])\n self.objects.append(objects.keys())\n\n def test_result(ret, objects, key):\n self.assertEqual(ret[key]['obj_id'], objects[key]['obj_id'])\n self.assertEqual(ret[key]['address'], objects[key]['address'])\n self.assertEqual(ret[key]['creation_date'], objects[key]['creation_date'])\n self._get_test([['obj_id', 'obj_id'], ['address', 'address'], ['creation_date', 'creation_date']], objects, 'get_objects', test_result)\n keys = objects.keys()\n keys.sort()\n ret = self.imp.call('spv.services', 'get_objects', {'info_key': 'key_toto'})\n self.assertEqual(len(ret), 1)\n test_result(ret, objects, keys[1])\n ret = self.imp.call('spv.services', 'get_objects', {'info_value': 'toto'})\n self.assertEqual(len(ret), 1)\n test_result(ret, objects, keys[1])\n ret = self.imp.call('spv.services', 'get_objects', {'creation_date': objects[keys[0]]['creation_date']})\n result_keys = [key for key in ret.keys() if key in keys]\n self.assertEqual(len(result_keys), 2)\n\n def test_get_checks(self):\n \"\"\" Create checks and get it from spv with different filter \"\"\"\n checks = self.imp.call('spv.services', 'create_checks', [{'plugin': 'toto', 'plugin_check': 'test1', 'name': 'This is test 1', 'repeat': 10, 'repeat_on_error': 10}, {'plugin': 'toto', 'plugin_check': 'test2', 'name': 'This is test 2', 'repeat': 10, 'repeat_on_error': 10, 'infos': {'test_key_': 'test_val_'}}])\n self.checks.append(checks.keys())\n\n def test_result(ret, checks, key):\n self.assertEqual(ret[key]['chk_id'], checks[key]['chk_id'])\n self.assertEqual(ret[key]['plugin'], checks[key]['plugin'])\n self.assertEqual(ret[key]['plugin_check'], checks[key]['plugin_check'])\n self._get_test([['chk_id', 'chk_id'], ['plugin', 'plugin'], ['plugin_check', 'plugin_check']], checks, 'get_plugin_checks', test_result)\n keys = checks.keys()\n keys.sort()\n ret = self.imp.call('spv.services', 'get_plugin_checks', {'info_key': 'test_key_'})\n self.assertEqual(len(ret), 1)\n test_result(ret, checks, keys[1])\n ret = self.imp.call('spv.services', 'get_plugin_checks', {'info_value': 'test_val_'})\n self.assertEqual(len(ret), 1)\n test_result(ret, checks, keys[1])\n ret = self.imp.call('spv.services', 'get_plugin_checks', {'plugin_name': 'toto'})\n self.assertEqual(len(ret), 2)\n", "method_code": " def _get_test(self, params, data, api_func, test_func):\n \"\"\" Generic test for test_get_* functions\n \n @params: list of key value for research in spv API\n [\n [key, param], ...\n ]\n @data: value returned when create an groups/object/checks\n @api_func: function of the spv API to call\n @test_func: function to call to validate the call to api_func\n \n \"\"\"\n for param, param_key in params:\n for key in data.keys():\n ret = self.imp.call('spv.services', api_func, {param: data[key][param_key]})\n test_func(ret, data, key)\n all_groups = self.imp.call('spv.services', api_func)\n result_keys = [key for key in all_groups.keys() if key in data.keys()]\n self.assertEqual(len(result_keys), len(data.keys()))\n ", "context": "class ServiceTest(unittest.TestCase):\n def _get_test(self, params, data, api_func, test_func): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _get_status_tests_create_data(self): ...\n def _get_status_test_value(self, data, groups, objects, checks): ...\n def _check_get_status_info(self, data, type, info, id_name): ...\n def test_delete_groups(self): ...\n def test_delete_checks(self): ...\n def test_delete_objects(self): ...\n def test_create_group(self): ...\n def test_create_checks(self): ...\n def test_error_create_checks(self): ...\n def test_create_objects(self): ...\n def test_error_create_objects(self): ...\n def test_get_groups(self): ...\n def test_get_objects(self): ...\n def test_get_checks(self): ...\n def test_update_groups(self): ...\n def test_update_checks(self): ...\n def test_update_objects(self): ...\n", "repository": "SmartJog/webengine-spv", "test_name": "test_get_objects", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001166.py"} {"focal_file": "tests/test_service_get_checks.py", "focal_class": null, "focal_method": "_get_status_tests_create_data", "tests": "import unittest\n\nclass Test_get_status_tests_create_data(unittest.TestCase):\n def test_get_status_check_status(self):\n \"\"\" ['get_checks'] Get every status with on specific status \"\"\"\n self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'status': ['FINISHED', 'ERROR']})\n for status in ret['status']:\n self.assertTrue(status['check_status'] in ['FINISHED', 'ERROR'])\n ret_finish = self.imp.call('spv.services', 'get_checks', {'status': 'FINISHED'})\n self.assertNotEqual(len(ret), 0)\n for status in ret_finish['status']:\n self.assertEqual(status['check_status'], 'FINISHED')\n len_error = len(self.imp.call('spv.services', 'get_checks', {'status': 'ERROR'})['status'])\n self.assertEqual(len(ret['status']), len(ret_finish['status']) + len_error)\n\n def test_get_status_status_id(self):\n \"\"\" ['get_checks'] Get status with a additional info on status \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'group_id': groups.keys()[0]})\n ret_status = self.imp.call('spv.services', 'set_checks_status', [{'status_id': ret['status'][0]['status_id'], 'sequence_id': 0, 'status': 'coucou !', 'message': 'salut', 'status_infos': {'key_status': 'value_status'}}])\n ret = self.imp.call('spv.services', 'get_checks', {'group_id': groups.keys()[0], 'get_status_infos': True})\n self.assertEqual(ret['status'][0]['status_infos'].keys(), ['key_status'])\n self.assertEqual(ret['status'][0]['status_infos']['key_status']['key'], 'key_status')\n self.assertEqual(ret['status'][0]['status_infos']['key_status']['value'], 'value_status')\n self.assertEqual(ret['status'][0]['status_infos']['key_status']['status_id'], ret['status'][0]['status_id'])\n\n def test_get_status_limit(self):\n \"\"\" ['get_checks'] Get object/checks/grousp by group_id with a limit \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n checks_second = self.imp.call('spv.services', 'create_checks', [{'plugin': '1', 'plugin_check': '2', 'name': '3', 'repeat': 100, 'repeat_on_error': 100, 'group_id': groups.keys()[0]}])\n self.checks.append(checks_second.keys())\n ret = self.imp.call('spv.services', 'get_checks', {'group_id': groups.keys()[0], 'limit': 1})\n self.assertEqual(len(ret['checks']), 1)\n ret = self.imp.call('spv.services', 'get_checks', {'group_id': groups.keys()[0]})\n self.assertEqual(len(ret['checks']), 2)\n\n def test_get_status_detailed_infos(self):\n \"\"\" ['get_checks'] Test get_status with 'get_detailed_infos' to False\"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'group_id': groups.keys()[0], 'get_check_infos': True, 'get_detailed_infos': False})\n self.assertEqual(ret['checks'][ret['checks'].keys()[0]]['check_infos'], {'key_toto': 'value_toto'})\n", "method_code": " def _get_status_tests_create_data(self):\n \"\"\" Test create object,group,check for get_status tests \"\"\"\n groups = self.imp.call('spv.services', 'create_groups', ['test_groups'])\n self.groups.append(groups.keys())\n objects = self.imp.call('spv.services', 'create_objects', [{'address': 'test_address', 'infos': {'key_toto': 'value_toto'}, 'group_id': groups.keys()[0]}])\n self.objects.append(objects.keys())\n checks = self.imp.call('spv.services', 'create_checks', [{'plugin': 'hey', 'plugin_check': 'salut', 'name': 'toi', 'repeat': 100, 'repeat_on_error': 100, 'infos': {'key_toto': 'value_toto'}, 'group_id': groups.keys()[0]}])\n self.checks.append(checks.keys())\n return [groups, objects, checks]\n ", "context": "class ServiceTest(unittest.TestCase):\n def _get_status_tests_create_data(self): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _get_status_test_value(self, data, groups, objects, checks): ...\n def test_get_status_check_status(self): ...\n def test_get_status_group_name(self): ...\n def test_get_status_object_address(self): ...\n def test_get_status_plugin_name(self): ...\n def test_get_status_plugin_check(self): ...\n def test_get_status_group_id(self): ...\n def test_get_status_check_id(self): ...\n def test_get_status_status_id(self): ...\n def test_get_status_limit(self): ...\n def _check_get_status_info(self, data, type, info, id_name): ...\n def test_get_status_object_info(self): ...\n def test_get_status_check_info(self): ...\n def test_get_status_detailed_infos(self): ...\n def test_get_checks_params_none(self): ...\n def test_create_status(self): ...\n def test_update_check(self): ...\n", "repository": "SmartJog/webengine-spv", "test_name": "test_get_status_check_status", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001167.py"} {"focal_file": "tests/test_service_get_checks.py", "focal_class": null, "focal_method": "_get_status_test_value", "tests": "import unittest\n\nclass Test_get_status_test_value(unittest.TestCase):\n def test_get_status_group_name(self):\n \"\"\" ['get_checks'] Get every status with on specific group_name \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'group_name': [groups.values()[0]['name']]})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_object_address(self):\n \"\"\" ['get_checks'] Get every status with on specific object address \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'object_address': objects.values()[0]['address']})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_plugin_name(self):\n \"\"\" ['get_checks'] Get every status with on specific plugin name \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'plugin_name': checks.values()[0]['plugin']})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_plugin_check(self):\n \"\"\" ['get_checks'] Get every status with on specific plugin check \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'plugin_check': checks.values()[0]['plugin_check']})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_group_id(self):\n \"\"\" ['get_checks'] Get every status with on specific groups_id \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'group_id': groups.keys()[0]})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_check_id(self):\n \"\"\" ['get_checks'] Get every status with on specific check_id \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n checks_second = self.imp.call('spv.services', 'create_checks', [{'plugin': '1', 'plugin_check': '2', 'name': '3', 'repeat': 100, 'repeat_on_error': 100, 'group_id': groups.keys()[0]}])\n self.checks.append(checks_second.keys())\n ret = self.imp.call('spv.services', 'get_checks', {'check_id': checks.keys()[0]})\n self._get_status_test_value(ret, groups, objects, checks)\n", "method_code": " def _get_status_test_value(self, data, groups, objects, checks):\n keys = data.keys()\n keys.sort()\n self.assertTrue(keys == ['checks', 'groups', 'objects', 'status'])\n self.assertTrue(data['checks'][checks.keys()[0]]['name'] == 'toi')\n self.assertTrue(data['groups'][groups.keys()[0]]['name'] == 'test_groups')\n self.assertTrue(data['objects'][objects.keys()[0]]['address'] == 'test_address')\n self.assertTrue(data['status'][0]['grp_id'] == groups.keys()[0])\n self.assertTrue(data['status'][0]['chk_id'] == checks.keys()[0])\n self.assertTrue(data['status'][0]['obj_id'] == objects.keys()[0])\n ", "context": "class ServiceTest(unittest.TestCase):\n def _get_status_test_value(self, data, groups, objects, checks): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _get_status_tests_create_data(self): ...\n def test_get_status_check_status(self): ...\n def test_get_status_group_name(self): ...\n def test_get_status_object_address(self): ...\n def test_get_status_plugin_name(self): ...\n def test_get_status_plugin_check(self): ...\n def test_get_status_group_id(self): ...\n def test_get_status_check_id(self): ...\n def test_get_status_status_id(self): ...\n def test_get_status_limit(self): ...\n def _check_get_status_info(self, data, type, info, id_name): ...\n def test_get_status_object_info(self): ...\n def test_get_status_check_info(self): ...\n def test_get_status_detailed_infos(self): ...\n def test_get_checks_params_none(self): ...\n def test_create_status(self): ...\n def test_update_check(self): ...\n", "repository": "SmartJog/webengine-spv", "test_name": "test_get_status_group_name", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001168.py"} {"focal_file": "tests/test_service_get_checks.py", "focal_class": null, "focal_method": "_check_get_status_info", "tests": "import unittest\n\nclass Test_check_get_status_info(unittest.TestCase):\n def test_get_status_object_info(self):\n \"\"\" ['get_checks'] Get object with additional info \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'group_id': groups.keys()[0], 'get_object_infos': True})\n self._check_get_status_info(ret, 'objects', 'object_infos', 'obj_id')\n\n def test_get_status_check_info(self):\n \"\"\" ['get_checks'] Get check with additional info \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_checks', {'group_id': groups.keys()[0], 'get_check_infos': True})\n self._check_get_status_info(ret, 'checks', 'check_infos', 'chk_id')\n", "method_code": " def _check_get_status_info(self, data, type, info, id_name):\n \"\"\" Generic funtionc to test get_status with additional info\"\"\"\n id = data[type].keys()[0]\n self.assertTrue(info in data[type][id].keys())\n infos = data[type][id][info]\n self.assertTrue('key_toto' in infos.keys())\n self.assertEqual(infos['key_toto'][id_name], id)\n self.assertEqual(infos['key_toto']['key'], 'key_toto')\n self.assertEqual(infos['key_toto']['value'], 'value_toto')\n ", "context": "class ServiceTest(unittest.TestCase):\n def _check_get_status_info(self, data, type, info, id_name): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _get_status_tests_create_data(self): ...\n def _get_status_test_value(self, data, groups, objects, checks): ...\n def test_get_status_check_status(self): ...\n def test_get_status_group_name(self): ...\n def test_get_status_object_address(self): ...\n def test_get_status_plugin_name(self): ...\n def test_get_status_plugin_check(self): ...\n def test_get_status_group_id(self): ...\n def test_get_status_check_id(self): ...\n def test_get_status_status_id(self): ...\n def test_get_status_limit(self): ...\n def test_get_status_object_info(self): ...\n def test_get_status_check_info(self): ...\n def test_get_status_detailed_infos(self): ...\n def test_get_checks_params_none(self): ...\n def test_create_status(self): ...\n def test_update_check(self): ...\n", "repository": "SmartJog/webengine-spv", "test_name": "test_get_status_object_info", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001169.py"} {"focal_file": "tests/test_service_get_status.py", "focal_class": null, "focal_method": "_get_status_tests_create_data", "tests": "import unittest\n\nclass Test_get_status_tests_create_data(unittest.TestCase):\n def test_get_status_check_status(self):\n \"\"\" ['get_status'] Get every status with on specific status \"\"\"\n self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'status': ['FINISHED', 'ERROR']})\n for status in ret['status']:\n self.assertTrue(ret['status'][status]['check_status'] in ['FINISHED', 'ERROR'])\n ret_finish = self.imp.call('spv.services', 'get_status', {'status': 'FINISHED'})\n self.assertNotEqual(len(ret), 0)\n for status in ret_finish['status']:\n self.assertEqual(ret_finish['status'][status]['check_status'], 'FINISHED')\n len_error = len(self.imp.call('spv.services', 'get_status', {'status': 'ERROR'})['status'])\n self.assertEqual(len(ret['status']), len(ret_finish['status']) + len_error)\n\n def test_get_status_status_id(self):\n \"\"\" ['get_status'] Get status with a additional info on status \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'group_id': groups.keys()[0], 'get_status_infos': True})\n ret_status = self.imp.call('spv.services', 'set_checks_status', [{'status_id': ret['status'][ret['status'].keys()[0]]['status_id'], 'sequence_id': 0, 'status': 'coucou !', 'message': 'salut', 'status_infos': {'key_status': 'value_status'}}])\n ret = self.imp.call('spv.services', 'get_status', {'group_id': groups.keys()[0], 'get_status_infos': True})\n self.assertEqual(ret['status'][ret['status'].keys()[0]]['status_infos'].keys(), ['key_status'])\n self.assertEqual(ret['status'][ret['status'].keys()[0]]['status_infos']['key_status']['value'], 'value_status')\n self.assertEqual(ret['status'][ret['status'].keys()[0]]['status_infos']['key_status']['key'], 'key_status')\n self.assertEqual(ret['status'][ret['status'].keys()[0]]['status_infos']['key_status']['status_id'], ret['status'].keys()[0])\n\n def test_get_status_limit(self):\n \"\"\" ['get_status'] Get object/checks/grousp by group_id with a limit \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n checks_second = self.imp.call('spv.services', 'create_checks', [{'plugin': '1', 'plugin_check': '2', 'name': '3', 'repeat': 100, 'repeat_on_error': 100, 'group_id': groups.keys()[0]}])\n self.checks.append(checks_second.keys())\n ret = self.imp.call('spv.services', 'get_status', {'group_id': groups.keys()[0], 'limit': 1})\n self.assertEqual(len(ret['checks']), 1)\n ret = self.imp.call('spv.services', 'get_status', {'group_id': groups.keys()[0]})\n self.assertEqual(len(ret['checks']), 2)\n\n def test_get_status_detailed_infos(self):\n \"\"\" ['get_status'] Test get_status with 'get_check_infos' to True\"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'group_id': groups.keys()[0], 'get_check_infos': True})\n self.assertEqual(ret['checks'][ret['checks'].keys()[0]]['check_infos'].keys(), ['key_toto'])\n", "method_code": " def _get_status_tests_create_data(self):\n \"\"\" Test create object,group,check for get_status tests \"\"\"\n groups = self.imp.call('spv.services', 'create_groups', ['test_groups'])\n self.groups.append(groups.keys())\n objects = self.imp.call('spv.services', 'create_objects', [{'address': 'test_address', 'infos': {'key_toto': 'value_toto'}, 'group_id': groups.keys()[0]}])\n self.objects.append(objects.keys())\n checks = self.imp.call('spv.services', 'create_checks', [{'plugin': 'hey', 'plugin_check': 'salut', 'name': 'toi', 'repeat': 100, 'repeat_on_error': 100, 'infos': {'key_toto': 'value_toto'}, 'group_id': groups.keys()[0]}])\n self.checks.append(checks.keys())\n return [groups, objects, checks]\n ", "context": "class ServiceTest(unittest.TestCase):\n def _get_status_tests_create_data(self): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _get_status_test_value(self, data, groups, objects, checks): ...\n def test_get_status_check_status(self): ...\n def test_get_status_group_name(self): ...\n def test_get_status_object_address(self): ...\n def test_get_status_plugin_name(self): ...\n def test_get_status_plugin_check(self): ...\n def test_get_status_group_id(self): ...\n def test_get_status_check_id(self): ...\n def test_get_status_status_id(self): ...\n def test_get_status_limit(self): ...\n def _check_get_status_info(self, data, type, info, id_name): ...\n def test_get_status_object_info(self): ...\n def test_get_status_check_info(self): ...\n def test_get_status_detailed_infos(self): ...\n def test_create_status(self): ...\n def test_update_check(self): ...\n", "repository": "SmartJog/webengine-spv", "test_name": "test_get_status_check_status", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001170.py"} {"focal_file": "tests/test_service_get_status.py", "focal_class": null, "focal_method": "_get_status_test_value", "tests": "import unittest\n\nclass Test_get_status_test_value(unittest.TestCase):\n def test_get_status_group_name(self):\n \"\"\" ['get_status'] Get every status with on specific group_name \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'group_name': [groups.values()[0]['name']]})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_object_address(self):\n \"\"\" ['get_status'] Get every status with on specific object address \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'object_address': objects.values()[0]['address']})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_plugin_name(self):\n \"\"\" ['get_status'] Get every status with on specific plugin name \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'plugin_name': checks.values()[0]['plugin']})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_plugin_check(self):\n \"\"\" ['get_status'] Get every status with on specific plugin check \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'plugin_check': checks.values()[0]['plugin_check']})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_group_id(self):\n \"\"\" ['get_status'] Get every status with on specific groups_id \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'group_id': groups.keys()[0]})\n self._get_status_test_value(ret, groups, objects, checks)\n\n def test_get_status_check_id(self):\n \"\"\" ['get_status'] Get every status with on specific check_id \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n checks_second = self.imp.call('spv.services', 'create_checks', [{'plugin': '1', 'plugin_check': '2', 'name': '3', 'repeat': 100, 'repeat_on_error': 100, 'group_id': groups.keys()[0]}])\n self.checks.append(checks_second.keys())\n ret = self.imp.call('spv.services', 'get_status', {'check_id': checks.keys()[0]})\n self._get_status_test_value(ret, groups, objects, checks)\n", "method_code": " def _get_status_test_value(self, data, groups, objects, checks):\n keys = data.keys()\n keys.sort()\n self.assertTrue(keys == ['checks', 'groups', 'objects', 'status'])\n self.assertTrue(data['checks'][checks.keys()[0]]['name'] == 'toi')\n self.assertTrue(data['groups'][groups.keys()[0]]['name'] == 'test_groups')\n self.assertTrue(data['objects'][objects.keys()[0]]['address'] == 'test_address')\n self.assertTrue(data['status'][data['status'].keys()[0]]['grp_id'] == groups.keys()[0])\n self.assertTrue(data['status'][data['status'].keys()[0]]['chk_id'] == checks.keys()[0])\n self.assertTrue(data['status'][data['status'].keys()[0]]['obj_id'] == objects.keys()[0])\n ", "context": "class ServiceTest(unittest.TestCase):\n def _get_status_test_value(self, data, groups, objects, checks): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _get_status_tests_create_data(self): ...\n def test_get_status_check_status(self): ...\n def test_get_status_group_name(self): ...\n def test_get_status_object_address(self): ...\n def test_get_status_plugin_name(self): ...\n def test_get_status_plugin_check(self): ...\n def test_get_status_group_id(self): ...\n def test_get_status_check_id(self): ...\n def test_get_status_status_id(self): ...\n def test_get_status_limit(self): ...\n def _check_get_status_info(self, data, type, info, id_name): ...\n def test_get_status_object_info(self): ...\n def test_get_status_check_info(self): ...\n def test_get_status_detailed_infos(self): ...\n def test_create_status(self): ...\n def test_update_check(self): ...\n", "repository": "SmartJog/webengine-spv", "test_name": "test_get_status_group_name", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001171.py"} {"focal_file": "tests/test_service_get_status.py", "focal_class": null, "focal_method": "_check_get_status_info", "tests": "import unittest\n\nclass Test_check_get_status_info(unittest.TestCase):\n def test_get_status_object_info(self):\n \"\"\" ['get_status'] Get object with additional info \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'group_id': groups.keys()[0], 'get_object_infos': True})\n self._check_get_status_info(ret, 'objects', 'object_infos', 'obj_id')\n\n def test_get_status_check_info(self):\n \"\"\" ['get_status'] Get check with additional info \"\"\"\n groups, objects, checks = self._get_status_tests_create_data()\n ret = self.imp.call('spv.services', 'get_status', {'group_id': groups.keys()[0], 'get_check_infos': True})\n self._check_get_status_info(ret, 'checks', 'check_infos', 'chk_id')\n", "method_code": " def _check_get_status_info(self, data, type, info, id_name):\n \"\"\" Generic funtionc to test get_status with additional info\"\"\"\n id = data[type].keys()[0]\n self.assertTrue(info in data[type][id].keys())\n infos = data[type][id][info]\n self.assertTrue('key_toto' in infos.keys())\n self.assertEqual(infos['key_toto'][id_name], id)\n self.assertEqual(infos['key_toto']['key'], 'key_toto')\n self.assertEqual(infos['key_toto']['value'], 'value_toto')\n ", "context": "class ServiceTest(unittest.TestCase):\n def _check_get_status_info(self, data, type, info, id_name): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _get_status_tests_create_data(self): ...\n def _get_status_test_value(self, data, groups, objects, checks): ...\n def test_get_status_check_status(self): ...\n def test_get_status_group_name(self): ...\n def test_get_status_object_address(self): ...\n def test_get_status_plugin_name(self): ...\n def test_get_status_plugin_check(self): ...\n def test_get_status_group_id(self): ...\n def test_get_status_check_id(self): ...\n def test_get_status_status_id(self): ...\n def test_get_status_limit(self): ...\n def test_get_status_object_info(self): ...\n def test_get_status_check_info(self): ...\n def test_get_status_detailed_infos(self): ...\n def test_create_status(self): ...\n def test_update_check(self): ...\n", "repository": "SmartJog/webengine-spv", "test_name": "test_get_status_object_info", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001172.py"} {"focal_file": "core/common_architecture.py", "focal_class": null, "focal_method": "get_bilstm_left_right", "tests": "import unittest\n\nclass Test_get_bilstm_left_right(unittest.TestCase):\n def test_get_bilstm_left_right(self):\n s1 = self.lstm1.initial_state()\n s2 = self.lstm2.initial_state()\n outputs1 = s1.transduce(self.inputs)\n outputs2 = s2.transduce(self.inputs_reverse)[::-1]\n lr = dy.concatenate([outputs1[0], outputs2[3]])\n subject = self.common.get_bilstm_left_right(self.inputs, self.lstm1, self.lstm2, 1, 2)\n for i in xrange(len(lr.value())):\n self.assertAlmostEqual(lr[i].value(), subject[i].value(), places=5)\n", "method_code": " def get_bilstm_left_right(self, inputs, lstm1, lstm2, start, end, update_flag=True):\n outputs1, outputs2 = self.run_bilstm(inputs, lstm1, lstm2, update_flag)\n return self.get_bilstm_left_right_from_outputs(outputs1, outputs2, start, end)\n ", "context": "class CommonArchitecture(object):\n def get_bilstm_left_right(self, inputs, lstm1, lstm2, start, end, update_flag=True): ...\n def __init__(self, model): ...\n def init_common_parameters(self, wembs={}): ...\n def get_wemb(self, w, update_flag=True): ...\n def get_cemb(self, c, update_flag=True): ...\n def get_jamo_rep(self, char, update_flag=True): ...\n def get_crep(self, chars, update_flag=True): ...\n def estimate_joint_priors(self, qp_pairs, smooth=False): ...\n def get_loss(self, qp_pairs): ...\n def evaluator_report(self, wseqs, tseqs, zseqs_X, zseqs_Y, zseqs_XY, infer_time, mi_value, metric, newline=False): ...\n def run_lstm(self, inputs, lstm, update_flag=True): ...\n def run_bilstm(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_bilstm_all(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_hier_bilstm_avg(self, input_seqs, flstm1, blstm1, flstm2, blstm2, update_flag=True): ...\n def get_bilstm_single(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_bilstm_left_right_from_outputs(self, outputs1, outputs2, start, end): ...\n def activate(self, h): ...\n def turn_on_training(self, drate): ...\n def turn_off_training(self): ...\n\n self.info = InformationTheory()\n self.model = model\n", "repository": "karlstratos/iaan", "test_name": "test_get_bilstm_left_right", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001173.py"} {"focal_file": "core/common_architecture.py", "focal_class": null, "focal_method": "get_bilstm_all", "tests": "import unittest\n\nclass Test_get_bilstm_all(unittest.TestCase):\n def test_get_bilstm_all(self):\n s1 = self.lstm1.initial_state()\n s2 = self.lstm2.initial_state()\n outputs1 = s1.transduce(self.inputs)\n outputs2 = s2.transduce(self.inputs_reverse)\n outputs2 = outputs2[::-1]\n subject = self.common.get_bilstm_all(self.inputs, self.lstm1, self.lstm2)\n for i in xrange(len(subject)):\n self.assertAlmostEqual(subject[i].value(), dy.concatenate([outputs1[i], outputs2[i]]).value(), places=5)\n\n def test_get_bilstm_all_update(self):\n pc = dy.ParameterCollection()\n trainer = dy.AdamTrainer(pc, 0.1)\n flstm = dy.LSTMBuilder(1, 1, 1, pc)\n blstm = dy.LSTMBuilder(1, 1, 1, pc)\n model = Model()\n common = CommonArchitecture(model)\n\n def make_inputs():\n return [dy.inputTensor([1.0]), dy.inputTensor([2.0]), dy.inputTensor([3.0]), dy.inputTensor([4.0])]\n\n def test(sqnorm_original_value, assert_equal):\n dy.renew_cg()\n inputs = make_inputs()\n avg = dy.average(common.get_bilstm_all(inputs, flstm, blstm))\n sqnorm = dy.squared_norm(avg)\n if assert_equal:\n self.assertAlmostEqual(sqnorm_original_value, sqnorm.value(), places=10)\n else:\n self.assertNotAlmostEqual(sqnorm_original_value, sqnorm.value(), places=10)\n inputs = make_inputs()\n avg = dy.average(common.get_bilstm_all(inputs, flstm, blstm, False))\n sqnorm = dy.squared_norm(avg)\n sqnorm_original_value = sqnorm.value()\n sqnorm.backward()\n trainer.update()\n test(sqnorm_original_value, True)\n dy.renew_cg()\n inputs = make_inputs()\n avg = dy.average(common.get_bilstm_all(inputs, flstm, blstm))\n sqnorm = dy.squared_norm(avg)\n sqnorm.backward()\n trainer.update()\n test(sqnorm_original_value, False)\n", "method_code": " def get_bilstm_all(self, inputs, lstm1, lstm2, update_flag=True):\n outputs1, outputs2 = self.run_bilstm(inputs, lstm1, lstm2, update_flag)\n return [dy.concatenate([outputs1[i], outputs2[i]]) for i in xrange(len(outputs1))]\n ", "context": "class CommonArchitecture(object):\n def get_bilstm_all(self, inputs, lstm1, lstm2, update_flag=True): ...\n def __init__(self, model): ...\n def init_common_parameters(self, wembs={}): ...\n def get_wemb(self, w, update_flag=True): ...\n def get_cemb(self, c, update_flag=True): ...\n def get_jamo_rep(self, char, update_flag=True): ...\n def get_crep(self, chars, update_flag=True): ...\n def estimate_joint_priors(self, qp_pairs, smooth=False): ...\n def get_loss(self, qp_pairs): ...\n def evaluator_report(self, wseqs, tseqs, zseqs_X, zseqs_Y, zseqs_XY, infer_time, mi_value, metric, newline=False): ...\n def run_lstm(self, inputs, lstm, update_flag=True): ...\n def run_bilstm(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_hier_bilstm_avg(self, input_seqs, flstm1, blstm1, flstm2, blstm2, update_flag=True): ...\n def get_bilstm_single(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_bilstm_left_right(self, inputs, lstm1, lstm2, start, end, update_flag=True): ...\n def get_bilstm_left_right_from_outputs(self, outputs1, outputs2, start, end): ...\n def activate(self, h): ...\n def turn_on_training(self, drate): ...\n def turn_off_training(self): ...\n\n self.info = InformationTheory()\n self.model = model\n", "repository": "karlstratos/iaan", "test_name": "test_get_bilstm_all", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001174.py"} {"focal_file": "core/common_architecture.py", "focal_class": null, "focal_method": "get_bilstm_single", "tests": "import unittest\n\nclass Test_get_bilstm_single(unittest.TestCase):\n def test_get_bilstm_single(self):\n s1 = self.lstm1.initial_state()\n s2 = self.lstm2.initial_state()\n outputs1 = s1.transduce(self.inputs)\n outputs2 = s2.transduce(self.inputs_reverse)\n single = dy.concatenate([outputs1[-1], outputs2[-1]])\n subject = self.common.get_bilstm_single(self.inputs, self.lstm1, self.lstm2)\n for i in xrange(len(single.value())):\n self.assertAlmostEqual(single[i].value(), subject[i].value(), places=5)\n", "method_code": " def get_bilstm_single(self, inputs, lstm1, lstm2, update_flag=True):\n outputs1, outputs2 = self.run_bilstm(inputs, lstm1, lstm2, update_flag)\n return dy.concatenate([outputs1[-1], outputs2[0]])\n ", "context": "class CommonArchitecture(object):\n def get_bilstm_single(self, inputs, lstm1, lstm2, update_flag=True): ...\n def __init__(self, model): ...\n def init_common_parameters(self, wembs={}): ...\n def get_wemb(self, w, update_flag=True): ...\n def get_cemb(self, c, update_flag=True): ...\n def get_jamo_rep(self, char, update_flag=True): ...\n def get_crep(self, chars, update_flag=True): ...\n def estimate_joint_priors(self, qp_pairs, smooth=False): ...\n def get_loss(self, qp_pairs): ...\n def evaluator_report(self, wseqs, tseqs, zseqs_X, zseqs_Y, zseqs_XY, infer_time, mi_value, metric, newline=False): ...\n def run_lstm(self, inputs, lstm, update_flag=True): ...\n def run_bilstm(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_bilstm_all(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_hier_bilstm_avg(self, input_seqs, flstm1, blstm1, flstm2, blstm2, update_flag=True): ...\n def get_bilstm_left_right(self, inputs, lstm1, lstm2, start, end, update_flag=True): ...\n def get_bilstm_left_right_from_outputs(self, outputs1, outputs2, start, end): ...\n def activate(self, h): ...\n def turn_on_training(self, drate): ...\n def turn_off_training(self): ...\n\n self.info = InformationTheory()\n self.model = model\n", "repository": "karlstratos/iaan", "test_name": "test_get_bilstm_single", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001175.py"} {"focal_file": "core/common_architecture.py", "focal_class": null, "focal_method": "run_bilstm", "tests": "import unittest\n\nclass Test_run_bilstm(unittest.TestCase):\n def test_run_bilstm(self):\n s1 = self.lstm1.initial_state()\n s2 = self.lstm2.initial_state()\n outputs1 = s1.transduce(self.inputs)\n outputs2 = s2.transduce(self.inputs_reverse)[::-1]\n subject1, subject2 = self.common.run_bilstm(self.inputs, self.lstm1, self.lstm2)\n for i in xrange(len(outputs1)):\n self.assertAlmostEqual(subject1[i].value(), outputs1[i].value(), places=5)\n self.assertAlmostEqual(subject2[i].value(), outputs2[i].value(), places=5)\n", "method_code": " def run_bilstm(self, inputs, lstm1, lstm2, update_flag=True):\n outputs1 = self.run_lstm(inputs, lstm1, update_flag)\n outputs2 = self.run_lstm(inputs[::-1], lstm2, update_flag)\n return (outputs1, outputs2[::-1])\n ", "context": "class CommonArchitecture(object):\n def run_bilstm(self, inputs, lstm1, lstm2, update_flag=True): ...\n def __init__(self, model): ...\n def init_common_parameters(self, wembs={}): ...\n def get_wemb(self, w, update_flag=True): ...\n def get_cemb(self, c, update_flag=True): ...\n def get_jamo_rep(self, char, update_flag=True): ...\n def get_crep(self, chars, update_flag=True): ...\n def estimate_joint_priors(self, qp_pairs, smooth=False): ...\n def get_loss(self, qp_pairs): ...\n def evaluator_report(self, wseqs, tseqs, zseqs_X, zseqs_Y, zseqs_XY, infer_time, mi_value, metric, newline=False): ...\n def run_lstm(self, inputs, lstm, update_flag=True): ...\n def get_bilstm_all(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_hier_bilstm_avg(self, input_seqs, flstm1, blstm1, flstm2, blstm2, update_flag=True): ...\n def get_bilstm_single(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_bilstm_left_right(self, inputs, lstm1, lstm2, start, end, update_flag=True): ...\n def get_bilstm_left_right_from_outputs(self, outputs1, outputs2, start, end): ...\n def activate(self, h): ...\n def turn_on_training(self, drate): ...\n def turn_off_training(self): ...\n\n self.info = InformationTheory()\n self.model = model\n", "repository": "karlstratos/iaan", "test_name": "test_run_bilstm", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001176.py"} {"focal_file": "core/common_architecture.py", "focal_class": null, "focal_method": "run_lstm", "tests": "import unittest\n\nclass Test_run_lstm(unittest.TestCase):\n def test_run_lstm(self):\n s1 = self.lstm1.initial_state()\n outputs1 = s1.transduce(self.inputs)\n subject1 = self.common.run_lstm(self.inputs, self.lstm1)\n for i in xrange(len(outputs1)):\n self.assertAlmostEqual(subject1[i].value(), outputs1[i].value(), places=5)\n", "method_code": " def run_lstm(self, inputs, lstm, update_flag=True):\n s = lstm.initial_state(update=update_flag)\n return s.transduce(inputs)\n ", "context": "class CommonArchitecture(object):\n def run_lstm(self, inputs, lstm, update_flag=True): ...\n def __init__(self, model): ...\n def init_common_parameters(self, wembs={}): ...\n def get_wemb(self, w, update_flag=True): ...\n def get_cemb(self, c, update_flag=True): ...\n def get_jamo_rep(self, char, update_flag=True): ...\n def get_crep(self, chars, update_flag=True): ...\n def estimate_joint_priors(self, qp_pairs, smooth=False): ...\n def get_loss(self, qp_pairs): ...\n def evaluator_report(self, wseqs, tseqs, zseqs_X, zseqs_Y, zseqs_XY, infer_time, mi_value, metric, newline=False): ...\n def run_bilstm(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_bilstm_all(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_hier_bilstm_avg(self, input_seqs, flstm1, blstm1, flstm2, blstm2, update_flag=True): ...\n def get_bilstm_single(self, inputs, lstm1, lstm2, update_flag=True): ...\n def get_bilstm_left_right(self, inputs, lstm1, lstm2, start, end, update_flag=True): ...\n def get_bilstm_left_right_from_outputs(self, outputs1, outputs2, start, end): ...\n def activate(self, h): ...\n def turn_on_training(self, drate): ...\n def turn_off_training(self): ...\n\n self.info = InformationTheory()\n self.model = model\n", "repository": "karlstratos/iaan", "test_name": "test_run_lstm", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001177.py"} {"focal_file": "core/model.py", "focal_class": null, "focal_method": "build_dicts", "tests": "import unittest\n\nclass Test_build_dicts(unittest.TestCase):\n def test_build_dicts_en(self):\n model = Model()\n wseqs, tseqs = model.read_wseqs(self.data_en_path, self.gold_en_path)\n model.build_dicts(wseqs, tseqs)\n self.assertEqual(model.wsize(), 7)\n self.assertEqual(model.csize(), 12)\n self.assertEqual(model.tsize(), 3)\n self.assertEqual(model.num_seqs, 3)\n self.assertEqual(model.num_words, 15)\n self.assert_counts_en(model)\n\n def test_build_dicts_ko(self):\n model = Model()\n wseqs, tseqs = model.read_wseqs(self.data_ko_path, self.gold_ko_path)\n model.jdim = 1\n model.build_dicts(wseqs, tseqs)\n self.assertEqual(model.wsize(), 8)\n self.assertEqual(model.csize(), 12)\n self.assertEqual(model.tsize(), 3)\n self.assertEqual(model.jamo_size(), 20)\n self.assertEqual(model.num_seqs, 3)\n self.assertEqual(model.num_words, 15)\n self.assert_counts_ko(model, model.jdim > 0)\n model.jdim = 0\n model.build_dicts(wseqs, tseqs)\n self.assert_counts_ko(model, model.jdim > 0)\n\n def test_build_dicts_ja(self):\n model = Model()\n wseqs, tseqs = model.read_wseqs(self.data_ja_path, '')\n model.build_dicts(wseqs, [])\n self.assertEqual(model.wsize(), 8)\n self.assertEqual(model.csize(), 13)\n self.assertEqual(model.tsize(), 0)\n self.assertEqual(model.num_seqs, 3)\n self.assertEqual(model.num_words, 15)\n self.assert_counts_ja(model)\n", "method_code": " def build_dicts(self, wseqs, tseqs, pretrained_wembs={}):\n self._w2i = {}\n self._i2w = {}\n self._c2i = {}\n self._i2c = {}\n self._t2i = {}\n self._i2t = {}\n self._jamo2i = {}\n self._i2jamo = {}\n self.w_count = Counter()\n self.c_count = Counter()\n self.t_count = Counter()\n self.jamo_count = Counter()\n self.num_seqs = len(wseqs)\n self.num_words = 0\n for wseq in wseqs:\n self.num_words += len(wseq)\n for w in wseq:\n self.w_count[w] += 1\n if not w in self._w2i:\n i = len(self._w2i)\n self._w2i[w] = i\n self._i2w[i] = w\n for c in w:\n self.c_count[c] += 1\n if not c in self._c2i:\n i = len(self._c2i)\n self._c2i[c] = i\n self._i2c[i] = c\n if self.jdim > 0:\n for jamo in h2j(c):\n self.jamo_count[jamo] += 1\n if not jamo in self._jamo2i:\n i = len(self._jamo2i)\n self._jamo2i[jamo] = i\n self._i2jamo[i] = jamo\n for tseq in tseqs:\n for t in tseq:\n self.t_count[t] += 1\n if not t in self._t2i:\n i = len(self._t2i)\n self._t2i[t] = i\n self._i2t[i] = t\n self.num_pretrained_wembs = len(pretrained_wembs)\n for w in pretrained_wembs:\n if isinstance(w, str):\n w = unicode(w, 'utf-8')\n if not w in self._w2i:\n i = len(self._w2i)\n self._w2i[w] = i\n self._i2w[i] = w\n self.w_count[w] = 1\n for c in w:\n if not c in self._c2i:\n i = len(self._c2i)\n self._c2i[c] = i\n self._i2c[i] = c\n self.c_count[c] = 1\n if self.jdim > 0:\n for jamo in h2j(c):\n if not jamo in self._jamo2i:\n i = len(self._jamo2i)\n self._jamo2i[jamo] = i\n self._i2jamo[i] = jamo\n self.jamo_count[jamo] = 1\n if self._UNK in self._w2i:\n del self._w2i[self._UNK]\n assert not self._BUF in self._w2i\n w_BUF_i = len(self._w2i)\n self._w2i[self._BUF] = w_BUF_i\n self._i2w[w_BUF_i] = self._BUF\n assert not (self._UNK in self._w2i or self._UNK in self._c2i)\n w_UNK_i = len(self._w2i)\n c_UNK_i = len(self._c2i)\n self._w2i[self._UNK] = w_UNK_i\n self._c2i[self._UNK] = c_UNK_i\n self._i2w[w_UNK_i] = self._UNK\n self._i2c[c_UNK_i] = self._UNK\n if self.jdim > 0:\n assert not (self._UNK in self._jamo2i or self._EMP in self._jamo2i)\n jamo_UNK_i = len(self._jamo2i)\n self._jamo2i[self._UNK] = jamo_UNK_i\n self._i2jamo[jamo_UNK_i] = self._UNK\n jamo_EMP_i = len(self._jamo2i)\n self._jamo2i[self._EMP] = jamo_EMP_i\n self._i2jamo[jamo_EMP_i] = self._EMP\n ", "context": "class Model(object):\n def build_dicts(self, wseqs, tseqs, pretrained_wembs={}): ...\n def __init__(self, cmd=''): ...\n def compute_drop_flag(self, item, count): ...\n def drop(self, item, count): ...\n def get_w_ind(self, w): ...\n def get_c_ind(self, c): ...\n def get_jamo_ind(self, jamo): ...\n def wsize(self): ...\n def csize(self): ...\n def tsize(self): ...\n def jamo_size(self): ...\n def _prepare_model_directory(self, model_path): ...\n def _log(self, string, newline=True): ...\n def read_articles(self, articles_path): ...\n def read_wseqs(self, wseq_path, tag_path=''): ...\n def read_spanseqs(self, span_path, entity_path=''): ...\n def read_ner_data(self, data_path, read_entities=True): ...\n def read_wembs(self, wemb_path, wdim=None): ...\n\n self._UNK = unicode('', 'utf-8')\n self._BUF = unicode('<*>', 'utf-8')\n self._EMP = unicode('', 'utf-8')\n self.evaluator = Evaluator()\n self._is_training = False\n self._input_drop = False\n self._verbose = False\n self._cmd = cmd\n self._activation = 'tanh'\n self._log_path = ''\n self.zsize = 0\n self.wdim = 0\n self.cdim = 0\n self.jdim = 0\n self.pseudocount = 0\n", "repository": "karlstratos/iaan", "test_name": "test_build_dicts_en", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001178.py"} {"focal_file": "core/model.py", "focal_class": null, "focal_method": "read_wembs", "tests": "import unittest\n\nclass Test_read_wembs(unittest.TestCase):\n def test_pretrained_wembs_en(self):\n model = Model()\n wseqs, tseqs = model.read_wseqs(self.data_en_path, self.gold_en_path)\n wembs = model.read_wembs(self.wemb_en_path)\n model.build_dicts(wseqs, tseqs, wembs)\n self.assertEqual(model.wsize(), 8)\n self.assertEqual(model.csize(), 13)\n self.assert_counts_en(model)\n self.assertEqual(model.w_count['cow'], 1)\n self.assertEqual(model.c_count['w'], 1)\n", "method_code": " def read_wembs(self, wemb_path, wdim=None):\n if not wemb_path:\n return {}\n wemb = {}\n with open(wemb_path, 'r') as wemb_file:\n for line in wemb_file:\n toks = line.split()\n w, emb = (unicode(toks[0], 'utf-8'), [float(f) for f in toks[1:]])\n if wdim:\n assert len(emb) == wdim\n wemb[w] = emb\n return wemb\n ", "context": "class Model(object):\n def read_wembs(self, wemb_path, wdim=None): ...\n def __init__(self, cmd=''): ...\n def compute_drop_flag(self, item, count): ...\n def drop(self, item, count): ...\n def get_w_ind(self, w): ...\n def get_c_ind(self, c): ...\n def get_jamo_ind(self, jamo): ...\n def wsize(self): ...\n def csize(self): ...\n def tsize(self): ...\n def jamo_size(self): ...\n def _prepare_model_directory(self, model_path): ...\n def _log(self, string, newline=True): ...\n def read_articles(self, articles_path): ...\n def read_wseqs(self, wseq_path, tag_path=''): ...\n def read_spanseqs(self, span_path, entity_path=''): ...\n def read_ner_data(self, data_path, read_entities=True): ...\n def build_dicts(self, wseqs, tseqs, pretrained_wembs={}): ...\n\n self._UNK = unicode('', 'utf-8')\n self._BUF = unicode('<*>', 'utf-8')\n self._EMP = unicode('', 'utf-8')\n self.evaluator = Evaluator()\n self._is_training = False\n self._input_drop = False\n self._verbose = False\n self._cmd = cmd\n self._activation = 'tanh'\n self._log_path = ''\n self.zsize = 0\n self.wdim = 0\n self.cdim = 0\n self.jdim = 0\n self.pseudocount = 0\n", "repository": "karlstratos/iaan", "test_name": "test_pretrained_wembs_en", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001179.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "cross_entropy_structbag", "tests": "import unittest\n\nclass Test_cross_entropy_structbag(unittest.TestCase):\n def test_cross_entropy_structbag(self):\n P = dy.inputTensor([[0.5, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 0.5]])\n Q = dy.inputTensor([[0.5, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 0.5]])\n entropy_unif = self.info.cross_entropy_structbag(P, Q)\n self.assertAlmostEqual(entropy_unif.value(), 5.0, places=10)\n", "method_code": " def cross_entropy_structbag(self, P, Q):\n \"\"\"\n P (K x m) represents a distribution over STRUCTURED labels where each\n label is a BAG of K INDEPENDENT symbols taking values in {1 ... m}.\n That is, z = (z1 ... zK) is assigned probability P1(z1) * ... * PK(zK).\n (Similarly for Q.) By the independence, H(P, Q) = sum_k H(Pk, Qk).\n \"\"\"\n return -dy.sum_dim(dy.cmult(P, self.log2(Q)), [0, 1])\n ", "context": "class InformationTheory(object):\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy(self, p): ...\n def entropy_zero(self, p): ...\n def conditional_entropy(self, conditional, prior): ...\n def conditional_entropy_zero(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def conditional2(self, joint, prior1): ...\n def kl(self, p, q): ...\n def mi(self, joint): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero(self, joint): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_cross_entropy_structbag", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001180.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "entropy", "tests": "import unittest\n\nclass Test_entropy(unittest.TestCase):\n def test_entropy(self):\n entropy_hot = self.info.entropy(dy.inputTensor([0.9999999, 1e-07 / 3.0, 1e-07 / 3.0, 1e-07 / 3.0]))\n self.assertAlmostEqual(entropy_hot.value(), 0.0, places=5)\n entropy_unif = self.info.entropy(dy.inputTensor([0.25, 0.25, 0.25, 0.25]))\n self.assertAlmostEqual(entropy_unif.value(), 2.0, places=5)\n entropy_random = self.info.entropy(self.info.rand(16)).value()\n self.assertGreaterEqual(entropy_random, 0.0)\n self.assertLessEqual(entropy_random, 4.0)\n", "method_code": " def entropy(self, p):\n return self.cross_entropy(p, p)\n ", "context": "class InformationTheory(object):\n def entropy(self, p): ...\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy_zero(self, p): ...\n def conditional_entropy(self, conditional, prior): ...\n def conditional_entropy_zero(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def conditional2(self, joint, prior1): ...\n def kl(self, p, q): ...\n def mi(self, joint): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero(self, joint): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_entropy", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001181.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "entropy_zero", "tests": "import unittest\n\nclass Test_entropy_zero(unittest.TestCase):\n def test_entropy_zero(self):\n entropy_hot = self.info.entropy_zero(dy.inputTensor([0.5, 0.0, 0.5, 0.0]))\n self.assertAlmostEqual(entropy_hot.value(), 1.0, places=5)\n rand = self.info.rand(16)\n entropy_random = self.info.entropy_zero(rand).value()\n self.assertAlmostEqual(entropy_random, self.info.entropy(rand).value(), places=5)\n", "method_code": " def entropy_zero(self, p):\n return self.cross_entropy_zero(p, p)\n ", "context": "class InformationTheory(object):\n def entropy_zero(self, p): ...\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy(self, p): ...\n def conditional_entropy(self, conditional, prior): ...\n def conditional_entropy_zero(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def conditional2(self, joint, prior1): ...\n def kl(self, p, q): ...\n def mi(self, joint): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero(self, joint): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_entropy_zero", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001182.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "conditional_entropy", "tests": "import unittest\n\nclass Test_conditional_entropy(unittest.TestCase):\n def test_conditional_entropy(self):\n self.assertAlmostEqual(self.info.conditional_entropy([self.info.unif(16) for y in xrange(4)], self.info.rand(4)).value(), 4.0, places=5)\n", "method_code": " def conditional_entropy(self, conditional, prior):\n return dy.esum([prior[z] * self.entropy(conditional[z]) for z in xrange(prior.dim()[0][0])])\n ", "context": "class InformationTheory(object):\n def conditional_entropy(self, conditional, prior): ...\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy(self, p): ...\n def entropy_zero(self, p): ...\n def conditional_entropy_zero(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def conditional2(self, joint, prior1): ...\n def kl(self, p, q): ...\n def mi(self, joint): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero(self, joint): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_conditional_entropy", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001183.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "conditional_entropy_zero", "tests": "import unittest\n\nclass Test_conditional_entropy_zero(unittest.TestCase):\n def test_conditional_entropy_zero(self):\n conditional = [dy.inputTensor([0.5, 0.0, 0.5, 0.0]), dy.inputTensor([0.25, 0.25, 0.25, 0.25]), dy.inputTensor([0.0, 0.0, 0.0, 1.0]), dy.inputTensor([0.25, 0.25, 0.25, 0.25])]\n prior = dy.inputTensor([0.5, 0.0, 0.4, 0.1])\n self.assertAlmostEqual(self.info.conditional_entropy_zero(conditional, prior).value(), 0.7, places=5)\n", "method_code": " def conditional_entropy_zero(self, conditional, prior):\n return dy.esum([prior[z] * self.entropy_zero(conditional[z]) for z in xrange(prior.dim()[0][0])])\n ", "context": "class InformationTheory(object):\n def conditional_entropy_zero(self, conditional, prior): ...\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy(self, p): ...\n def entropy_zero(self, p): ...\n def conditional_entropy(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def conditional2(self, joint, prior1): ...\n def kl(self, p, q): ...\n def mi(self, joint): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero(self, joint): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_conditional_entropy_zero", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001184.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "kl", "tests": "import unittest\n\nclass Test_kl(unittest.TestCase):\n def test_kl(self):\n p = self.info.rand(16)\n q = self.info.rand(16)\n self.assertAlmostEqual(self.info.kl(p, p).value(), 0.0, places=5)\n self.assertGreaterEqual(self.info.kl(p, q).value(), 0.0)\n", "method_code": " def kl(self, p, q):\n return self.cross_entropy(p, q) - self.entropy(p)\n ", "context": "class InformationTheory(object):\n def kl(self, p, q): ...\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy(self, p): ...\n def entropy_zero(self, p): ...\n def conditional_entropy(self, conditional, prior): ...\n def conditional_entropy_zero(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def conditional2(self, joint, prior1): ...\n def mi(self, joint): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero(self, joint): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_kl", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001185.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "mi", "tests": "import unittest\n\nclass Test_mi(unittest.TestCase):\n def test_mi(self):\n joint = dy.inputTensor([[0.4999999, 1e-07], [1e-07, 0.4999999]])\n self.assertAlmostEqual(self.info.mi(joint).value(), 1.0, places=5)\n joint = dy.inputTensor([[0.25, 0.25], [0.25, 0.25]])\n self.assertAlmostEqual(self.info.mi(joint).value(), 0.0, places=5)\n self.assertAlmostEqual(self.info.mi(joint).value(), self.info.mi(dy.transpose(joint)).value())\n", "method_code": " def mi(self, joint):\n prior1 = dy.sum_dim(joint, [1])\n prior2 = dy.sum_dim(joint, [0])\n return self.mi_with_priors(joint, prior1, prior2)\n ", "context": "class InformationTheory(object):\n def mi(self, joint): ...\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy(self, p): ...\n def entropy_zero(self, p): ...\n def conditional_entropy(self, conditional, prior): ...\n def conditional_entropy_zero(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def conditional2(self, joint, prior1): ...\n def kl(self, p, q): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero(self, joint): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_mi", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001186.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "mi_zero", "tests": "import unittest\n\nclass Test_mi_zero(unittest.TestCase):\n def test_mi_zero(self):\n joint = dy.inputTensor([[0.5, 0.0], [0.0, 0.5]])\n self.assertAlmostEqual(self.info.mi_zero(joint).value(), 1.0, places=5)\n joint = dy.inputTensor([[0.0, 0.0], [1.0, 0.0]])\n self.assertAlmostEqual(self.info.mi_zero(joint).value(), 0.0, places=5)\n joint = self.info.rand_joint(10, 20)\n self.assertAlmostEqual(self.info.mi_zero(joint).value(), self.info.mi(joint).value(), places=5)\n", "method_code": " def mi_zero(self, joint):\n prior1 = dy.sum_dim(joint, [1])\n prior2 = dy.sum_dim(joint, [0])\n return self.mi_zero_with_priors(joint, prior1, prior2)\n ", "context": "class InformationTheory(object):\n def mi_zero(self, joint): ...\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy(self, p): ...\n def entropy_zero(self, p): ...\n def conditional_entropy(self, conditional, prior): ...\n def conditional_entropy_zero(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def conditional2(self, joint, prior1): ...\n def kl(self, p, q): ...\n def mi(self, joint): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_mi_zero", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001187.py"} {"focal_file": "core/information_theory.py", "focal_class": null, "focal_method": "conditional2", "tests": "import unittest\n\nclass Test_conditional2(unittest.TestCase):\n def test_conditional(self):\n joint = dy.inputTensor([[0.2, 0.1], [0.1, 0.2], [0.3, 0.1]])\n prior2 = dy.inputTensor([0.6, 0.4])\n conditional1 = self.info.conditional1(joint, prior2)\n self.assertAlmostEqual(conditional1[0][0].value(), 0.2 / 0.6, places=5)\n self.assertAlmostEqual(conditional1[0][1].value(), 0.1 / 0.6, places=5)\n self.assertAlmostEqual(conditional1[0][2].value(), 0.3 / 0.6, places=5)\n self.assertAlmostEqual(conditional1[1][0].value(), 0.1 / 0.4, places=5)\n self.assertAlmostEqual(conditional1[1][1].value(), 0.2 / 0.4, places=5)\n self.assertAlmostEqual(conditional1[1][2].value(), 0.1 / 0.4, places=5)\n prior1 = dy.inputTensor([0.3, 0.3, 0.4])\n conditional2 = self.info.conditional2(joint, prior1)\n self.assertAlmostEqual(conditional2[0][0].value(), 0.2 / 0.3, places=5)\n self.assertAlmostEqual(conditional2[0][1].value(), 0.1 / 0.3, places=5)\n self.assertAlmostEqual(conditional2[1][0].value(), 0.1 / 0.3, places=5)\n self.assertAlmostEqual(conditional2[1][1].value(), 0.2 / 0.3, places=5)\n self.assertAlmostEqual(conditional2[2][0].value(), 0.3 / 0.4, places=5)\n self.assertAlmostEqual(conditional2[2][1].value(), 0.1 / 0.4, places=5)\n", "method_code": " def conditional2(self, joint, prior1):\n size1, size2 = joint.dim()[0]\n conditional = []\n for z in xrange(size1):\n z_copied = dy.concatenate([prior1[z] for _ in xrange(size2)])\n conditional.append(dy.cdiv(dy.pick(joint, z), z_copied))\n return conditional\n ", "context": "class InformationTheory(object):\n def conditional2(self, joint, prior1): ...\n def cross_entropy_structbag(self, P, Q): ...\n def cross_entropy(self, p, q): ...\n def cross_entropy_zero(self, p, q): ...\n def entropy(self, p): ...\n def entropy_zero(self, p): ...\n def conditional_entropy(self, conditional, prior): ...\n def conditional_entropy_zero(self, conditional, prior): ...\n def conditional1(self, joint, prior2): ...\n def kl(self, p, q): ...\n def mi(self, joint): ...\n def mi_with_priors(self, joint, prior1, prior2): ...\n def mi_zero(self, joint): ...\n def mi_zero_with_priors(self, joint, prior1, prior2): ...\n def log2(self, value): ...\n def unif(self, size): ...\n def unif_joint(self, size1, size2): ...\n def rand(self, size): ...\n def rand_joint(self, size1, size2): ...\n", "repository": "karlstratos/iaan", "test_name": "test_conditional", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001188.py"} {"focal_file": "analyzer/darwin/lib/core/osx.py", "focal_class": null, "focal_method": "set_wallclock", "tests": "import unittest\n\nclass Test_set_wallclock(unittest.TestCase):\n def test_set_wallclock(self):\n clock_str = '20151203T15:23:43'\n result = set_wallclock(clock_str, just_testing=True)\n self.assertEqual(result, 'sudo date 1203152315.43')\n", "method_code": "def set_wallclock(clock_str, **kwargs):\n clock = datetime.strptime(clock_str, '%Y%m%dT%H:%M:%S')\n cmd = 'sudo date {0}'.format(clock.strftime('%m%d%H%M%y.%S'))\n if 'just_testing' in kwargs:\n return cmd\n else:\n system(cmd)", "context": "def set_wallclock(clock_str, **kwargs): ...\ndef set_wallclock(clock_str, **kwargs): ...\n", "repository": "0x71/cuckoo-exfildetect", "test_name": "test_set_wallclock", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001189.py"} {"focal_file": "analyzer/darwin/lib/core/packages.py", "focal_class": null, "focal_method": "choose_package_class", "tests": "import unittest\n\nclass Test_choose_package_class(unittest.TestCase):\n def test_macho_package(self):\n file_type = 'Mach-O 64-bit executable x86_64'\n file_name = 'codesign'\n pkg_class = choose_package_class(file_type, file_name)\n self.assertEqual(pkg_class.__name__, 'Macho')\n\n def test_macho_package_alt(self):\n file_type = 'Mach-O 32-bit executable i386'\n file_name = 'foobar'\n pkg_class = choose_package_class(file_type, file_name)\n self.assertEqual(pkg_class.__name__, 'Macho')\n", "method_code": "def choose_package_class(file_type, file_name, suggestion=None):\n if suggestion is not None:\n name = suggestion\n else:\n name = _guess_package_name(file_type, file_name)\n if not name:\n return None\n full_name = 'modules.packages.%s' % name\n try:\n sys.path.append(path.abspath(path.join(path.dirname(__file__), '..', '..')))\n module = __import__(full_name, globals(), locals(), ['*'])\n except ImportError:\n raise Exception('Unable to import package \"{0}\": it does not exist.'.format(name))\n try:\n pkg_class = _found_target_class(module, name)\n except IndexError as err:\n raise Exception('Unable to select package class (package={0}): {1}'.format(full_name, err))\n return pkg_class", "context": "def choose_package_class(file_type, file_name, suggestion=None): ...\ndef choose_package_class(file_type, file_name, suggestion=None): ...\ndef _found_target_class(module, name): ...\ndef _guess_package_name(file_type, file_name): ...\ndef _string_to_bool(raw): ...\n", "repository": "0x71/cuckoo-exfildetect", "test_name": "test_macho_package", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001190.py"} {"focal_file": "analyzer/darwin/lib/dtrace/autoprobes.py", "focal_class": null, "focal_method": "dereference_type", "tests": "import unittest\n\nclass Test_dereference_type(unittest.TestCase):\n def test_probes_dereference_value_type(self):\n type = 'scalar_t'\n output = dereference_type(type)\n self.assertEqual('scalar_t', output)\n\n def test_probes_dereference_reference_type(self):\n type = 'foo *'\n output = dereference_type(type)\n self.assertEqual('foo', output)\n", "method_code": "def dereference_type(t):\n \"\"\" Removes everything after the last star character in a type string,\n except for 'void *' and 'char *`. \"\"\"\n if t.strip() in ['void *', 'char *']:\n return t.strip()\n try:\n return t[:t.rindex('*')].strip()\n except:\n return t.strip()", "context": "def dereference_type(t): ...\ndef generate_probes(definitions, output_path, overwrite=True): ...\ndef read_definitions(fromfile): ...\ndef read_types(infile): ...\ndef dump_probes(probes, tofile): ...\ndef probe_from_definition(definition, types): ...\ndef entry_probe_from_definition(df): ...\ndef return_probe_from_definition(df, types): ...\ndef typedefs_for_custom_structs(defs, types): ...\ndef arguments_section(args, types): ...\ndef arguments_format_string(args, types): ...\ndef retval_section(retval_type, types): ...\ndef printf_format_for_type(t, types): ...\ndef printf_format_for_struct(t, types): ...\ndef serialize_argument_at_idx(idx, all_args, accessor, types): ...\ndef serialize_type(name, accessor, types): ...\ndef serialize_atomic_type(argtype, cast, accessor): ...\ndef serialize_struct_type(struct_type, accessor, types): ...\ndef serialize_type_with_template(oftype, accessor, types): ...\ndef dereference_type(t): ...\ndef type_description(name, types): ...\ndef push_on_stack_section(args): ...\ndef pop_from_stack_section(args): ...\n", "repository": "0x71/cuckoo-exfildetect", "test_name": "test_probes_dereference_value_type", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001191.py"} {"focal_file": "analyzer/darwin/lib/dtrace/autoprobes.py", "focal_class": null, "focal_method": "serialize_atomic_type", "tests": "import unittest\n\nclass Test_serialize_atomic_type(unittest.TestCase):\n def test_probes_atomic_type_serialization(self):\n type = 'float'\n accessor = 'self->arg0'\n output = serialize_atomic_type(type, type, accessor)\n self.assertEqual('(float)(self->arg0)', output)\n", "method_code": "def serialize_atomic_type(argtype, cast, accessor):\n \"\"\" Returns a serialization statement for the given atomic type.\n In case of pointers, values they're referencing will be used instead\n (see `dereference_type()` for exceptions). \"\"\"\n if dereference_type(argtype) == argtype:\n return '(%s)(%s)' % (cast, accessor)\n else:\n real_type = dereference_type(argtype)\n t = (accessor, cast, real_type, accessor, real_type)\n return '!!(%s) ? (%s)0 : *(%s *)copyin((uint64_t)%s, sizeof(%s))' % t", "context": "def serialize_atomic_type(argtype, cast, accessor): ...\ndef generate_probes(definitions, output_path, overwrite=True): ...\ndef read_definitions(fromfile): ...\ndef read_types(infile): ...\ndef dump_probes(probes, tofile): ...\ndef probe_from_definition(definition, types): ...\ndef entry_probe_from_definition(df): ...\ndef return_probe_from_definition(df, types): ...\ndef typedefs_for_custom_structs(defs, types): ...\ndef arguments_section(args, types): ...\ndef arguments_format_string(args, types): ...\ndef retval_section(retval_type, types): ...\ndef printf_format_for_type(t, types): ...\ndef printf_format_for_struct(t, types): ...\ndef serialize_argument_at_idx(idx, all_args, accessor, types): ...\ndef serialize_type(name, accessor, types): ...\ndef serialize_atomic_type(argtype, cast, accessor): ...\ndef serialize_struct_type(struct_type, accessor, types): ...\ndef serialize_type_with_template(oftype, accessor, types): ...\ndef dereference_type(t): ...\ndef type_description(name, types): ...\ndef push_on_stack_section(args): ...\ndef pop_from_stack_section(args): ...\n", "repository": "0x71/cuckoo-exfildetect", "test_name": "test_probes_atomic_type_serialization", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001192.py"} {"focal_file": "analyzer/darwin/lib/dtrace/autoprobes.py", "focal_class": null, "focal_method": "serialize_struct_type", "tests": "import unittest\n\nclass Test_serialize_struct_type(unittest.TestCase):\n def test_probes_struct_type_serialization(self):\n type = 'foo_t'\n accessor = 'self->arg0'\n types = {'float': {'printf_specifier': '%f', 'native': True}, 'char *': {'printf_specifier': '\"%S\"', 'native': True, 'template': '!!(${ARG}) ? copyinstr((uint64_t)${ARG}) : \"\"'}, 'foo_t': {'native': False, 'struct': {'value_f': 'float', 'value_str': 'char *'}}}\n output = serialize_struct_type(type, accessor, types)\n self.assertEqual('(float)(((foo_t)(self->arg0)).value_f), !!(((foo_t)(self->arg0)).value_str) ? copyinstr((uint64_t)((foo_t)(self->arg0)).value_str) : \"\"', output)\n", "method_code": "def serialize_struct_type(struct_type, accessor, types):\n \"\"\" Returns a serialization statement for the given structure type. \"\"\"\n fields = []\n if struct_type == dereference_type(struct_type):\n memeber_operator = '.'\n else:\n memeber_operator = '->'\n structure = type_description(struct_type, types)['struct']\n for field_name, field_type in structure.iteritems():\n fields.append(serialize_type(field_type, '((%s)(%s))' % (struct_type, accessor) + memeber_operator + field_name, types))\n return ', '.join(fields)", "context": "def serialize_struct_type(struct_type, accessor, types): ...\ndef generate_probes(definitions, output_path, overwrite=True): ...\ndef read_definitions(fromfile): ...\ndef read_types(infile): ...\ndef dump_probes(probes, tofile): ...\ndef probe_from_definition(definition, types): ...\ndef entry_probe_from_definition(df): ...\ndef return_probe_from_definition(df, types): ...\ndef typedefs_for_custom_structs(defs, types): ...\ndef arguments_section(args, types): ...\ndef arguments_format_string(args, types): ...\ndef retval_section(retval_type, types): ...\ndef printf_format_for_type(t, types): ...\ndef printf_format_for_struct(t, types): ...\ndef serialize_argument_at_idx(idx, all_args, accessor, types): ...\ndef serialize_type(name, accessor, types): ...\ndef serialize_atomic_type(argtype, cast, accessor): ...\ndef serialize_struct_type(struct_type, accessor, types): ...\ndef serialize_type_with_template(oftype, accessor, types): ...\ndef dereference_type(t): ...\ndef type_description(name, types): ...\ndef push_on_stack_section(args): ...\ndef pop_from_stack_section(args): ...\n", "repository": "0x71/cuckoo-exfildetect", "test_name": "test_probes_struct_type_serialization", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001193.py"} {"focal_file": "Blackjack/deck.py", "focal_class": null, "focal_method": "pop", "tests": "import unittest\n\nclass Test_pop(unittest.TestCase):\n def test_pop(self):\n my_deck = Deck()\n my_deck.pop()\n self.assertEqual(51, len(my_deck))\n", "method_code": " def pop(self):\n \"\"\"\n :return: Card\n \"\"\"\n top = self.cards[0]\n self.cards.remove(top)\n return top\n ", "context": "class Deck():\n def pop(self): ...\n def __init__(self, init_shuffle=False): ...\n def __len__(self): ...\n def shuffle(self): ...\n\n self.cards = []\n", "repository": "go-dima/PythonCourse", "test_name": "test_pop", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001194.py"} {"focal_file": "lib/Crypto/PublicKey/DSA.py", "focal_class": null, "focal_method": "generate", "tests": "import unittest\n\nclass Test_generate(unittest.TestCase):\n def test_generate_1arg(self):\n \"\"\"DSA (default implementation) generated key (1 argument)\"\"\"\n dsaObj = self.dsa.generate(1024)\n self._check_private_key(dsaObj)\n pub = dsaObj.publickey()\n self._check_public_key(pub)\n\n def test_generate_2arg(self):\n \"\"\"DSA (default implementation) generated key (2 arguments)\"\"\"\n dsaObj = self.dsa.generate(1024, Random.new().read)\n self._check_private_key(dsaObj)\n pub = dsaObj.publickey()\n self._check_public_key(pub)\n", "method_code": " def generate(self, bits, randfunc=None, progress_func=None):\n \"\"\"Randomly generate a fresh, new DSA key.\n \n :Parameters:\n bits : int\n Key length, or size (in bits) of the DSA modulus\n *p*.\n It must be a multiple of 64, in the closed\n interval [512,1024].\n randfunc : callable\n Random number generation function; it should accept\n a single integer N and return a string of random data\n N bytes long.\n If not specified, a new one will be instantiated\n from ``Crypto.Random``.\n progress_func : callable\n Optional function that will be called with a short string\n containing the key parameter currently being generated;\n it's useful for interactive applications where a user is\n waiting for a key to be generated.\n \n :attention: You should always use a cryptographically secure random number generator,\n such as the one defined in the ``Crypto.Random`` module; **don't** just use the\n current time and the ``random`` module.\n \n :Return: A DSA key object (`_DSAobj`).\n \n :Raise ValueError:\n When **bits** is too little, too big, or not a multiple of 64.\n \"\"\"\n for i in (0, 1, 2, 3, 4, 5, 6, 7, 8):\n if bits == 512 + 64 * i:\n return self._generate(bits, randfunc, progress_func)\n raise ValueError('Number of bits in p must be a multiple of 64 between 512 and 1024, not %d bits' % (bits,))\n ", "context": "class DSAImplementation(object):\n def generate(self, bits, randfunc=None, progress_func=None): ...\n def __init__(self, **kwargs): ...\n def _get_randfunc(self, randfunc): ...\n def _generate(self, bits, randfunc=None, progress_func=None): ...\n def construct(self, tup): ...\n\n self.error = self._math.error\n self._default_randfunc = kwargs.get('default_randfunc', None)\n self._current_randfunc = None\n", "repository": "the-code-chef/multi-user-blogs", "test_name": "test_generate_1arg", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001195.py"} {"focal_file": "lib/Crypto/PublicKey/DSA.py", "focal_class": null, "focal_method": "construct", "tests": "import unittest\n\nclass Test_construct(unittest.TestCase):\n def test_construct_4tuple(self):\n \"\"\"DSA (default implementation) constructed key (4-tuple)\"\"\"\n y, g, p, q = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]\n dsaObj = self.dsa.construct((y, g, p, q))\n self._test_verification(dsaObj)\n\n def test_construct_5tuple(self):\n \"\"\"DSA (default implementation) constructed key (5-tuple)\"\"\"\n y, g, p, q, x = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]\n dsaObj = self.dsa.construct((y, g, p, q, x))\n self._test_signing(dsaObj)\n self._test_verification(dsaObj)\n", "method_code": " def construct(self, tup):\n \"\"\"Construct a DSA key from a tuple of valid DSA components.\n \n The modulus *p* must be a prime.\n \n The following equations must apply:\n \n - p-1 = 0 mod q\n - g^x = y mod p\n - 0 < x < q\n - 1 < g < p\n \n :Parameters:\n tup : tuple\n A tuple of long integers, with 4 or 5 items\n in the following order:\n \n 1. Public key (*y*).\n 2. Sub-group generator (*g*).\n 3. Modulus, finite field order (*p*).\n 4. Sub-group order (*q*).\n 5. Private key (*x*). Optional.\n \n :Return: A DSA key object (`_DSAobj`).\n \"\"\"\n key = self._math.dsa_construct(*tup)\n return _DSAobj(self, key)\n ", "context": "class DSAImplementation(object):\n def construct(self, tup): ...\n def __init__(self, **kwargs): ...\n def _get_randfunc(self, randfunc): ...\n def generate(self, bits, randfunc=None, progress_func=None): ...\n def _generate(self, bits, randfunc=None, progress_func=None): ...\n\n self.error = self._math.error\n self._default_randfunc = kwargs.get('default_randfunc', None)\n self._current_randfunc = None\n", "repository": "the-code-chef/multi-user-blogs", "test_name": "test_construct_4tuple", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001196.py"} {"focal_file": "lib/Crypto/SelfTest/Signature/test_pkcs1_pss.py", "focal_class": null, "focal_method": "verify", "tests": "import unittest\n\nclass Test_verify(unittest.TestCase):\n def testSignVerify(self):\n h = SHA.new()\n h.update(b('blah blah blah'))\n rng = Random.new().read\n key = MyKey(RSA.generate(1024, rng))\n global mgfcalls\n\n def newMGF(seed, maskLen):\n global mgfcalls\n mgfcalls += 1\n return bchr(0) * maskLen\n for hashmod in (MD2, MD5, SHA, SHA224, SHA256, SHA384, RIPEMD):\n h = hashmod.new()\n h.update(b('blah blah blah'))\n key.asked = 0\n signer = PKCS.new(key)\n s = signer.sign(h)\n self.failUnless(signer.verify(h, s))\n self.assertEqual(key.asked, h.digest_size)\n h = SHA.new()\n h.update(b('blah blah blah'))\n for sLen in (0, 3, 21):\n key.asked = 0\n signer = PKCS.new(key, saltLen=sLen)\n s = signer.sign(h)\n self.assertEqual(key.asked, sLen)\n self.failUnless(signer.verify(h, s))\n mgfcalls = 0\n signer = PKCS.new(key, newMGF)\n s = signer.sign(h)\n self.assertEqual(mgfcalls, 1)\n self.failUnless(signer.verify(h, s))\n key.asked = 0\n mgfcalls = 0\n signer = PKCS.new(key, newMGF, 0)\n s = signer.sign(h)\n self.assertEqual(key.asked, 0)\n self.assertEqual(mgfcalls, 1)\n self.failUnless(signer.verify(h, s))\n", "method_code": " def verify(self, m, p):\n return self._key.verify(m, p)\n ", "context": "class MyKey():\n def verify(self, m, p): ...\n def __init__(self, key): ...\n def _randfunc(self, N): ...\n def sign(self, m): ...\n def has_private(self): ...\n def decrypt(self, m): ...\n def encrypt(self, m, p): ...\n\n self._key = key\n self.n = key.n\n self.asked = 0\n", "repository": "the-code-chef/multi-user-blogs", "test_name": "testSignVerify", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001197.py"} {"focal_file": "equadratures/scalers.py", "focal_class": null, "focal_method": "fit", "tests": "import unittest\n\nclass Test_fit(unittest.TestCase):\n def test_scalers(self):\n \"\"\"\n Tests the scaler classes.\n \"\"\"\n from equadratures.scalers import scaler_minmax, scaler_meanvar\n Xorig, _ = datasets.gen_linear(n_observations=500, n_dim=10, random_seed=42)\n Xorig *= 10\n scaler = scaler_minmax()\n scaler.fit(Xorig)\n X = scaler.transform(Xorig)\n np.testing.assert_array_almost_equal(X.max(), 1.0, decimal=5, err_msg='Problem!')\n np.testing.assert_array_almost_equal(X.min(), -1.0, decimal=5, err_msg='Problem!')\n X = scaler.untransform(X)\n np.testing.assert_array_almost_equal(X, Xorig, decimal=5, err_msg='Problem!')\n scaler = scaler_meanvar()\n scaler.fit(Xorig)\n X = scaler.transform(Xorig)\n np.testing.assert_array_almost_equal(X.mean(), 0.0, decimal=5, err_msg='Problem!')\n np.testing.assert_array_almost_equal(X.var(), 1.0, decimal=5, err_msg='Problem!')\n X = scaler.untransform(X)\n np.testing.assert_array_almost_equal(X, Xorig, decimal=5, err_msg='Problem!')\n", "method_code": " def fit(self, X):\n \"\"\" Fit scaler to data.\n \n Parameters\n ----------\n X : numpy.ndarray\n Array with shape (number_of_samples, number_of_dimensions) containing data to fit scaler to.\n \"\"\"\n if X.ndim == 1:\n X = X.reshape(-1, 1)\n self.Xmin = np.min(X, axis=0)\n self.Xmax = np.max(X, axis=0)\n self.fitted = True\n ", "context": "class scaler_minmax(object):\n def fit(self, X): ...\n def __init__(self): ...\n def transform(self, X): ...\n def untransform(self, X): ...\n\n self.fitted = False\n", "repository": "equadratures/equadratures", "test_name": "test_scalers", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001198.py"} {"focal_file": "betas/binary_score_plot.py", "focal_class": null, "focal_method": "get_threshold", "tests": "import unittest\n\nclass Test_get_threshold(unittest.TestCase):\n def test_threshold_assignment(self):\n \"\"\"\n Testing the threshold assignment in constructor\n \"\"\"\n threshold = 0.55\n bsp = BinaryScorePlot(SCORES, LABELS, threshold)\n assigned_threshold = bsp.get_threshold()\n self.assertTrue(threshold == assigned_threshold)\n", "method_code": " def get_threshold(self):\n \"\"\"\n Output:\n - threshold\n \"\"\"\n return self._threshold\n ", "context": "class BinaryScorePlot(object):\n def get_threshold(self): ...\n def __init__(self, scores=np.array([]), labels=np.array([]), threshold=0.5): ...\n def get_scores(self): ...\n def get_labels(self): ...\n def get_df(self): ...\n def set_scores(self, scores): ...\n def set_labels(self, labels): ...\n def plot_hist(self, bins=30): ...\n def plot_jitter(self): ...\n def plot_pr_by_threshold(self): ...\n def plot_roc(self): ...\n def optimal_threshold(self, by_mode='roc'): ...\n\n self._scores = scores\n self._labels = labels\n self._threshold = threshold\n self._df = df_curr\n", "repository": "betas-org/betas", "test_name": "test_threshold_assignment", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001199.py"} {"focal_file": "betas/binary_score_plot.py", "focal_class": null, "focal_method": "set_scores", "tests": "import unittest\n\nclass Test_set_scores(unittest.TestCase):\n def test_set_scores(self):\n \"\"\"\n Test scores assignment\n \"\"\"\n bsp = BinaryScorePlot(SCORES, LABELS)\n test_scores = np.zeros(20)\n bsp.set_scores(test_scores)\n self.assertEqual(bsp.get_scores().all(), test_scores.all())\n", "method_code": " def set_scores(self, scores):\n \"\"\"\n Set model scores to plot\n Input:\n - 1D numpy array of model scores\n \"\"\"\n self._scores = scores\n ", "context": "class BinaryScorePlot(object):\n def set_scores(self, scores): ...\n def __init__(self, scores=np.array([]), labels=np.array([]), threshold=0.5): ...\n def get_scores(self): ...\n def get_labels(self): ...\n def get_df(self): ...\n def get_threshold(self): ...\n def set_labels(self, labels): ...\n def plot_hist(self, bins=30): ...\n def plot_jitter(self): ...\n def plot_pr_by_threshold(self): ...\n def plot_roc(self): ...\n def optimal_threshold(self, by_mode='roc'): ...\n\n self._scores = scores\n self._labels = labels\n self._threshold = threshold\n self._df = df_curr\n", "repository": "betas-org/betas", "test_name": "test_set_scores", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001200.py"} {"focal_file": "betas/binary_score_plot.py", "focal_class": null, "focal_method": "set_labels", "tests": "import unittest\n\nclass Test_set_labels(unittest.TestCase):\n def test_set_labels(self):\n \"\"\"\n Test labels assignment\n \"\"\"\n bsp = BinaryScorePlot(SCORES, LABELS)\n test_labels = np.zeros(20)\n bsp.set_labels(test_labels)\n self.assertEqual(bsp.get_labels().all(), test_labels.all())\n", "method_code": " def set_labels(self, labels):\n \"\"\"\n Set model labels to plot\n Input:\n - 1D numpy array of model labels\n \"\"\"\n self._labels = labels\n ", "context": "class BinaryScorePlot(object):\n def set_labels(self, labels): ...\n def __init__(self, scores=np.array([]), labels=np.array([]), threshold=0.5): ...\n def get_scores(self): ...\n def get_labels(self): ...\n def get_df(self): ...\n def get_threshold(self): ...\n def set_scores(self, scores): ...\n def plot_hist(self, bins=30): ...\n def plot_jitter(self): ...\n def plot_pr_by_threshold(self): ...\n def plot_roc(self): ...\n def optimal_threshold(self, by_mode='roc'): ...\n\n self._scores = scores\n self._labels = labels\n self._threshold = threshold\n self._df = df_curr\n", "repository": "betas-org/betas", "test_name": "test_set_labels", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001201.py"} {"focal_file": "betas/binary_score_plot.py", "focal_class": null, "focal_method": "plot_hist", "tests": "import unittest\n\nclass Test_plot_hist(unittest.TestCase):\n def test_plots(self):\n \"\"\"\n Test four plots\n \"\"\"\n bsp = BinaryScorePlot(SCORES, LABELS)\n bsp.plot_hist()\n bsp.plot_jitter()\n bsp.plot_pr_by_threshold()\n bsp.plot_roc()\n self.assertEqual(1, 1)\n", "method_code": " def plot_hist(self, bins=30):\n \"\"\"\n Plot two histograms: one of\n the actual binary labels\n and one of the model scores\n Input:\n - number of histogram bins to use\n \"\"\"\n labels = self.get_labels()\n scores = self.get_scores()\n plt.clf()\n plt.subplot(221)\n sns.distplot(labels, kde=False)\n plt.xlabel('Actual Label', fontsize=12)\n plt.xticks([0, 1])\n plt.subplot(222)\n sns.distplot(scores, bins=bins, kde=False)\n plt.xlabel('Scores', fontsize=12)\n plt.xticks([0, 0.25, 0.5, 0.75, 1])\n plt.subplots_adjust(hspace=0.5)\n plt.subplot(223)\n sns.distplot(scores[labels == 0], bins=bins, kde=False)\n plt.xlabel('Actual Label = 0', fontsize=12)\n plt.subplot(224)\n sns.distplot(scores[labels == 1], bins=bins, kde=False)\n plt.xlabel('Actual Label = 1', fontsize=12)\n plt.suptitle('Histograms of Model Scores by Actual Label', fontsize=16)\n plt.show()\n ", "context": "class BinaryScorePlot(object):\n def plot_hist(self, bins=30): ...\n def __init__(self, scores=np.array([]), labels=np.array([]), threshold=0.5): ...\n def get_scores(self): ...\n def get_labels(self): ...\n def get_df(self): ...\n def get_threshold(self): ...\n def set_scores(self, scores): ...\n def set_labels(self, labels): ...\n def plot_jitter(self): ...\n def plot_pr_by_threshold(self): ...\n def plot_roc(self): ...\n def optimal_threshold(self, by_mode='roc'): ...\n\n self._scores = scores\n self._labels = labels\n self._threshold = threshold\n self._df = df_curr\n", "repository": "betas-org/betas", "test_name": "test_plots", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001202.py"} {"focal_file": "betas/binary_score_plot.py", "focal_class": null, "focal_method": "optimal_threshold", "tests": "import unittest\n\nclass Test_optimal_threshold(unittest.TestCase):\n def test_optimal_threshold_range_roc(self):\n \"\"\"\n Testing the optimal threshold range by roc (default)\n \"\"\"\n bsp = BinaryScorePlot(SCORES, LABELS)\n opt_thresh = bsp.optimal_threshold(by_mode='roc')\n self.assertTrue(opt_thresh >= 0)\n self.assertTrue(opt_thresh <= 1)\n\n def test_optimal_threshold_range(self):\n \"\"\"\n Testing the optimal threshold range not by roc\n \"\"\"\n bsp = BinaryScorePlot(SCORES, LABELS)\n opt_thresh = bsp.optimal_threshold(by_mode='other')\n self.assertTrue(opt_thresh >= 0)\n self.assertTrue(opt_thresh <= 1)\n", "method_code": " def optimal_threshold(self, by_mode='roc'):\n \"\"\"\n Calculate the optimal threshold by auc of either ROC or PR curve\n Input:\n - 1D numpy array of model scores\n - 1D numpy array of actual labels\n - Curve to use\n \"\"\"\n labels = self.get_labels()\n scores = self.get_scores()\n if by_mode == 'roc':\n fpr, tpr, thresholds = roc_curve(labels, scores)\n tnr = 1 - fpr\n t_f = tpr - tnr\n optimal_threshold = round(thresholds[abs(t_f).argsort()[0]], 2)\n else:\n precision, recall, thresholds = precision_recall_curve(labels, scores)\n thresholds = np.append(thresholds, 1)\n t_f = precision - recall\n optimal_threshold = round(thresholds[abs(t_f).argsort()[0]], 2)\n return optimal_threshold\n ", "context": "class BinaryScorePlot(object):\n def optimal_threshold(self, by_mode='roc'): ...\n def __init__(self, scores=np.array([]), labels=np.array([]), threshold=0.5): ...\n def get_scores(self): ...\n def get_labels(self): ...\n def get_df(self): ...\n def get_threshold(self): ...\n def set_scores(self, scores): ...\n def set_labels(self, labels): ...\n def plot_hist(self, bins=30): ...\n def plot_jitter(self): ...\n def plot_pr_by_threshold(self): ...\n def plot_roc(self): ...\n\n self._scores = scores\n self._labels = labels\n self._threshold = threshold\n self._df = df_curr\n", "repository": "betas-org/betas", "test_name": "test_optimal_threshold_range_roc", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001203.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "get_dataframe", "tests": "import unittest\n\nclass Test_get_dataframe(unittest.TestCase):\n def test_get_dataframe(self):\n \"\"\"\n Test if dataframe matched\n \"\"\"\n self.assertEqual(MYPLOT.get_dataframe().all().all(), DF.all().all(), 'Dataframe not matched')\n", "method_code": " def get_dataframe(self):\n \"\"\"\n Return the pandas dataframe\n Output:\n - A pandas dataframe\n \"\"\"\n return copy.deepcopy(self.dataframe)\n ", "context": "class RegressionAnalysisPlot(object):\n def get_dataframe(self): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_get_dataframe", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001204.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "get_predictors", "tests": "import unittest\n\nclass Test_get_predictors(unittest.TestCase):\n def test_get_predictors(self):\n \"\"\"\n Test if predictors matched and in dataframe columns\n \"\"\"\n self.assertEqual(MYPLOT.get_predictors(), PREDS, 'Predictors not matched')\n for pred_my in MYPLOT.get_predictors():\n self.assertIn(pred_my, DF.columns, 'Predictors not in dataframe columns')\n", "method_code": " def get_predictors(self):\n \"\"\"\n Return the list of predictor variable(s)\n Output:\n - A list of string indicating the predictor variable(s)\n \"\"\"\n return copy.deepcopy(self.predictors)\n ", "context": "class RegressionAnalysisPlot(object):\n def get_predictors(self): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_get_predictors", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001205.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "get_response", "tests": "import unittest\n\nclass Test_get_response(unittest.TestCase):\n def test_get_response(self):\n \"\"\"\n Test if response matched and in dataframe columns\n \"\"\"\n self.assertIn(MYPLOT.get_response(), RESP, 'Predictors not matched')\n self.assertIn(MYPLOT.get_response(), DF.columns, 'Predictors not in dataframe columns')\n", "method_code": " def get_response(self):\n \"\"\"\n Return the response variable\n Output:\n - A string indicating the response variable\n \"\"\"\n return copy.deepcopy(self.response)\n ", "context": "class RegressionAnalysisPlot(object):\n def get_response(self): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_get_response", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001206.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "set_predictors", "tests": "import unittest\n\nclass Test_set_predictors(unittest.TestCase):\n def test_set_predictors(self):\n \"\"\"\n Test predictors matched\n \"\"\"\n test_preds = [DF.columns[1]]\n MYPLOT.set_predictors(test_preds)\n self.assertEqual(MYPLOT.get_predictors(), test_preds, 'Predictors not matched')\n\n def test_set_predictors_err(self):\n \"\"\"\n Check set error if predictors not chosen from dataframe\n \"\"\"\n try:\n test_preds = PREDS + ['somename']\n MYPLOT.set_predictors(test_preds)\n except Exception as err:\n msg = 'Input predictor variable(s) not existed in the '\n msg += 'given dataframe'\n self.assertEqual(err.args[0], msg)\n", "method_code": " def set_predictors(self, predictors):\n \"\"\"\n Set predictor variable(s)\n Input:\n - predictors: A list of string indicating the predictor variable(s)\n \"\"\"\n dataframe = self.get_dataframe()\n for pred in predictors:\n if pred not in dataframe.columns:\n err = 'Input predictor variable(s) not existed '\n err += 'in the given dataframe'\n raise ValueError(err)\n self.predictors = predictors\n ", "context": "class RegressionAnalysisPlot(object):\n def set_predictors(self, predictors): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_set_predictors", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001207.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "set_response", "tests": "import unittest\n\nclass Test_set_response(unittest.TestCase):\n def test_set_response(self):\n \"\"\"\n Test response matched\n \"\"\"\n test_resp = DF.columns[2]\n MYPLOT.set_response(test_resp)\n self.assertEqual(MYPLOT.get_response(), test_resp, 'Response not matched')\n\n def test_set_response_err(self):\n \"\"\"\n Check set error if response not chosen from dataframe\n \"\"\"\n try:\n test_resp = 'somename'\n MYPLOT.set_response(test_resp)\n except Exception as err:\n msg = 'Input response variable not existed in the given '\n msg += 'dataframe'\n self.assertEqual(err.args[0], msg)\n", "method_code": " def set_response(self, response):\n \"\"\"\n Set response variable\n Input:\n - response: A string indicating the response variable\n \"\"\"\n dataframe = self.get_dataframe()\n if response not in dataframe.columns:\n err = 'Input response variable not existed '\n err += 'in the given dataframe'\n raise ValueError(err)\n self.response = response\n ", "context": "class RegressionAnalysisPlot(object):\n def set_response(self, response): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_set_response", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001208.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "matrix_plot", "tests": "import unittest\n\nclass Test_matrix_plot(unittest.TestCase):\n def test_matrix_plot_label(self):\n \"\"\"\n Test matrix_plot with assigned label\n \"\"\"\n MYPLOT.matrix_plot(label='species')\n self.assertEqual(1, 1)\n\n def test_matrix_plot_no_label(self):\n \"\"\"\n Test matrix_plot without assigned label\n \"\"\"\n MYPLOT.matrix_plot()\n self.assertEqual(1, 1)\n", "method_code": " def matrix_plot(self, label=None):\n \"\"\"\n Create a matrix scatter plot\n Input:\n - label: A categorical label for plot legend (default=None)\n \"\"\"\n dataframe = self.get_dataframe()\n cols = self.get_predictors()\n huelabel = None\n if label is not None:\n huelabel = label\n else:\n huelabel = self.get_response()\n if huelabel is not None:\n cols.append(huelabel)\n sns.pairplot(dataframe[cols], hue=huelabel, palette='Set1')\n else:\n sns.pairplot(dataframe[cols], palette='Set1')\n ", "context": "class RegressionAnalysisPlot(object):\n def matrix_plot(self, label=None): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_matrix_plot_label", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001209.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "corr_heatmap", "tests": "import unittest\n\nclass Test_corr_heatmap(unittest.TestCase):\n def test_corr_heatmap_figsize(self):\n \"\"\"\n Test corr_heatmap with assigned figsize\n \"\"\"\n MYPLOT.corr_heatmap(figsize=(10, 15))\n self.assertEqual(1, 1)\n\n def test_corr_heatmap_no_figsize(self):\n \"\"\"\n Test corr_heatmap without assigned figsize\n \"\"\"\n MYPLOT.corr_heatmap()\n self.assertEqual(1, 1)\n", "method_code": " def corr_heatmap(self, **kwargs):\n \"\"\"\n Create a heat map for observing the correlations among all predictors\n \"\"\"\n dataframe = self.get_dataframe()\n if 'figsize' in kwargs:\n figsize = kwargs['figsize']\n else:\n figsize = (10, 10)\n plt.figure(figsize=figsize)\n sns.heatmap(dataframe.corr(), annot=True, cmap='YlGnBu', linewidths=0.5)\n ", "context": "class RegressionAnalysisPlot(object):\n def corr_heatmap(self, **kwargs): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_corr_heatmap_figsize", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001210.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "reg_plot", "tests": "import unittest\n\nclass Test_reg_plot(unittest.TestCase):\n def test_reg_plot(self):\n \"\"\"\n Test reg_plot\n \"\"\"\n MYPLOT.reg_plot(DF.columns[0], DF.columns[1])\n self.assertEqual(1, 1)\n", "method_code": " def reg_plot(self, var_x, var_y):\n \"\"\"\n Create a scatter plot with regression line\n Input:\n - var_x: A variable on x-axis\n - var_y: A variable on y-axis\n \"\"\"\n dataframe = self.get_dataframe()\n sns.regplot(x=var_x, y=var_y, data=dataframe)\n ", "context": "class RegressionAnalysisPlot(object):\n def reg_plot(self, var_x, var_y): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_reg_plot", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001211.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "box_plot", "tests": "import unittest\n\nclass Test_box_plot(unittest.TestCase):\n def test_box_plot(self):\n \"\"\"\n Test box_plot\n \"\"\"\n MYPLOT.box_plot(DF.columns[0], DF.columns[1])\n self.assertEqual(1, 1)\n", "method_code": " def box_plot(self, var_x, var_y):\n \"\"\"\n Create a box plot\n Input:\n - var_x: A variable on x-axis\n - var_y: A variable on y-axis\n \"\"\"\n dataframe = self.get_dataframe()\n sns.boxplot(x=var_x, y=var_y, data=dataframe)\n ", "context": "class RegressionAnalysisPlot(object):\n def box_plot(self, var_x, var_y): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_box_plot", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001212.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "dist_plot", "tests": "import unittest\n\nclass Test_dist_plot(unittest.TestCase):\n def test_dist_plot(self):\n \"\"\"\n Test dist_plot\n \"\"\"\n MYPLOT.dist_plot(DF.columns[0], 'species')\n self.assertEqual(1, 1)\n", "method_code": " def dist_plot(self, var_x, var_y):\n \"\"\"\n Create a distribution plot with probability density function curves\n Input:\n - var_x: A variable on x-axis\n - var_y: A categorical variable shown in plot legend\n \"\"\"\n dataframe = self.get_dataframe()\n sns.FacetGrid(dataframe, hue=var_y, height=5).map(sns.distplot, var_x).add_legend()\n ", "context": "class RegressionAnalysisPlot(object):\n def dist_plot(self, var_x, var_y): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_dist_plot", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001213.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "resid_plot", "tests": "import unittest\n\nclass Test_resid_plot(unittest.TestCase):\n def test_resid_plot(self):\n \"\"\"\n Test resid_plot\n \"\"\"\n MYPLOT.resid_plot()\n self.assertEqual(1, 1)\n\n def test_resid_plot_arg_err(self):\n \"\"\"\n Check error for resid_plot, with no assigned variables\n \"\"\"\n try:\n test_plot = plt.RegressionAnalysisPlot(DF)\n test_plot.resid_plot()\n except Exception as err:\n self.assertEqual(err.args[0], 'No predictors or response assigned')\n", "method_code": " def resid_plot(self, var_x=None, var_y=None):\n \"\"\"\n Create a residuals VS fitted plot\n Input:\n - var_x: A list of predictor variable(s) (default=None)\n - var_y: A response variable (default=None)\n \"\"\"\n dataframe = self.get_dataframe()\n if var_x is not None and var_y is not None:\n self.reg(var_x, var_y)\n else:\n var_x = self.get_predictors()\n var_y = self.get_response()\n if var_x is not None and var_y is not None:\n self.reg(var_x, var_y)\n else:\n raise ValueError('No predictors or response assigned')\n model = self.get_model()\n fitted = model.fittedvalues\n sns.residplot(fitted, var_y, data=dataframe, lowess=True, scatter_kws={'alpha': 0.5}, line_kws={'color': 'red', 'lw': 1, 'alpha': 1})\n plt.title('Residuals vs Fitted')\n plt.xlabel('Fitted values')\n plt.ylabel('Residuals')\n ", "context": "class RegressionAnalysisPlot(object):\n def resid_plot(self, var_x=None, var_y=None): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_resid_plot", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001214.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "qq_plot", "tests": "import unittest\n\nclass Test_qq_plot(unittest.TestCase):\n def test_qq_plot(self):\n \"\"\"\n Test qq_plot\n \"\"\"\n MYPLOT.qq_plot()\n self.assertEqual(1, 1)\n\n def test_qq_plot_arg_err(self):\n \"\"\"\n Check error for qq_plot, with no assigned variables\n \"\"\"\n try:\n test_plot = plt.RegressionAnalysisPlot(DF)\n test_plot.qq_plot()\n except Exception as err:\n self.assertEqual(err.args[0], 'No predictors or response assigned')\n", "method_code": " def qq_plot(self, var_x=None, var_y=None):\n \"\"\"\n Creates a normal qq plot\n Input:\n - var_x: A list of predictor variable(s) (default=None)\n - var_y: A response variable (default=None)\n \"\"\"\n if var_x is not None and var_y is not None:\n self.reg(var_x, var_y)\n else:\n var_x = self.get_predictors()\n var_y = self.get_response()\n if var_x is not None and var_y is not None:\n self.reg(var_x, var_y)\n else:\n raise ValueError('No predictors or response assigned')\n model = self.get_model()\n resid_norm = model.get_influence().resid_studentized_internal\n qq_plt = ProbPlot(resid_norm)\n theo = qq_plt.theoretical_quantiles\n sample = qq_plt.sample_quantiles\n plt.scatter(theo, sample, alpha=0.5)\n sns.regplot(theo, theo, scatter=False, ci=False, lowess=True, line_kws={'color': 'red', 'lw': 1, 'alpha': 1})\n plt.title('Normal Q-Q')\n plt.xlabel('Theoretical Quantiles')\n plt.ylabel('Standardized Residuals')\n ", "context": "class RegressionAnalysisPlot(object):\n def qq_plot(self, var_x=None, var_y=None): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_qq_plot", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001215.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "scale_loc_plot", "tests": "import unittest\n\nclass Test_scale_loc_plot(unittest.TestCase):\n def test_scale_loc_plot(self):\n \"\"\"\n Test scale_loc_plot\n \"\"\"\n MYPLOT.scale_loc_plot()\n self.assertEqual(1, 1)\n\n def test_scale_loc_plot_assign_arg(self):\n \"\"\"\n Test scale_loc_plot, with input\n \"\"\"\n MYPLOT.scale_loc_plot(var_x=DF.columns[0], var_y=DF.columns[1])\n self.assertEqual(1, 1)\n\n def test_scale_loc_plot_arg_err(self):\n \"\"\"\n Check error for scale_loc_plot, with no assigned variables\n \"\"\"\n try:\n test_plot = plt.RegressionAnalysisPlot(DF)\n test_plot.scale_loc_plot()\n except Exception as err:\n self.assertEqual(err.args[0], 'No predictors or response assigned')\n", "method_code": " def scale_loc_plot(self, var_x=None, var_y=None):\n \"\"\"\n Creates a scale-location plot\n Goal: Check if the residuals suffer from non-constant variance, i.e.,\n heteroscedasticity\n Input:\n - var_x: A list of predictor variable(s) (default=None)\n - var_y: A response variable (default=None)\n \"\"\"\n if var_x is not None and var_y is not None:\n self.reg(var_x, var_y)\n else:\n var_x = self.get_predictors()\n var_y = self.get_response()\n if var_x is not None and var_y is not None:\n self.reg(var_x, var_y)\n else:\n raise ValueError('No predictors or response assigned')\n model = self.get_model()\n fitted = model.fittedvalues\n resid_norm = model.get_influence().resid_studentized_internal\n resid_norm_abs_sqrt = np.sqrt(np.abs(resid_norm))\n plt.scatter(fitted, resid_norm_abs_sqrt, alpha=0.5)\n sns.regplot(fitted, resid_norm_abs_sqrt, scatter=False, ci=False, lowess=True, line_kws={'color': 'red', 'lw': 1, 'alpha': 1})\n plt.title('Scale-Location')\n plt.xlabel('Fitted values')\n plt.ylabel('Absolute squared normalized residuals')\n ", "context": "class RegressionAnalysisPlot(object):\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_scale_loc_plot", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001216.py"} {"focal_file": "betas/regression_analysis_plot.py", "focal_class": null, "focal_method": "resid_lever_plot", "tests": "import unittest\n\nclass Test_resid_lever_plot(unittest.TestCase):\n def test_resid_lever_plot(self):\n \"\"\"\n Test resid_lever_plot\n \"\"\"\n MYPLOT.resid_lever_plot()\n self.assertEqual(1, 1)\n\n def test_resid_lever_plot_assign_arg(self):\n \"\"\"\n Test resid_lever_plot, with input\n \"\"\"\n MYPLOT.resid_lever_plot(var_x=DF.columns[0], var_y=DF.columns[1])\n self.assertEqual(1, 1)\n\n def test_resid_lever_plot_arg_err(self):\n \"\"\"\n Check error for resid_lever_plot, with no assigned variables\n \"\"\"\n try:\n test_plot = plt.RegressionAnalysisPlot(DF)\n test_plot.resid_lever_plot()\n except Exception as err:\n self.assertEqual(err.args[0], 'No predictors or response assigned')\n", "method_code": " def resid_lever_plot(self, var_x=None, var_y=None):\n \"\"\"\n Creates a residuals vs leverage plot\n Input:\n - var_x: A list of predictor variable(s) (default=None)\n - var_y: A response variable (default=None)\n \"\"\"\n if var_x is not None and var_y is not None:\n self.reg(var_x, var_y)\n else:\n var_x = self.get_predictors()\n var_y = self.get_response()\n if var_x is not None and var_y is not None:\n self.reg(var_x, var_y)\n else:\n raise ValueError('No predictors or response assigned')\n model = self.get_model()\n model_leverage = model.get_influence().hat_matrix_diag\n resid_norm = model.get_influence().resid_studentized_internal\n plt.scatter(model_leverage, resid_norm, alpha=0.5)\n sns.regplot(model_leverage, resid_norm, scatter=False, ci=False, lowess=True, line_kws={'color': 'red', 'lw': 1, 'alpha': 1})\n plt.title('Residuals vs Leverage')\n plt.xlabel('Leverage')\n plt.ylabel('Standardized Residuals')\n ", "context": "class RegressionAnalysisPlot(object):\n def resid_lever_plot(self, var_x=None, var_y=None): ...\n def __init__(self, dataframe, predictors=None, response=None): ...\n def get_dataframe(self): ...\n def get_predictors(self): ...\n def get_response(self): ...\n def get_model(self): ...\n def set_predictors(self, predictors): ...\n def set_response(self, response): ...\n def set_model(self, model): ...\n def matrix_plot(self, label=None): ...\n def corr_heatmap(self, **kwargs): ...\n def reg_plot(self, var_x, var_y): ...\n def box_plot(self, var_x, var_y): ...\n def dist_plot(self, var_x, var_y): ...\n def reg(self, var_x=None, var_y=None, report=False): ...\n def resid_plot(self, var_x=None, var_y=None): ...\n def qq_plot(self, var_x=None, var_y=None): ...\n def scale_loc_plot(self, var_x=None, var_y=None): ...\n\n self.dataframe = dataframe\n self.predictors = predictors\n self.response = response\n self.model = None\n", "repository": "betas-org/betas", "test_name": "test_resid_lever_plot", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_001217.py"} {"focal_file": "imagetools/image_upload.py", "focal_class": null, "focal_method": "data_save", "tests": "import unittest\n\nclass Test_data_save(unittest.TestCase):\n def test_image_upload(self):\n data = self.cloudscreen.takeshot()\n os.environ['PLATFORM_IP'] = '0.0.0.0'\n self.image_upload.data_save(data, 'test.jpg')\n for i in range(0, 100):\n data = self.cloudscreen.takeshot()\n self.image_upload.upload_image(data, (50, 50), Color.PURPLE, 2)\n self.image_upload.upload_image(data, (50, 50), Color.PURPLE, 1)\n self.image_upload.upload_image(data, (50, 50), Color.PURPLE, 10)\n", "method_code": " def data_save(self, data, file_path):\n data_write(data, file_path)\n ", "context": "class ImageUpload(object):\n def data_save(self, data, file_path): ...\n def __init__(self, _testid, _deviceid): ...\n def set_image_index(self, _image_index): ...\n def set_local_image_path(self, path=local_image_save_path): ...\n def __get_image_index(self): ...\n def __back_image_index(self): ...\n def _upload_image(self, image_data, point=None, tag_color=Color.RED, radius=8, time_stamp=time.time() * 1000): ...\n def _report_ui_issue(self, image_data, time_stamp, image_index, issame=False): ...\n def _save2localdirectory(self, image, path, point=None, tag_color=Color.RED, radius=8): ...\n def upload_image(self, image, point, issame=None, tag_color=Color.RED, radius=8, time_stamp=time.time() * 1000): ...\n\n self.image_index = 1\n self.info_server = get_info_server()\n self.image_server = get_image_server()\n self.last_image_issue = ImageErrorCode.NORMAL\n self.local_image_path = './screen_images/'\n", "repository": "vegeta34/Pluto", "test_name": "test_image_upload", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001218.py"} {"focal_file": "vendor/oauth2client/_helpers.py", "focal_class": null, "focal_method": "_add_query_parameter", "tests": "import unittest\n\nclass Test_add_query_parameter(unittest.TestCase):\n def test__add_query_parameter(self):\n self.assertEqual(_helpers._add_query_parameter('/action', 'a', None), '/action')\n self.assertEqual(_helpers._add_query_parameter('/action', 'a', 'b'), '/action?a=b')\n self.assertEqual(_helpers._add_query_parameter('/action?a=b', 'a', 'c'), '/action?a=c')\n self.assertIn(_helpers._add_query_parameter('/action?a=b', 'c', 'd'), ['/action?a=b&c=d', '/action?c=d&a=b'])\n self.assertEqual(_helpers._add_query_parameter('/action', 'a', ' ='), '/action?a=+%3D')\n", "method_code": "def _add_query_parameter(url, name, value):\n \"\"\"Adds a query parameter to a url.\n\n Replaces the current value if it already exists in the URL.\n\n Args:\n url: string, url to add the query parameter to.\n name: string, query parameter name.\n value: string, query parameter value.\n\n Returns:\n Updated query parameter. Does not update the url if value is None.\n \"\"\"\n if value is None:\n return url\n else:\n return update_query_params(url, {name: value})", "context": "def _add_query_parameter(url, name, value): ...\ndef positional(max_positional_args): ...\ndef scopes_to_string(scopes): ...\ndef string_to_scopes(scopes): ...\ndef parse_unique_urlencoded(content): ...\ndef update_query_params(uri, params): ...\ndef _add_query_parameter(url, name, value): ...\ndef validate_file(filename): ...\ndef _parse_pem_key(raw_key_input): ...\ndef _json_encode(data): ...\ndef _to_bytes(value, encoding='ascii'): ...\ndef _from_bytes(value): ...\ndef _urlsafe_b64encode(raw_bytes): ...\ndef _urlsafe_b64decode(b64string): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__add_query_parameter", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001219.py"} {"focal_file": "vendor/oauth2client/_helpers.py", "focal_class": null, "focal_method": "update_query_params", "tests": "import unittest\n\nclass Test_update_query_params(unittest.TestCase):\n def test_update_query_params_no_params(self):\n uri = 'http://www.google.com'\n updated = _helpers.update_query_params(uri, {'a': 'b'})\n self.assertEqual(updated, uri + '?a=b')\n\n def test_update_query_params_existing_params(self):\n uri = 'http://www.google.com?x=y'\n updated = _helpers.update_query_params(uri, {'a': 'b', 'c': 'd&'})\n hardcoded_update = uri + '&a=b&c=d%26'\n test_client.assertUrisEqual(self, updated, hardcoded_update)\n\n def test_update_query_params_replace_param(self):\n base_uri = 'http://www.google.com'\n uri = base_uri + '?x=a'\n updated = _helpers.update_query_params(uri, {'x': 'b', 'y': 'c'})\n hardcoded_update = base_uri + '?x=b&y=c'\n test_client.assertUrisEqual(self, updated, hardcoded_update)\n\n def test_update_query_params_repeated_params(self):\n uri = 'http://www.google.com?x=a&x=b'\n with self.assertRaises(ValueError):\n _helpers.update_query_params(uri, {'a': 'c'})\n", "method_code": "def update_query_params(uri, params):\n \"\"\"Updates a URI with new query parameters.\n\n If a given key from ``params`` is repeated in the ``uri``, then\n the URI will be considered invalid and an error will occur.\n\n If the URI is valid, then each value from ``params`` will\n replace the corresponding value in the query parameters (if\n it exists).\n\n Args:\n uri: string, A valid URI, with potential existing query parameters.\n params: dict, A dictionary of query parameters.\n\n Returns:\n The same URI but with the new query parameters added.\n \"\"\"\n parts = urllib.parse.urlparse(uri)\n query_params = parse_unique_urlencoded(parts.query)\n query_params.update(params)\n new_query = urllib.parse.urlencode(query_params)\n new_parts = parts._replace(query=new_query)\n return urllib.parse.urlunparse(new_parts)", "context": "def update_query_params(uri, params): ...\ndef positional(max_positional_args): ...\ndef scopes_to_string(scopes): ...\ndef string_to_scopes(scopes): ...\ndef parse_unique_urlencoded(content): ...\ndef update_query_params(uri, params): ...\ndef _add_query_parameter(url, name, value): ...\ndef validate_file(filename): ...\ndef _parse_pem_key(raw_key_input): ...\ndef _json_encode(data): ...\ndef _to_bytes(value, encoding='ascii'): ...\ndef _from_bytes(value): ...\ndef _urlsafe_b64encode(raw_bytes): ...\ndef _urlsafe_b64decode(b64string): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_update_query_params_no_params", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001220.py"} {"focal_file": "vendor/oauth2client/_pkce.py", "focal_class": null, "focal_method": "code_verifier", "tests": "import unittest\n\nclass Test_code_verifier(unittest.TestCase):\n @mock.patch('oauth2client._pkce.os.urandom')\n def test_verifier(self, fake_urandom):\n canned_randomness = b'\\x98\\x10D7\\xf3\\xb7\\xaa\\xfc\\xdd\\xd3M\\xe2\\xa3,\\x06\\xa0\\xb0\\xa9\\xb4\\x8f\\xcb\\xd0\\xf5\\x86N2p\\x8c]!W\\x9a\\xed54\\x99\\x9d\\x8dv\\\\\\xa7/\\x81\\xf3J\\x98\\xc3\\x90\\xee\\xb0\\x8c\\xb7Zc#\\x05M0O\\x08\\xda\\t\\x1f\\x07'\n fake_urandom.return_value = canned_randomness\n expected = b'mBBEN_O3qvzd003ioywGoLCptI_L0PWGTjJwjF0hV5rtNTSZnY12XKcvgfNKmMOQ7rCMt1pjIwVNME8I2gkfBw=='\n result = _pkce.code_verifier()\n self.assertEqual(result, expected)\n", "method_code": "def code_verifier(n_bytes=64):\n \"\"\"\n Generates a 'code_verifier' as described in section 4.1 of RFC 7636.\n\n This is a 'high-entropy cryptographic random string' that will be\n impractical for an attacker to guess.\n\n Args:\n n_bytes: integer between 31 and 96, inclusive. default: 64\n number of bytes of entropy to include in verifier.\n\n Returns:\n Bytestring, representing urlsafe base64-encoded random data.\n \"\"\"\n verifier = base64.urlsafe_b64encode(os.urandom(n_bytes))\n if len(verifier) < 43:\n raise ValueError('Verifier too short. n_bytes must be > 30.')\n elif len(verifier) > 128:\n raise ValueError('Verifier too long. n_bytes must be < 97.')\n else:\n return verifier", "context": "def code_verifier(n_bytes=64): ...\ndef code_verifier(n_bytes=64): ...\ndef code_challenge(verifier): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001221.py"} {"focal_file": "vendor/oauth2client/_pkce.py", "focal_class": null, "focal_method": "code_challenge", "tests": "import unittest\n\nclass Test_code_challenge(unittest.TestCase):\n def test_challenge(self):\n result = _pkce.code_challenge(b'SOME_VERIFIER')\n expected = b'6xJCQsjTtS3zjUwd8_ZqH0SyviGHnp5PsHXWKOCqDuI='\n self.assertEqual(result, expected)\n", "method_code": "def code_challenge(verifier):\n \"\"\"\n Creates a 'code_challenge' as described in section 4.2 of RFC 7636\n by taking the sha256 hash of the verifier and then urlsafe\n base64-encoding it.\n\n Args:\n verifier: bytestring, representing a code_verifier as generated by\n code_verifier().\n\n Returns:\n Bytestring, representing a urlsafe base64-encoded sha256 hash digest.\n \"\"\"\n return base64.urlsafe_b64encode(hashlib.sha256(verifier).digest())", "context": "def code_challenge(verifier): ...\ndef code_verifier(n_bytes=64): ...\ndef code_challenge(verifier): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_challenge", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001222.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.Credentials", "focal_method": "_to_json", "tests": "import unittest\n\nclass Test_oauth2client_client_Credentials_to_json(unittest.TestCase):\n def test__to_json_basic(self):\n credentials = client.Credentials()\n json_payload = credentials._to_json([])\n self.assertIsInstance(json_payload, str)\n payload = json.loads(json_payload)\n expected_payload = {'_class': client.Credentials.__name__, '_module': client.Credentials.__module__, 'token_expiry': None}\n self.assertEqual(payload, expected_payload)\n", "method_code": " def _to_json(self, strip, to_serialize=None):\n \"\"\"Utility function that creates JSON repr. of a Credentials object.\n \n Args:\n strip: array, An array of names of members to exclude from the\n JSON.\n to_serialize: dict, (Optional) The properties for this object\n that will be serialized. This allows callers to\n modify before serializing.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n curr_type = self.__class__\n if to_serialize is None:\n to_serialize = copy.copy(self.__dict__)\n else:\n to_serialize = copy.copy(to_serialize)\n for member in strip:\n if member in to_serialize:\n del to_serialize[member]\n to_serialize['token_expiry'] = _parse_expiry(to_serialize.get('token_expiry'))\n to_serialize['_class'] = curr_type.__name__\n to_serialize['_module'] = curr_type.__module__\n for key, val in to_serialize.items():\n if isinstance(val, bytes):\n to_serialize[key] = val.decode('utf-8')\n if isinstance(val, set):\n to_serialize[key] = list(val)\n return json.dumps(to_serialize)\n ", "context": "class Credentials(object):\n def _to_json(self, strip, to_serialize=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def to_json(self): ...\n def new_from_json(cls, json_data): ...\n def from_json(cls, unused_data): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['store'])\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__to_json_basic", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001223.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.Credentials", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_oauth2client_client_Credentials_to_json(unittest.TestCase):\n @mock.patch.object(client.Credentials, '_to_json', return_value=object())\n def test_to_json(self, to_json):\n credentials = client.Credentials()\n self.assertEqual(credentials.to_json(), to_json.return_value)\n to_json.assert_called_once_with(client.Credentials.NON_SERIALIZED_MEMBERS)\n", "method_code": " def to_json(self):\n \"\"\"Creating a JSON representation of an instance of Credentials.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n return self._to_json(self.NON_SERIALIZED_MEMBERS)\n ", "context": "class Credentials(object):\n def to_json(self): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip, to_serialize=None): ...\n def new_from_json(cls, json_data): ...\n def from_json(cls, unused_data): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['store'])\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001224.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n unused_data = {}\n credentials = client.Credentials.from_json(unused_data)\n self.assertIsInstance(credentials, client.Credentials)\n self.assertEqual(credentials.__dict__, {})\n\n def test_to_from_json(self):\n json = self.credentials.to_json()\n instance = client.OAuth2Credentials.from_json(json)\n self.assertEqual(client.OAuth2Credentials, type(instance))\n instance.token_expiry = None\n self.credentials.token_expiry = None\n self.assertEqual(instance.__dict__, self.credentials.__dict__)\n", "method_code": " def from_json(cls, unused_data):\n \"\"\"Instantiate a Credentials object from a JSON description of it.\n \n The JSON should have been produced by calling .to_json() on the object.\n \n Args:\n unused_data: dict, A deserialized JSON object.\n \n Returns:\n An instance of a Credentials subclass.\n \"\"\"\n return Credentials()\n ", "context": "class Credentials(object):\n @classmethod\n def from_json(cls, unused_data): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip, to_serialize=None): ...\n def to_json(self): ...\n def new_from_json(cls, json_data): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['store'])\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_from_json", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001225.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.Storage", "focal_method": "locked_get", "tests": "import unittest\n\nclass Test_oauth2client_client_Storage_locked_get(unittest.TestCase):\n def test_locked_get_abstract(self):\n storage = client.Storage()\n with self.assertRaises(NotImplementedError):\n storage.locked_get()\n", "method_code": " def locked_get(self):\n \"\"\"Retrieve credential.\n \n The Storage lock must be held when this is called.\n \n Returns:\n oauth2client.client.Credentials\n \"\"\"\n raise NotImplementedError\n ", "context": "class Storage(object):\n def locked_get(self): ...\n def __init__(self, lock=None): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def locked_put(self, credentials): ...\n def locked_delete(self): ...\n def get(self): ...\n def put(self, credentials): ...\n def delete(self): ...\n\n self._lock = lock\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_locked_get_abstract", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001226.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.Storage", "focal_method": "locked_put", "tests": "import unittest\n\nclass Test_oauth2client_client_Storage_locked_put(unittest.TestCase):\n def test_locked_put_abstract(self):\n storage = client.Storage()\n credentials = object()\n with self.assertRaises(NotImplementedError):\n storage.locked_put(credentials)\n", "method_code": " def locked_put(self, credentials):\n \"\"\"Write a credential.\n \n The Storage lock must be held when this is called.\n \n Args:\n credentials: Credentials, the credentials to store.\n \"\"\"\n raise NotImplementedError\n ", "context": "class Storage(object):\n def locked_put(self, credentials): ...\n def __init__(self, lock=None): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def locked_get(self): ...\n def locked_delete(self): ...\n def get(self): ...\n def put(self, credentials): ...\n def delete(self): ...\n\n self._lock = lock\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_locked_put_abstract", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001227.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.Storage", "focal_method": "locked_delete", "tests": "import unittest\n\nclass Test_oauth2client_client_Storage_locked_delete(unittest.TestCase):\n def test_locked_delete_abstract(self):\n storage = client.Storage()\n with self.assertRaises(NotImplementedError):\n storage.locked_delete()\n", "method_code": " def locked_delete(self):\n \"\"\"Delete a credential.\n \n The Storage lock must be held when this is called.\n \"\"\"\n raise NotImplementedError\n ", "context": "class Storage(object):\n def locked_delete(self): ...\n def __init__(self, lock=None): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def locked_get(self): ...\n def locked_put(self, credentials): ...\n def get(self): ...\n def put(self, credentials): ...\n def delete(self): ...\n\n self._lock = lock\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_locked_delete_abstract", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001228.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required(self):\n self.assertFalse(self.get_a_google_credentials_object().create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n \"\"\"Whether this Credentials object is scopeless.\n \n create_scoped(scopes) method needs to be called in order to create\n a Credentials object for API calls.\n \"\"\"\n return False\n ", "context": "class GoogleCredentials(OAuth2Credentials):\n def create_scoped_required(self): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def create_scoped(self, scopes): ...\n def from_json(cls, json_data): ...\n def serialization_data(self): ...\n def _implicit_credentials_from_gae(): ...\n def _implicit_credentials_from_gce(): ...\n def _implicit_credentials_from_files(): ...\n def _get_implicit_credentials(cls): ...\n def get_application_default(): ...\n def from_stream(credential_filename): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['_private_key']) | OAuth2Credentials.NON_SERIALIZED_MEMBERS\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_scoped_required", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001229.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "create_scoped", "tests": "import unittest\n\nclass Test_create_scoped(unittest.TestCase):\n def test_create_scoped(self):\n credentials = self.get_a_google_credentials_object()\n self.assertEqual(credentials, credentials.create_scoped(None))\n self.assertEqual(credentials, credentials.create_scoped(['dummy_scope']))\n", "method_code": " def create_scoped(self, scopes):\n \"\"\"Create a Credentials object for the given scopes.\n \n The Credentials type is preserved.\n \"\"\"\n return self\n ", "context": "class GoogleCredentials(OAuth2Credentials):\n def create_scoped(self, scopes): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def create_scoped_required(self): ...\n def from_json(cls, json_data): ...\n def serialization_data(self): ...\n def _implicit_credentials_from_gae(): ...\n def _implicit_credentials_from_gce(): ...\n def _implicit_credentials_from_files(): ...\n def _get_implicit_credentials(cls): ...\n def get_application_default(): ...\n def from_stream(credential_filename): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['_private_key']) | OAuth2Credentials.NON_SERIALIZED_MEMBERS\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_scoped", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001230.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "get_application_default", "tests": "import unittest\n\nclass Test_get_application_default(unittest.TestCase):\n @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_files', return_value=None)\n @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_gce')\n @mock.patch.object(client, '_in_gae_environment', return_value=True)\n @mock.patch.object(client, '_get_application_default_credential_GAE', return_value=object())\n def test_get_application_default_in_gae(self, gae_adc, in_gae, from_gce, from_files):\n credentials = client.GoogleCredentials.get_application_default()\n self.assertEqual(credentials, gae_adc.return_value)\n from_files.assert_called_once_with()\n in_gae.assert_called_once_with()\n from_gce.assert_not_called()\n\n @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_gae', return_value=None)\n @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_files', return_value=None)\n @mock.patch.object(client, '_in_gce_environment', return_value=True)\n @mock.patch.object(client, '_get_application_default_credential_GCE', return_value=object())\n def test_get_application_default_in_gce(self, gce_adc, in_gce, from_files, from_gae):\n credentials = client.GoogleCredentials.get_application_default()\n self.assertEqual(credentials, gce_adc.return_value)\n in_gce.assert_called_once_with()\n from_gae.assert_called_once_with()\n from_files.assert_called_once_with()\n", "method_code": " def get_application_default():\n \"\"\"Get the Application Default Credentials for the current environment.\n \n Raises:\n ApplicationDefaultCredentialsError: raised when the credentials\n fail to be retrieved.\n \"\"\"\n return GoogleCredentials._get_implicit_credentials()\n ", "context": "class GoogleCredentials(OAuth2Credentials):\n @staticmethod\n def get_application_default(): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def from_json(cls, json_data): ...\n def serialization_data(self): ...\n def _implicit_credentials_from_gae(): ...\n def _implicit_credentials_from_gce(): ...\n def _implicit_credentials_from_files(): ...\n def _get_implicit_credentials(cls): ...\n def from_stream(credential_filename): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['_private_key']) | OAuth2Credentials.NON_SERIALIZED_MEMBERS\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001231.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "_get_environment_variable_file", "tests": "import unittest\n\nclass Test_get_environment_variable_file(unittest.TestCase):\n def test_get_environment_variable_file(self):\n environment_variable_file = datafile(os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))\n os.environ[client.GOOGLE_APPLICATION_CREDENTIALS] = environment_variable_file\n self.assertEqual(environment_variable_file, client._get_environment_variable_file())\n\n def test_get_environment_variable_file_error(self):\n nonexistent_file = datafile('nonexistent')\n os.environ[client.GOOGLE_APPLICATION_CREDENTIALS] = nonexistent_file\n expected_err_msg = 'File {0} \\\\(pointed by {1} environment variable\\\\) does not exist!'.format(nonexistent_file, client.GOOGLE_APPLICATION_CREDENTIALS)\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._get_environment_variable_file()\n\n @mock.patch.dict(os.environ, {}, clear=True)\n def test_get_environment_variable_file_without_env_var(self):\n self.assertIsNone(client._get_environment_variable_file())\n", "method_code": "def _get_environment_variable_file():\n application_default_credential_filename = os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, None)\n if application_default_credential_filename:\n if os.path.isfile(application_default_credential_filename):\n return application_default_credential_filename\n else:\n raise ApplicationDefaultCredentialsError('File ' + application_default_credential_filename + ' (pointed by ' + GOOGLE_APPLICATION_CREDENTIALS + ' environment variable) does not exist!')", "context": "def _get_environment_variable_file(): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_get_environment_variable_file", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001232.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "_get_well_known_file", "tests": "import unittest\n\nclass Test_get_well_known_file(unittest.TestCase):\n @mock.patch('os.name', new='nt')\n @mock.patch.dict(os.environ, {'APPDATA': DATA_DIR}, clear=True)\n def test_get_well_known_file_on_windows(self):\n well_known_file = datafile(os.path.join(client._CLOUDSDK_CONFIG_DIRECTORY, client._WELL_KNOWN_CREDENTIALS_FILE))\n self.assertEqual(well_known_file, client._get_well_known_file())\n\n @mock.patch('os.name', new='nt')\n @mock.patch.dict(os.environ, {'SystemDrive': 'G:'}, clear=True)\n def test_get_well_known_file_on_windows_without_appdata(self):\n well_known_file = os.path.join('G:', '\\\\', client._CLOUDSDK_CONFIG_DIRECTORY, client._WELL_KNOWN_CREDENTIALS_FILE)\n self.assertEqual(well_known_file, client._get_well_known_file())\n\n @mock.patch.dict(os.environ, {client._CLOUDSDK_CONFIG_ENV_VAR: 'CUSTOM_DIR'}, clear=True)\n def test_get_well_known_file_with_custom_config_dir(self):\n CUSTOM_DIR = os.environ[client._CLOUDSDK_CONFIG_ENV_VAR]\n EXPECTED_FILE = os.path.join(CUSTOM_DIR, client._WELL_KNOWN_CREDENTIALS_FILE)\n well_known_file = client._get_well_known_file()\n self.assertEqual(well_known_file, EXPECTED_FILE)\n", "method_code": "def _get_well_known_file():\n \"\"\"Get the well known file produced by command 'gcloud auth login'.\"\"\"\n default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR)\n if default_config_dir is None:\n if os.name == 'nt':\n try:\n default_config_dir = os.path.join(os.environ['APPDATA'], _CLOUDSDK_CONFIG_DIRECTORY)\n except KeyError:\n drive = os.environ.get('SystemDrive', 'C:')\n default_config_dir = os.path.join(drive, '\\\\', _CLOUDSDK_CONFIG_DIRECTORY)\n else:\n default_config_dir = os.path.join(os.path.expanduser('~'), '.config', _CLOUDSDK_CONFIG_DIRECTORY)\n return os.path.join(default_config_dir, _WELL_KNOWN_CREDENTIALS_FILE)", "context": "def _get_well_known_file(): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001233.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "save_to_well_known_file", "tests": "import unittest\n\nclass Test_save_to_well_known_file(unittest.TestCase):\n def test_save_to_well_known_file_service_account(self):\n credential_file = datafile(os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))\n credentials = client._get_application_default_credential_from_file(credential_file)\n temp_credential_file = datafile(os.path.join('gcloud', 'temp_well_known_file_service_account.json'))\n client.save_to_well_known_file(credentials, temp_credential_file)\n with open(temp_credential_file) as f:\n d = json.load(f)\n self.assertEqual('service_account', d['type'])\n self.assertEqual('123', d['client_id'])\n self.assertEqual('dummy@google.com', d['client_email'])\n self.assertEqual('ABCDEF', d['private_key_id'])\n os.remove(temp_credential_file)\n\n def test_save_to_well_known_file_authorized_user(self):\n credentials_file = datafile(os.path.join('gcloud', 'application_default_credentials_authorized_user.json'))\n credentials = client._get_application_default_credential_from_file(credentials_file)\n temp_credential_file = datafile(os.path.join('gcloud', 'temp_well_known_file_authorized_user.json'))\n client.save_to_well_known_file(credentials, temp_credential_file)\n with open(temp_credential_file) as f:\n d = json.load(f)\n self.assertEqual('authorized_user', d['type'])\n self.assertEqual('123', d['client_id'])\n self.assertEqual('secret', d['client_secret'])\n self.assertEqual('alabalaportocala', d['refresh_token'])\n os.remove(temp_credential_file)\n", "method_code": "def save_to_well_known_file(credentials, well_known_file=None):\n \"\"\"Save the provided GoogleCredentials to the well known file.\n\n Args:\n credentials: the credentials to be saved to the well known file;\n it should be an instance of GoogleCredentials\n well_known_file: the name of the file where the credentials are to be\n saved; this parameter is supposed to be used for\n testing only\n \"\"\"\n if well_known_file is None:\n well_known_file = _get_well_known_file()\n config_dir = os.path.dirname(well_known_file)\n if not os.path.isdir(config_dir):\n raise OSError('Config directory does not exist: {0}'.format(config_dir))\n credentials_data = credentials.serialization_data\n _save_private_file(well_known_file, credentials_data)", "context": "def save_to_well_known_file(credentials, well_known_file=None): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_save_to_well_known_file_service_account", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001234.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "_get_application_default_credential_from_file", "tests": "import unittest\n\nclass Test_get_application_default_credential_from_file(unittest.TestCase):\n def test_get_application_default_credential_from_malformed_file_1(self):\n credentials_file = datafile(os.path.join('gcloud', 'application_default_credentials_malformed_1.json'))\n expected_err_msg = \"'type' field should be defined \\\\(and have one of the '{0}' or '{1}' values\\\\)\".format(client.AUTHORIZED_USER, client.SERVICE_ACCOUNT)\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._get_application_default_credential_from_file(credentials_file)\n\n def test_get_application_default_credential_from_malformed_file_2(self):\n credentials_file = datafile(os.path.join('gcloud', 'application_default_credentials_malformed_2.json'))\n expected_err_msg = 'The following field\\\\(s\\\\) must be defined: private_key_id'\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._get_application_default_credential_from_file(credentials_file)\n\n def test_get_application_default_credential_from_malformed_file_3(self):\n credentials_file = datafile(os.path.join('gcloud', 'application_default_credentials_malformed_3.json'))\n with self.assertRaises(ValueError):\n client._get_application_default_credential_from_file(credentials_file)\n", "method_code": "def _get_application_default_credential_from_file(filename):\n \"\"\"Build the Application Default Credentials from file.\"\"\"\n with open(filename) as file_obj:\n client_credentials = json.load(file_obj)\n credentials_type = client_credentials.get('type')\n if credentials_type == AUTHORIZED_USER:\n required_fields = set(['client_id', 'client_secret', 'refresh_token'])\n elif credentials_type == SERVICE_ACCOUNT:\n required_fields = set(['client_id', 'client_email', 'private_key_id', 'private_key'])\n else:\n raise ApplicationDefaultCredentialsError(\"'type' field should be defined (and have one of the '\" + AUTHORIZED_USER + \"' or '\" + SERVICE_ACCOUNT + \"' values)\")\n missing_fields = required_fields.difference(client_credentials.keys())\n if missing_fields:\n _raise_exception_for_missing_fields(missing_fields)\n if client_credentials['type'] == AUTHORIZED_USER:\n return GoogleCredentials(access_token=None, client_id=client_credentials['client_id'], client_secret=client_credentials['client_secret'], refresh_token=client_credentials['refresh_token'], token_expiry=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, user_agent='Python client library')\n else:\n from oauth2client import service_account\n return service_account._JWTAccessCredentials.from_json_keyfile_dict(client_credentials)", "context": "def _get_application_default_credential_from_file(filename): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_get_application_default_credential_from_malformed_file_1", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001235.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "_raise_exception_for_missing_fields", "tests": "import unittest\n\nclass Test_raise_exception_for_missing_fields(unittest.TestCase):\n def test_raise_exception_for_missing_fields(self):\n missing_fields = ['first', 'second', 'third']\n expected_err_msg = 'The following field\\\\(s\\\\) must be defined: ' + ', '.join(missing_fields)\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._raise_exception_for_missing_fields(missing_fields)\n", "method_code": "def _raise_exception_for_missing_fields(missing_fields):\n raise ApplicationDefaultCredentialsError('The following field(s) must be defined: ' + ', '.join(missing_fields))", "context": "def _raise_exception_for_missing_fields(missing_fields): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_raise_exception_for_missing_fields", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001236.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.ApplicationDefaultCredentialsError", "focal_method": "_raise_exception_for_reading_json", "tests": "import unittest\n\nclass Test_oauth2client_client_ApplicationDefaultCredentialsError_raise_exception_for_reading_json(unittest.TestCase):\n def test_raise_exception_for_reading_json(self):\n credential_file = 'any_file'\n extra_help = ' be good'\n error = client.ApplicationDefaultCredentialsError('stuff happens')\n expected_err_msg = 'An error was encountered while reading json file: ' + credential_file + extra_help + ': ' + str(error)\n with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg):\n client._raise_exception_for_reading_json(credential_file, extra_help, error)\n", "method_code": "def _raise_exception_for_reading_json(credential_file, extra_help, error):\n raise ApplicationDefaultCredentialsError('An error was encountered while reading json file: ' + credential_file + extra_help + ': ' + str(error))", "context": "def _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_raise_exception_for_reading_json", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001237.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "_parse_expiry", "tests": "import unittest\n\nclass Test_parse_expiry(unittest.TestCase):\n def test_parse_expiry(self):\n dt = datetime.datetime(2016, 1, 1)\n parsed_expiry = client._parse_expiry(dt)\n self.assertEqual('2016-01-01T00:00:00Z', parsed_expiry)\n", "method_code": "def _parse_expiry(expiry):\n if expiry and isinstance(expiry, datetime.datetime):\n return expiry.strftime(EXPIRY_FORMAT)\n else:\n return None", "context": "def _parse_expiry(expiry): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_parse_expiry", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001238.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "authorize", "tests": "import unittest\n\nclass Test_authorize(unittest.TestCase):\n def test_recursive_authorize(self):\n token_response = {'access_token': '1/3w', 'expires_in': 3600}\n encoded_response = json.dumps(token_response).encode('utf-8')\n http = http_mock.HttpMock(data=encoded_response)\n http = self.credentials.authorize(http)\n http = self.credentials.authorize(http)\n transport.request(http, 'http://example.com')\n", "method_code": " def authorize(self, http):\n \"\"\"Take an httplib2.Http instance (or equivalent) and authorizes it.\n \n Authorizes it for the set of credentials, usually by replacing\n http.request() with a method that adds in the appropriate headers and\n then delegates to the original Http.request() method.\n \n Args:\n http: httplib2.Http, an http object to be used to make the refresh\n request.\n \"\"\"\n raise NotImplementedError\n ", "context": "class Credentials(object):\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip, to_serialize=None): ...\n def to_json(self): ...\n def new_from_json(cls, json_data): ...\n def from_json(cls, unused_data): ...\n\n NON_SERIALIZED_MEMBERS = frozenset(['store'])\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_recursive_authorize", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001239.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2Credentials", "focal_method": "_expires_in", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2Credentials_expires_in(unittest.TestCase):\n def test__expires_in_no_expiry(self):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n self.assertIsNone(credentials.token_expiry)\n self.assertIsNone(credentials._expires_in())\n\n @mock.patch('oauth2client.client._UTCNOW')\n def test__expires_in_expired(self, utcnow):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n credentials.token_expiry = datetime.datetime.utcnow()\n now = credentials.token_expiry + datetime.timedelta(seconds=1)\n self.assertLess(credentials.token_expiry, now)\n utcnow.return_value = now\n self.assertEqual(credentials._expires_in(), 0)\n utcnow.assert_called_once_with()\n\n @mock.patch('oauth2client.client._UTCNOW')\n def test__expires_in_not_expired(self, utcnow):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n credentials.token_expiry = datetime.datetime.utcnow()\n seconds = 1234\n now = credentials.token_expiry - datetime.timedelta(seconds=seconds)\n self.assertLess(now, credentials.token_expiry)\n utcnow.return_value = now\n self.assertEqual(credentials._expires_in(), seconds)\n utcnow.assert_called_once_with()\n", "method_code": " def _expires_in(self):\n \"\"\"Return the number of seconds until this token expires.\n \n If token_expiry is in the past, this method will return 0, meaning the\n token has already expired.\n \n If token_expiry is None, this method will return None. Note that\n returning 0 in such a case would not be fair: the token may still be\n valid; we just don't know anything about it.\n \"\"\"\n if self.token_expiry:\n now = _UTCNOW()\n if self.token_expiry > now:\n time_delta = self.token_expiry - now\n return time_delta.days * 86400 + time_delta.seconds\n else:\n return 0\n ", "context": "class OAuth2Credentials(Credentials):\n def _expires_in(self): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def has_scopes(self, scopes): ...\n def retrieve_scopes(self, http): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def get_access_token(self, http=None): ...\n def set_store(self, store): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__expires_in_no_expiry", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001240.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "get_access_token", "tests": "import unittest\n\nclass Test_get_access_token(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n def test_get_access_token(self, utcnow):\n seconds = 11\n NOW = datetime.datetime(1992, 12, 31, second=seconds)\n utcnow.return_value = NOW\n lifetime = 2\n EXPIRY_TIME = datetime.datetime(1992, 12, 31, second=seconds + lifetime)\n token1 = u'first_token'\n token_response_first = {'access_token': token1, 'expires_in': lifetime}\n token2 = u'second_token'\n token_response_second = {'access_token': token2, 'expires_in': lifetime}\n http = http_mock.HttpMockSequence([({'status': '200'}, json.dumps(token_response_first).encode('utf-8')), ({'status': '200'}, json.dumps(token_response_second).encode('utf-8'))])\n credentials = copy.deepcopy(self.credentials)\n credentials.access_token = None\n credentials.token_expiry = None\n self.assertEqual(credentials.access_token, None)\n self.assertFalse(credentials.access_token_expired)\n self.assertEqual(credentials.token_expiry, None)\n token = credentials.get_access_token(http=http)\n self.assertEqual(credentials.token_expiry, EXPIRY_TIME)\n self.assertEqual(token1, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertEqual(token_response_first, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * 2\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(credentials.access_token, token1)\n self.assertFalse(credentials.access_token_expired)\n token = credentials.get_access_token(http=http)\n self.assertEqual(token1, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertEqual(token_response_first, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * (2 + 3)\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(credentials.access_token, token1)\n credentials.token_expiry = NOW\n self.assertTrue(credentials.access_token_expired)\n token = credentials.get_access_token(http=http)\n self.assertEqual(token2, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertFalse(credentials.access_token_expired)\n self.assertEqual(token_response_second, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * (2 + 3 + 5)\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n", "method_code": " def get_access_token(self, http=None):\n \"\"\"Return the access token and its expiration information.\n \n If the token does not exist, get one.\n If the token expired, refresh it.\n \"\"\"\n if not self.access_token or self.access_token_expired:\n if not http:\n http = transport.get_http_object()\n self.refresh(http)\n return AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())\n ", "context": "class OAuth2Credentials(Credentials):\n def get_access_token(self, http=None): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def has_scopes(self, scopes): ...\n def retrieve_scopes(self, http): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def set_store(self, store): ...\n def _expires_in(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001241.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2Credentials", "focal_method": "get_access_token", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2Credentials_get_access_token(unittest.TestCase):\n @mock.patch.object(client.OAuth2Credentials, 'refresh')\n @mock.patch.object(client.OAuth2Credentials, '_expires_in', return_value=1835)\n def test_get_access_token_without_http(self, expires_in, refresh_mock):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n credentials.invalid = True\n credentials.access_token = 'ya29-s3kr3t'\n with mock.patch('oauth2client.transport.get_http_object', return_value=object()) as new_http:\n token_info = credentials.get_access_token()\n expires_in.assert_called_once_with()\n refresh_mock.assert_called_once_with(new_http.return_value)\n new_http.assert_called_once_with()\n self.assertIsInstance(token_info, client.AccessTokenInfo)\n self.assertEqual(token_info.access_token, credentials.access_token)\n self.assertEqual(token_info.expires_in, expires_in.return_value)\n\n @mock.patch.object(client.OAuth2Credentials, 'refresh')\n @mock.patch.object(client.OAuth2Credentials, '_expires_in', return_value=1835)\n def test_get_access_token_with_http(self, expires_in, refresh_mock):\n credentials = client.OAuth2Credentials(None, None, None, None, None, None, None)\n credentials.invalid = True\n credentials.access_token = 'ya29-s3kr3t'\n http_obj = object()\n token_info = credentials.get_access_token(http_obj)\n self.assertIsInstance(token_info, client.AccessTokenInfo)\n self.assertEqual(token_info.access_token, credentials.access_token)\n self.assertEqual(token_info.expires_in, expires_in.return_value)\n expires_in.assert_called_once_with()\n refresh_mock.assert_called_once_with(http_obj)\n", "method_code": " def get_access_token(self, http=None):\n \"\"\"Return the access token and its expiration information.\n \n If the token does not exist, get one.\n If the token expired, refresh it.\n \"\"\"\n if not self.access_token or self.access_token_expired:\n if not http:\n http = transport.get_http_object()\n self.refresh(http)\n return AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())\n ", "context": "class OAuth2Credentials(Credentials):\n def get_access_token(self, http=None): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def has_scopes(self, scopes): ...\n def retrieve_scopes(self, http): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def set_store(self, store): ...\n def _expires_in(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001242.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "has_scopes", "tests": "import unittest\n\nclass Test_has_scopes(unittest.TestCase):\n def test_has_scopes(self):\n self.assertTrue(self.credentials.has_scopes('foo'))\n self.assertTrue(self.credentials.has_scopes(['foo']))\n self.assertFalse(self.credentials.has_scopes('bar'))\n self.assertFalse(self.credentials.has_scopes(['bar']))\n self.credentials.scopes = set(['foo', 'bar'])\n self.assertTrue(self.credentials.has_scopes('foo'))\n self.assertTrue(self.credentials.has_scopes('bar'))\n self.assertFalse(self.credentials.has_scopes('baz'))\n self.assertTrue(self.credentials.has_scopes(['foo', 'bar']))\n self.assertFalse(self.credentials.has_scopes(['foo', 'baz']))\n self.credentials.scopes = set([])\n self.assertFalse(self.credentials.has_scopes('foo'))\n", "method_code": " def has_scopes(self, scopes):\n \"\"\"Verify that the credentials are authorized for the given scopes.\n \n Returns True if the credentials authorized scopes contain all of the\n scopes given.\n \n Args:\n scopes: list or string, the scopes to check.\n \n Notes:\n There are cases where the credentials are unaware of which scopes\n are authorized. Notably, credentials obtained and stored before\n this code was added will not have scopes, AccessTokenCredentials do\n not have scopes. In both cases, you can use refresh_scopes() to\n obtain the canonical set of scopes.\n \"\"\"\n scopes = _helpers.string_to_scopes(scopes)\n return set(scopes).issubset(self.scopes)\n ", "context": "class OAuth2Credentials(Credentials):\n def has_scopes(self, scopes): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def retrieve_scopes(self, http): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def get_access_token(self, http=None): ...\n def set_store(self, store): ...\n def _expires_in(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_has_scopes", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001243.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "retrieve_scopes", "tests": "import unittest\n\nclass Test_retrieve_scopes(unittest.TestCase):\n def test_retrieve_scopes(self):\n info_response_first = {'scope': 'foo bar'}\n info_response_second = {'error_description': 'abcdef'}\n http = http_mock.HttpMockSequence([({'status': '200'}, json.dumps(info_response_first).encode('utf-8')), ({'status': '400'}, json.dumps(info_response_second).encode('utf-8')), ({'status': '500'}, b'')])\n self.credentials.retrieve_scopes(http)\n self.assertEqual(set(['foo', 'bar']), self.credentials.scopes)\n with self.assertRaises(client.Error):\n self.credentials.retrieve_scopes(http)\n with self.assertRaises(client.Error):\n self.credentials.retrieve_scopes(http)\n", "method_code": " def retrieve_scopes(self, http):\n \"\"\"Retrieves the canonical list of scopes for this access token.\n \n Gets the scopes from the OAuth2 provider.\n \n Args:\n http: httplib2.Http, an http object to be used to make the refresh\n request.\n \n Returns:\n A set of strings containing the canonical list of scopes.\n \"\"\"\n self._retrieve_scopes(http)\n return self.scopes\n ", "context": "class OAuth2Credentials(Credentials):\n def retrieve_scopes(self, http): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None, scopes=None, token_info_uri=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def has_scopes(self, scopes): ...\n def from_json(cls, json_data): ...\n def access_token_expired(self): ...\n def get_access_token(self, http=None): ...\n def set_store(self, store): ...\n def _expires_in(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http): ...\n def _do_refresh_request(self, http): ...\n def _revoke(self, http): ...\n def _do_revoke(self, http, token): ...\n def _retrieve_scopes(self, http): ...\n def _do_retrieve_scopes(self, http, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.scopes = set(_helpers.string_to_scopes(scopes or []))\n self.token_info_uri = token_info_uri\n self.invalid = False\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_retrieve_scopes", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001244.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.AssertionCredentials", "focal_method": "_generate_assertion", "tests": "import unittest\n\nclass Test_oauth2client_client_AssertionCredentials_generate_assertion(unittest.TestCase):\n def test__generate_assertion_abstract(self):\n credentials = client.AssertionCredentials(None)\n with self.assertRaises(NotImplementedError):\n credentials._generate_assertion()\n", "method_code": " def _generate_assertion(self):\n \"\"\"Generate assertion string to be used in the access token request.\"\"\"\n raise NotImplementedError\n ", "context": "class AssertionCredentials(GoogleCredentials):\n def _generate_assertion(self): ...\n def __init__(self, assertion_type, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **unused_kwargs): ...\n def _generate_refresh_request_body(self): ...\n def _revoke(self, http): ...\n def sign_blob(self, blob): ...\n\n self.assertion_type = assertion_type\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__generate_assertion_abstract", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001245.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "step1_get_authorize_url", "tests": "import unittest\n\nclass Test_step1_get_authorize_url(unittest.TestCase):\n def test_construct_authorize_url(self):\n authorize_url = self.flow.step1_get_authorize_url(state='state+1')\n parsed = urllib.parse.urlparse(authorize_url)\n q = urllib.parse.parse_qs(parsed[4])\n self.assertEqual('client_id+1', q['client_id'][0])\n self.assertEqual('code', q['response_type'][0])\n self.assertEqual('foo', q['scope'][0])\n self.assertEqual(client.OOB_CALLBACK_URN, q['redirect_uri'][0])\n self.assertEqual('offline', q['access_type'][0])\n self.assertEqual('state+1', q['state'][0])\n", "method_code": " def step1_get_authorize_url(self, redirect_uri=None, state=None):\n \"\"\"Returns a URI to redirect to the provider.\n \n Args:\n redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'\n for a non-web-based application, or a URI that\n handles the callback from the authorization server.\n This parameter is deprecated, please move to passing\n the redirect_uri in via the constructor.\n state: string, Opaque state string which is passed through the\n OAuth2 flow and returned to the client as a query parameter\n in the callback.\n \n Returns:\n A URI as a string to redirect the user to begin the authorization\n flow.\n \"\"\"\n if redirect_uri is not None:\n logger.warning('The redirect_uri parameter for OAuth2WebServerFlow.step1_get_authorize_url is deprecated. Please move to passing the redirect_uri in via the constructor.')\n self.redirect_uri = redirect_uri\n if self.redirect_uri is None:\n raise ValueError('The value of redirect_uri must not be None.')\n query_params = {'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'scope': self.scope}\n if state is not None:\n query_params['state'] = state\n if self.login_hint is not None:\n query_params['login_hint'] = self.login_hint\n if self._pkce:\n if not self.code_verifier:\n self.code_verifier = _pkce.code_verifier()\n challenge = _pkce.code_challenge(self.code_verifier)\n query_params['code_challenge'] = challenge\n query_params['code_challenge_method'] = 'S256'\n query_params.update(self.params)\n return _helpers.update_query_params(self.auth_uri, query_params)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(1)\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_device_and_user_codes(self, http=None): ...\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_construct_authorize_url", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001246.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "_oauth2_web_server_flow_params", "tests": "import unittest\n\nclass Test_oauth2_web_server_flow_params(unittest.TestCase):\n def test__oauth2_web_server_flow_params(self):\n params = client._oauth2_web_server_flow_params({})\n self.assertEqual(params['access_type'], 'offline')\n self.assertEqual(params['response_type'], 'code')\n params = client._oauth2_web_server_flow_params({'approval_prompt': 'force'})\n self.assertEqual(params['prompt'], 'consent')\n self.assertNotIn('approval_prompt', params)\n params = client._oauth2_web_server_flow_params({'approval_prompt': 'other'})\n self.assertEqual(params['approval_prompt'], 'other')\n", "method_code": "def _oauth2_web_server_flow_params(kwargs):\n \"\"\"Configures redirect URI parameters for OAuth2WebServerFlow.\"\"\"\n params = {'access_type': 'offline', 'response_type': 'code'}\n params.update(kwargs)\n approval_prompt = params.get('approval_prompt')\n if approval_prompt is not None:\n logger.warning('The approval_prompt parameter for OAuth2WebServerFlow is deprecated. Please use the prompt parameter instead.')\n if approval_prompt == 'force':\n logger.warning('approval_prompt=\"force\" has been adjusted to prompt=\"consent\"')\n params['prompt'] = 'consent'\n del params['approval_prompt']\n return params", "context": "def _oauth2_web_server_flow_params(kwargs): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__oauth2_web_server_flow_params", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001247.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2WebServerFlow", "focal_method": "step1_get_authorize_url", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2WebServerFlow_step1_get_authorize_url(unittest.TestCase):\n @mock.patch('oauth2client.client.logger')\n def test_step1_get_authorize_url_redirect_override(self, logger):\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri=client.OOB_CALLBACK_URN)\n alt_redirect = 'foo:bar'\n self.assertEqual(flow.redirect_uri, client.OOB_CALLBACK_URN)\n result = flow.step1_get_authorize_url(redirect_uri=alt_redirect)\n self.assertEqual(flow.redirect_uri, alt_redirect)\n query_params = {'client_id': flow.client_id, 'redirect_uri': alt_redirect, 'scope': flow.scope, 'access_type': 'offline', 'response_type': 'code'}\n expected = _helpers.update_query_params(flow.auth_uri, query_params)\n assertUrisEqual(self, expected, result)\n self.assertEqual(logger.warning.call_count, 1)\n\n @mock.patch('oauth2client.client._pkce.code_challenge')\n @mock.patch('oauth2client.client._pkce.code_verifier')\n def test_step1_get_authorize_url_pkce(self, fake_verifier, fake_challenge):\n fake_verifier.return_value = self.good_verifier\n fake_challenge.return_value = self.good_challenger\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri='http://example.com', pkce=True)\n auth_url = urllib.parse.urlparse(flow.step1_get_authorize_url())\n self.assertEqual(flow.code_verifier, self.good_verifier)\n results = dict(urllib.parse.parse_qsl(auth_url.query))\n self.assertEqual(results['code_challenge'], self.good_challenger.decode())\n self.assertEqual(results['code_challenge_method'], 'S256')\n fake_verifier.assert_called()\n fake_challenge.assert_called_with(self.good_verifier)\n\n @mock.patch('oauth2client.client._pkce.code_challenge')\n @mock.patch('oauth2client.client._pkce.code_verifier')\n def test_step1_get_authorize_url_pkce_invalid_verifier(self, fake_verifier, fake_challenge):\n fake_verifier.return_value = self.good_verifier\n fake_challenge.return_value = self.good_challenger\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri='http://example.com', pkce=True, code_verifier=self.bad_verifier)\n auth_url = urllib.parse.urlparse(flow.step1_get_authorize_url())\n self.assertEqual(flow.code_verifier, self.bad_verifier)\n results = dict(urllib.parse.parse_qsl(auth_url.query))\n self.assertEqual(results['code_challenge'], self.good_challenger.decode())\n self.assertEqual(results['code_challenge_method'], 'S256')\n fake_verifier.assert_not_called()\n fake_challenge.assert_called_with(self.bad_verifier)\n\n def test_step1_get_authorize_url_without_redirect(self):\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri=None)\n with self.assertRaises(ValueError):\n flow.step1_get_authorize_url(redirect_uri=None)\n\n def test_step1_get_authorize_url_without_login_hint(self):\n login_hint = 'There are wascally wabbits nearby'\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri=client.OOB_CALLBACK_URN, login_hint=login_hint)\n result = flow.step1_get_authorize_url()\n query_params = {'client_id': flow.client_id, 'login_hint': login_hint, 'redirect_uri': client.OOB_CALLBACK_URN, 'scope': flow.scope, 'access_type': 'offline', 'response_type': 'code'}\n expected = _helpers.update_query_params(flow.auth_uri, query_params)\n assertUrisEqual(self, expected, result)\n", "method_code": " def step1_get_authorize_url(self, redirect_uri=None, state=None):\n \"\"\"Returns a URI to redirect to the provider.\n \n Args:\n redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'\n for a non-web-based application, or a URI that\n handles the callback from the authorization server.\n This parameter is deprecated, please move to passing\n the redirect_uri in via the constructor.\n state: string, Opaque state string which is passed through the\n OAuth2 flow and returned to the client as a query parameter\n in the callback.\n \n Returns:\n A URI as a string to redirect the user to begin the authorization\n flow.\n \"\"\"\n if redirect_uri is not None:\n logger.warning('The redirect_uri parameter for OAuth2WebServerFlow.step1_get_authorize_url is deprecated. Please move to passing the redirect_uri in via the constructor.')\n self.redirect_uri = redirect_uri\n if self.redirect_uri is None:\n raise ValueError('The value of redirect_uri must not be None.')\n query_params = {'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'scope': self.scope}\n if state is not None:\n query_params['state'] = state\n if self.login_hint is not None:\n query_params['login_hint'] = self.login_hint\n if self._pkce:\n if not self.code_verifier:\n self.code_verifier = _pkce.code_verifier()\n challenge = _pkce.code_challenge(self.code_verifier)\n query_params['code_challenge'] = challenge\n query_params['code_challenge_method'] = 'S256'\n query_params.update(self.params)\n return _helpers.update_query_params(self.auth_uri, query_params)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(1)\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_device_and_user_codes(self, http=None): ...\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001248.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2WebServerFlow", "focal_method": "step1_get_device_and_user_codes", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2WebServerFlow_step1_get_device_and_user_codes(unittest.TestCase):\n def test_step1_get_device_and_user_codes_wo_device_uri(self):\n flow = client.OAuth2WebServerFlow('CID', scope='foo', device_uri=None)\n with self.assertRaises(ValueError):\n flow.step1_get_device_and_user_codes()\n", "method_code": " def step1_get_device_and_user_codes(self, http=None):\n \"\"\"Returns a user code and the verification URL where to enter it\n \n Returns:\n A user code as a string for the user to authorize the application\n An URL as a string where the user has to enter the code\n \"\"\"\n if self.device_uri is None:\n raise ValueError('The value of device_uri must not be None.')\n body = urllib.parse.urlencode({'client_id': self.client_id, 'scope': self.scope})\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n if self.user_agent is not None:\n headers['user-agent'] = self.user_agent\n if http is None:\n http = transport.get_http_object()\n resp, content = transport.request(http, self.device_uri, method='POST', body=body, headers=headers)\n content = _helpers._from_bytes(content)\n if resp.status == http_client.OK:\n try:\n flow_info = json.loads(content)\n except ValueError as exc:\n raise OAuth2DeviceCodeError('Could not parse server response as JSON: \"{0}\", error: \"{1}\"'.format(content, exc))\n return DeviceFlowInfo.FromResponse(flow_info)\n else:\n error_msg = 'Invalid response {0}.'.format(resp.status)\n try:\n error_dict = json.loads(content)\n if 'error' in error_dict:\n error_msg += ' Error: {0}'.format(error_dict['error'])\n except ValueError:\n pass\n raise OAuth2DeviceCodeError(error_msg)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(1)\n def step1_get_device_and_user_codes(self, http=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_step1_get_device_and_user_codes_wo_device_uri", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001249.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.OAuth2WebServerFlow", "focal_method": "step2_exchange", "tests": "import unittest\n\nclass Test_oauth2client_client_OAuth2WebServerFlow_step2_exchange(unittest.TestCase):\n def test_step2_exchange_no_input(self):\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo')\n with self.assertRaises(ValueError):\n flow.step2_exchange()\n\n def test_exchange_with_pkce(self):\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, b'access_token=SlAV32hkKG')])\n flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', redirect_uri='http://example.com', pkce=True, code_verifier=self.good_verifier)\n flow.step2_exchange(code='some random code', http=http)\n self.assertEqual(len(http.requests), 1)\n test_request = http.requests[0]\n self.assertIn('code_verifier={0}'.format(self.good_verifier.decode()), test_request['body'])\n", "method_code": " def step2_exchange(self, code=None, http=None, device_flow_info=None):\n \"\"\"Exchanges a code for OAuth2Credentials.\n \n Args:\n code: string, a dict-like object, or None. For a non-device\n flow, this is either the response code as a string, or a\n dictionary of query parameters to the redirect_uri. For a\n device flow, this should be None.\n http: httplib2.Http, optional http instance to use when fetching\n credentials.\n device_flow_info: DeviceFlowInfo, return value from step1 in the\n case of a device flow.\n \n Returns:\n An OAuth2Credentials object that can be used to authorize requests.\n \n Raises:\n FlowExchangeError: if a problem occurred exchanging the code for a\n refresh_token.\n ValueError: if code and device_flow_info are both provided or both\n missing.\n \"\"\"\n if code is None and device_flow_info is None:\n raise ValueError('No code or device_flow_info provided.')\n if code is not None and device_flow_info is not None:\n raise ValueError('Cannot provide both code and device_flow_info.')\n if code is None:\n code = device_flow_info.device_code\n elif not isinstance(code, (six.string_types, six.binary_type)):\n if 'code' not in code:\n raise FlowExchangeError(code.get('error', 'No code was supplied in the query parameters.'))\n code = code['code']\n post_data = {'client_id': self.client_id, 'code': code, 'scope': self.scope}\n if self.client_secret is not None:\n post_data['client_secret'] = self.client_secret\n if self._pkce:\n post_data['code_verifier'] = self.code_verifier\n if device_flow_info is not None:\n post_data['grant_type'] = 'http://oauth.net/grant_type/device/1.0'\n else:\n post_data['grant_type'] = 'authorization_code'\n post_data['redirect_uri'] = self.redirect_uri\n body = urllib.parse.urlencode(post_data)\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n if self.authorization_header is not None:\n headers['Authorization'] = self.authorization_header\n if self.user_agent is not None:\n headers['user-agent'] = self.user_agent\n if http is None:\n http = transport.get_http_object()\n resp, content = transport.request(http, self.token_uri, method='POST', body=body, headers=headers)\n d = _parse_exchange_token_response(content)\n if resp.status == http_client.OK and 'access_token' in d:\n access_token = d['access_token']\n refresh_token = d.get('refresh_token', None)\n if not refresh_token:\n logger.info(\"Received token response with no refresh_token. Consider reauthenticating with prompt='consent'.\")\n token_expiry = None\n if 'expires_in' in d:\n delta = datetime.timedelta(seconds=int(d['expires_in']))\n token_expiry = delta + _UTCNOW()\n extracted_id_token = None\n if 'id_token' in d:\n extracted_id_token = _extract_id_token(d['id_token'])\n logger.info('Successfully retrieved access token')\n return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=extracted_id_token, token_response=d, scopes=self.scope, token_info_uri=self.token_info_uri)\n else:\n logger.info('Failed to retrieve access token: %s', content)\n if 'error' in d:\n error_msg = str(d['error']) + str(d.get('error_description', ''))\n else:\n error_msg = 'Invalid response: {0}.'.format(str(resp.status))\n raise FlowExchangeError(error_msg)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(2)\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def step1_get_device_and_user_codes(self, http=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_step2_exchange_no_input", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001250.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "step2_exchange", "tests": "import unittest\n\nclass Test_step2_exchange(unittest.TestCase):\n def test_exchange_failure(self):\n http = http_mock.HttpMock(headers={'status': http_client.BAD_REQUEST}, data=b'{\"error\":\"invalid_request\"}')\n with self.assertRaises(client.FlowExchangeError):\n self.flow.step2_exchange(code='some random code', http=http)\n\n def test_exchange_dictlike(self):\n\n class FakeDict(object):\n\n def __init__(self, d):\n self.d = d\n\n def __getitem__(self, name):\n return self.d[name]\n\n def __contains__(self, name):\n return name in self.d\n code = 'some random code'\n not_a_dict = FakeDict({'code': code})\n payload = b'{ \"access_token\":\"SlAV32hkKG\", \"expires_in\":3600, \"refresh_token\":\"8xLOxBtZp8\"}'\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, payload)])\n credentials = self.flow.step2_exchange(code=not_a_dict, http=http)\n self.assertEqual('SlAV32hkKG', credentials.access_token)\n self.assertNotEqual(None, credentials.token_expiry)\n self.assertEqual('8xLOxBtZp8', credentials.refresh_token)\n self.assertEqual('dummy_revoke_uri', credentials.revoke_uri)\n self.assertEqual(set(['foo']), credentials.scopes)\n self.assertEqual(len(http.requests), 1)\n request_code = urllib.parse.parse_qs(http.requests[0]['body'])['code'][0]\n self.assertEqual(code, request_code)\n\n def test_exchange_id_token(self):\n body = {'foo': 'bar'}\n body_json = json.dumps(body).encode('ascii')\n payload = base64.urlsafe_b64encode(body_json).strip(b'=')\n jwt = base64.urlsafe_b64encode(b'stuff') + b'.' + payload + b'.' + base64.urlsafe_b64encode(b'signature')\n payload = b'{ \"access_token\":\"SlAV32hkKG\", \"refresh_token\":\"8xLOxBtZp8\", \"id_token\": \"' + jwt + b'\"}'\n http = http_mock.HttpMock(data=payload)\n credentials = self.flow.step2_exchange(code='some random code', http=http)\n self.assertEqual(credentials.id_token, body)\n", "method_code": " def step2_exchange(self, code=None, http=None, device_flow_info=None):\n \"\"\"Exchanges a code for OAuth2Credentials.\n \n Args:\n code: string, a dict-like object, or None. For a non-device\n flow, this is either the response code as a string, or a\n dictionary of query parameters to the redirect_uri. For a\n device flow, this should be None.\n http: httplib2.Http, optional http instance to use when fetching\n credentials.\n device_flow_info: DeviceFlowInfo, return value from step1 in the\n case of a device flow.\n \n Returns:\n An OAuth2Credentials object that can be used to authorize requests.\n \n Raises:\n FlowExchangeError: if a problem occurred exchanging the code for a\n refresh_token.\n ValueError: if code and device_flow_info are both provided or both\n missing.\n \"\"\"\n if code is None and device_flow_info is None:\n raise ValueError('No code or device_flow_info provided.')\n if code is not None and device_flow_info is not None:\n raise ValueError('Cannot provide both code and device_flow_info.')\n if code is None:\n code = device_flow_info.device_code\n elif not isinstance(code, (six.string_types, six.binary_type)):\n if 'code' not in code:\n raise FlowExchangeError(code.get('error', 'No code was supplied in the query parameters.'))\n code = code['code']\n post_data = {'client_id': self.client_id, 'code': code, 'scope': self.scope}\n if self.client_secret is not None:\n post_data['client_secret'] = self.client_secret\n if self._pkce:\n post_data['code_verifier'] = self.code_verifier\n if device_flow_info is not None:\n post_data['grant_type'] = 'http://oauth.net/grant_type/device/1.0'\n else:\n post_data['grant_type'] = 'authorization_code'\n post_data['redirect_uri'] = self.redirect_uri\n body = urllib.parse.urlencode(post_data)\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n if self.authorization_header is not None:\n headers['Authorization'] = self.authorization_header\n if self.user_agent is not None:\n headers['user-agent'] = self.user_agent\n if http is None:\n http = transport.get_http_object()\n resp, content = transport.request(http, self.token_uri, method='POST', body=body, headers=headers)\n d = _parse_exchange_token_response(content)\n if resp.status == http_client.OK and 'access_token' in d:\n access_token = d['access_token']\n refresh_token = d.get('refresh_token', None)\n if not refresh_token:\n logger.info(\"Received token response with no refresh_token. Consider reauthenticating with prompt='consent'.\")\n token_expiry = None\n if 'expires_in' in d:\n delta = datetime.timedelta(seconds=int(d['expires_in']))\n token_expiry = delta + _UTCNOW()\n extracted_id_token = None\n if 'id_token' in d:\n extracted_id_token = _extract_id_token(d['id_token'])\n logger.info('Successfully retrieved access token')\n return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=extracted_id_token, token_response=d, scopes=self.scope, token_info_uri=self.token_info_uri)\n else:\n logger.info('Failed to retrieve access token: %s', content)\n if 'error' in d:\n error_msg = str(d['error']) + str(d.get('error_description', ''))\n else:\n error_msg = 'Invalid response: {0}.'.format(str(resp.status))\n raise FlowExchangeError(error_msg)\n ", "context": "class OAuth2WebServerFlow(Flow):\n @_helpers.positional(2)\n def step2_exchange(self, code=None, http=None, device_flow_info=None): ...\n def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=None, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, pkce=False, code_verifier=None, **kwargs): ...\n def step1_get_authorize_url(self, redirect_uri=None, state=None): ...\n def step1_get_device_and_user_codes(self, http=None): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = _helpers.scopes_to_string(scope)\n self.redirect_uri = redirect_uri\n self.login_hint = login_hint\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.revoke_uri = revoke_uri\n self.device_uri = device_uri\n self.token_info_uri = token_info_uri\n self.authorization_header = authorization_header\n self._pkce = pkce\n self.code_verifier = code_verifier\n self.params = _oauth2_web_server_flow_params(kwargs)\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_exchange_failure", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001251.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": null, "focal_method": "flow_from_clientsecrets", "tests": "import unittest\n\nclass Test_flow_from_clientsecrets(unittest.TestCase):\n def test_flow_from_clientsecrets_cached(self):\n cache_mock = http_mock.CacheMock()\n load_and_cache('client_secrets.json', 'some_secrets', cache_mock)\n flow = client.flow_from_clientsecrets('some_secrets', '', redirect_uri='oob', cache=cache_mock)\n self.assertEqual('foo_client_secret', flow.client_secret)\n\n @mock.patch('oauth2client.clientsecrets.loadfile', side_effect=clientsecrets.InvalidClientSecretsError)\n def test_flow_from_clientsecrets_invalid(self, loadfile_mock):\n filename = object()\n cache = object()\n with self.assertRaises(clientsecrets.InvalidClientSecretsError):\n client.flow_from_clientsecrets(filename, None, cache=cache, message=None)\n loadfile_mock.assert_called_once_with(filename, cache=cache)\n\n @mock.patch('oauth2client.clientsecrets.loadfile', side_effect=clientsecrets.InvalidClientSecretsError)\n @mock.patch('sys.exit')\n def test_flow_from_clientsecrets_invalid_w_msg(self, sys_exit, loadfile_mock):\n filename = object()\n cache = object()\n message = 'hi mom'\n client.flow_from_clientsecrets(filename, None, cache=cache, message=message)\n sys_exit.assert_called_once_with(message)\n loadfile_mock.assert_called_once_with(filename, cache=cache)\n\n @mock.patch('oauth2client.clientsecrets.loadfile', side_effect=clientsecrets.InvalidClientSecretsError('foobar'))\n @mock.patch('sys.exit')\n def test_flow_from_clientsecrets_invalid_w_msg_and_text(self, sys_exit, loadfile_mock):\n filename = object()\n cache = object()\n message = 'hi mom'\n expected = 'The client secrets were invalid: \\n{0}\\n{1}'.format('foobar', 'hi mom')\n client.flow_from_clientsecrets(filename, None, cache=cache, message=message)\n sys_exit.assert_called_once_with(expected)\n loadfile_mock.assert_called_once_with(filename, cache=cache)\n\n @mock.patch('oauth2client.clientsecrets.loadfile')\n def test_flow_from_clientsecrets_unknown_flow(self, loadfile_mock):\n client_type = 'UNKNOWN'\n loadfile_mock.return_value = (client_type, None)\n filename = object()\n cache = object()\n err_msg = 'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type)\n with self.assertRaisesRegexp(client.UnknownClientSecretsFlowError, err_msg):\n client.flow_from_clientsecrets(filename, None, cache=cache)\n loadfile_mock.assert_called_once_with(filename, cache=cache)\n", "method_code": "def flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None):\n \"\"\"Create a Flow from a clientsecrets file.\n\n Will create the right kind of Flow based on the contents of the\n clientsecrets file or will raise InvalidClientSecretsError for unknown\n types of Flows.\n\n Args:\n filename: string, File name of client secrets.\n scope: string or iterable of strings, scope(s) to request.\n redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for\n a non-web-based application, or a URI that handles the\n callback from the authorization server.\n message: string, A friendly string to display to the user if the\n clientsecrets file is missing or invalid. If message is\n provided then sys.exit will be called in the case of an error.\n If message in not provided then\n clientsecrets.InvalidClientSecretsError will be raised.\n cache: An optional cache service client that implements get() and set()\n methods. See clientsecrets.loadfile() for details.\n login_hint: string, Either an email address or domain. Passing this\n hint will either pre-fill the email box on the sign-in form\n or select the proper multi-login session, thereby\n simplifying the login flow.\n device_uri: string, URI for device authorization endpoint. For\n convenience defaults to Google's endpoints but any\n OAuth 2.0 provider can be used.\n\n Returns:\n A Flow object.\n\n Raises:\n UnknownClientSecretsFlowError: if the file describes an unknown kind of\n Flow.\n clientsecrets.InvalidClientSecretsError: if the clientsecrets file is\n invalid.\n \"\"\"\n try:\n client_type, client_info = clientsecrets.loadfile(filename, cache=cache)\n if client_type in (clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED):\n constructor_kwargs = {'redirect_uri': redirect_uri, 'auth_uri': client_info['auth_uri'], 'token_uri': client_info['token_uri'], 'login_hint': login_hint}\n revoke_uri = client_info.get('revoke_uri')\n optional = ('revoke_uri', 'device_uri', 'pkce', 'code_verifier')\n for param in optional:\n if locals()[param] is not None:\n constructor_kwargs[param] = locals()[param]\n return OAuth2WebServerFlow(client_info['client_id'], client_info['client_secret'], scope, **constructor_kwargs)\n except clientsecrets.InvalidClientSecretsError as e:\n if message is not None:\n if e.args:\n message = 'The client secrets were invalid: \\n{0}\\n{1}'.format(e, message)\n sys.exit(message)\n else:\n raise\n else:\n raise UnknownClientSecretsFlowError('This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type))", "context": "@_helpers.positional(2)\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\ndef _parse_expiry(expiry): ...\ndef _detect_gce_environment(): ...\ndef _in_gae_environment(): ...\ndef _in_gce_environment(): ...\ndef _save_private_file(filename, json_contents): ...\ndef save_to_well_known_file(credentials, well_known_file=None): ...\ndef _get_environment_variable_file(): ...\ndef _get_well_known_file(): ...\ndef _get_application_default_credential_from_file(filename): ...\ndef _raise_exception_for_missing_fields(missing_fields): ...\ndef _raise_exception_for_reading_json(credential_file, extra_help, error): ...\ndef _get_application_default_credential_GAE(): ...\ndef _get_application_default_credential_GCE(): ...\ndef _require_crypto_or_die(): ...\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, pkce=False, code_verifier=None): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None): ...\ndef _oauth2_web_server_flow_params(kwargs): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_flow_from_clientsecrets_cached", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001252.py"} {"focal_file": "vendor/oauth2client/client.py", "focal_class": "oauth2client.client.DeviceFlowInfo", "focal_method": "FromResponse", "tests": "import unittest\n\nclass Test_oauth2client_client_DeviceFlowInfo_FromResponse(unittest.TestCase):\n def test_FromResponse(self):\n response = {'device_code': self.DEVICE_CODE, 'user_code': self.USER_CODE, 'verification_url': self.VER_URL}\n result = client.DeviceFlowInfo.FromResponse(response)\n expected_result = client.DeviceFlowInfo(self.DEVICE_CODE, self.USER_CODE, None, self.VER_URL, None)\n self.assertEqual(result, expected_result)\n", "method_code": " def FromResponse(cls, response):\n \"\"\"Create a DeviceFlowInfo from a server response.\n \n The response should be a dict containing entries as described here:\n \n http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1\n \"\"\"\n kwargs = {'device_code': response['device_code'], 'user_code': response['user_code']}\n verification_url = response.get('verification_url', response.get('verification_uri'))\n if verification_url is None:\n raise OAuth2DeviceCodeError('No verification_url provided in server response')\n kwargs['verification_url'] = verification_url\n kwargs.update({'interval': response.get('interval'), 'user_code_expiry': None})\n if 'expires_in' in response:\n kwargs['user_code_expiry'] = _UTCNOW() + datetime.timedelta(seconds=int(response['expires_in']))\n return cls(**kwargs)\n ", "context": "class DeviceFlowInfo(collections.namedtuple('DeviceFlowInfo', ('device_code', 'user_code', 'interval', 'verification_url', 'user_code_expiry'))):\n @classmethod\n def FromResponse(cls, response): ...", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_FromResponse", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001253.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": "oauth2client.service_account.ServiceAccountCredentials", "focal_method": "_to_json", "tests": "import unittest\n\nclass Test_oauth2client_service_account_ServiceAccountCredentials_to_json(unittest.TestCase):\n def test__to_json_override(self):\n signer = object()\n creds = service_account.ServiceAccountCredentials('name@email.com', signer)\n self.assertEqual(creds._signer, signer)\n to_serialize = {'unrelated': 'data'}\n serialized_str = creds._to_json([], to_serialize.copy())\n serialized_data = json.loads(serialized_str)\n expected_serialized = {'_class': 'ServiceAccountCredentials', '_module': 'oauth2client.service_account', 'token_expiry': None}\n expected_serialized.update(to_serialize)\n self.assertEqual(serialized_data, expected_serialized)\n", "method_code": " def _to_json(self, strip, to_serialize=None):\n \"\"\"Utility function that creates JSON repr. of a credentials object.\n \n Over-ride is needed since PKCS#12 keys will not in general be JSON\n serializable.\n \n Args:\n strip: array, An array of names of members to exclude from the\n JSON.\n to_serialize: dict, (Optional) The properties for this object\n that will be serialized. This allows callers to\n modify before serializing.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n if to_serialize is None:\n to_serialize = copy.copy(self.__dict__)\n pkcs12_val = to_serialize.get(_PKCS12_KEY)\n if pkcs12_val is not None:\n to_serialize[_PKCS12_KEY] = base64.b64encode(pkcs12_val)\n return super(ServiceAccountCredentials, self)._to_json(strip, to_serialize=to_serialize)\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def _to_json(self, strip, to_serialize=None): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__to_json_override", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001254.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": null, "focal_method": "sign_blob", "tests": "import unittest\n\nclass Test_sign_blob(unittest.TestCase):\n def test_sign_blob(self):\n private_key_id, signature = self.credentials.sign_blob('Google')\n self.assertEqual(self.private_key_id, private_key_id)\n pub_key = rsa.PublicKey.load_pkcs1_openssl_pem(datafile('publickey_openssl.pem'))\n self.assertTrue(rsa.pkcs1.verify(b'Google', signature, pub_key))\n with self.assertRaises(rsa.pkcs1.VerificationError):\n rsa.pkcs1.verify(b'Orest', signature, pub_key)\n with self.assertRaises(rsa.pkcs1.VerificationError):\n rsa.pkcs1.verify(b'Google', b'bad signature', pub_key)\n", "method_code": " def sign_blob(self, blob):\n \"\"\"Cryptographically sign a blob (of bytes).\n \n Implements abstract method\n :meth:`oauth2client.client.AssertionCredentials.sign_blob`.\n \n Args:\n blob: bytes, Message to be signed.\n \n Returns:\n tuple, A pair of the private key ID used to sign the blob and\n the signed contents.\n \"\"\"\n return (self._private_key_id, self._signer.sign(blob))\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def sign_blob(self, blob): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_sign_blob", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001255.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": null, "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required_without_scopes(self):\n self.assertTrue(self.credentials.create_scoped_required())\n\n def test_create_scoped_required(self):\n self.assertTrue(self.jwt.create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n return not self._scopes\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def create_scoped_required(self): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_scoped_required_without_scopes", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001256.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": "oauth2client.service_account.ServiceAccountCredentials", "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_oauth2client_service_account_ServiceAccountCredentials_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required_with_scopes(self):\n signer = object()\n self.credentials = service_account.ServiceAccountCredentials(self.service_account_email, signer, scopes=self.scopes, private_key_id=self.private_key_id, client_id=self.client_id)\n self.assertFalse(self.credentials.create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n return not self._scopes\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def create_scoped_required(self): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_scoped_required_with_scopes", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001257.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": null, "focal_method": "create_scoped", "tests": "import unittest\n\nclass Test_create_scoped(unittest.TestCase):\n def test_create_scoped(self):\n self.jwt._private_key_pkcs12 = ''\n self.jwt._private_key_password = ''\n new_credentials = self.jwt.create_scoped('dummy_scope')\n self.assertNotEqual(self.jwt, new_credentials)\n self.assertIsInstance(new_credentials, service_account.ServiceAccountCredentials)\n self.assertEqual('dummy_scope', new_credentials._scopes)\n", "method_code": " def create_scoped(self, scopes):\n result = self.__class__(self._service_account_email, self._signer, scopes=scopes, private_key_id=self._private_key_id, client_id=self.client_id, user_agent=self._user_agent, **self._kwargs)\n result.token_uri = self.token_uri\n result.revoke_uri = self.revoke_uri\n result._private_key_pkcs8_pem = self._private_key_pkcs8_pem\n result._private_key_pkcs12 = self._private_key_pkcs12\n result._private_key_password = self._private_key_password\n return result\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def create_scoped(self, scopes): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped_required(self): ...\n def create_with_claims(self, claims): ...\n def create_delegated(self, sub): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_scoped", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001258.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": "oauth2client.service_account.ServiceAccountCredentials", "focal_method": "create_delegated", "tests": "import unittest\n\nclass Test_oauth2client_service_account_ServiceAccountCredentials_create_delegated(unittest.TestCase):\n def test_create_delegated(self):\n signer = object()\n sub = 'foo@email.com'\n creds = service_account.ServiceAccountCredentials('name@email.com', signer)\n self.assertNotIn('sub', creds._kwargs)\n delegated_creds = creds.create_delegated(sub)\n self.assertEqual(delegated_creds._kwargs['sub'], sub)\n self.assertNotIn('sub', creds._kwargs)\n\n def test_create_delegated_existing_sub(self):\n signer = object()\n sub1 = 'existing@email.com'\n sub2 = 'new@email.com'\n creds = service_account.ServiceAccountCredentials('name@email.com', signer, sub=sub1)\n self.assertEqual(creds._kwargs['sub'], sub1)\n delegated_creds = creds.create_delegated(sub2)\n self.assertEqual(delegated_creds._kwargs['sub'], sub2)\n self.assertEqual(creds._kwargs['sub'], sub1)\n", "method_code": " def create_delegated(self, sub):\n \"\"\"Create credentials that act as domain-wide delegation of authority.\n \n Use the ``sub`` parameter as the subject to delegate on behalf of\n that user.\n \n For example::\n \n >>> account_sub = 'foo@email.com'\n >>> delegate_creds = creds.create_delegated(account_sub)\n \n Args:\n sub: string, An email address that this service account will\n act on behalf of (via domain-wide delegation).\n \n Returns:\n ServiceAccountCredentials, a copy of the current service account\n updated to act on behalf of ``sub``.\n \"\"\"\n return self.create_with_claims({'sub': sub})\n ", "context": "class ServiceAccountCredentials(client.AssertionCredentials):\n def create_delegated(self, sub): ...\n def __init__(self, service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): ...\n def _to_json(self, strip, to_serialize=None): ...\n def _from_parsed_json_keyfile(cls, keyfile_dict, scopes, token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_name(cls, filename, scopes='', token_uri=None, revoke_uri=None): ...\n def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None): ...\n def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _generate_assertion(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n def serialization_data(self): ...\n def from_json(cls, json_data): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def create_with_claims(self, claims): ...\n\n self._service_account_email = service_account_email\n self._signer = signer\n self._scopes = _helpers.scopes_to_string(scopes)\n self._private_key_id = private_key_id\n self.client_id = client_id\n self._user_agent = user_agent\n self._kwargs = kwargs\n\n MAX_TOKEN_LIFETIME_SECS = 3600\n NON_SERIALIZED_MEMBERS = frozenset(['_signer']) | client.AssertionCredentials.NON_SERIALIZED_MEMBERS\n _private_key_pkcs8_pem = None\n _private_key_pkcs12 = None\n _private_key_password = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_delegated", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001259.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": "oauth2client.service_account.ServiceAccountCredentials", "focal_method": "get_access_token", "tests": "import unittest\n\nclass Test_oauth2client_service_account_ServiceAccountCredentials_get_access_token(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n def test_access_token(self, utcnow):\n seconds = 11\n NOW = datetime.datetime(1992, 12, 31, second=seconds)\n utcnow.return_value = NOW\n signer = mock.Mock()\n signed_value = b'signed-content'\n signer.sign = mock.Mock(name='sign', return_value=signed_value)\n credentials = service_account.ServiceAccountCredentials(self.service_account_email, signer, private_key_id=self.private_key_id, client_id=self.client_id)\n lifetime = 2\n EXPIRY_TIME = datetime.datetime(1992, 12, 31, second=seconds + lifetime)\n token1 = u'first_token'\n token_response_first = {'access_token': token1, 'expires_in': lifetime}\n token2 = u'second_token'\n token_response_second = {'access_token': token2, 'expires_in': lifetime}\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, json.dumps(token_response_first).encode('utf-8')), ({'status': http_client.OK}, json.dumps(token_response_second).encode('utf-8'))])\n self.assertIsNone(credentials.access_token)\n self.assertFalse(credentials.access_token_expired)\n self.assertIsNone(credentials.token_expiry)\n token = credentials.get_access_token(http=http)\n self.assertEqual(credentials.token_expiry, EXPIRY_TIME)\n self.assertEqual(token1, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertEqual(token_response_first, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * 2\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(len(signer.sign.mock_calls), 1)\n self.assertEqual(credentials.access_token, token1)\n self.assertFalse(credentials.access_token_expired)\n token = credentials.get_access_token(http=http)\n self.assertEqual(token1, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertEqual(token_response_first, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * (2 + 3)\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(len(signer.sign.mock_calls), 1 + 0)\n self.assertEqual(credentials.access_token, token1)\n credentials.token_expiry = NOW\n self.assertTrue(credentials.access_token_expired)\n token = credentials.get_access_token(http=http)\n self.assertEqual(token2, token.access_token)\n self.assertEqual(lifetime, token.expires_in)\n self.assertFalse(credentials.access_token_expired)\n self.assertEqual(token_response_second, credentials.token_response)\n expected_utcnow_calls = [mock.call()] * (2 + 3 + 5)\n self.assertEqual(expected_utcnow_calls, utcnow.mock_calls)\n self.assertEqual(len(signer.sign.mock_calls), 1 + 0 + 1)\n self.assertEqual(credentials.access_token, token2)\n", "method_code": " def get_access_token(self, http=None, additional_claims=None):\n \"\"\"Create a signed jwt.\n \n Args:\n http: unused\n additional_claims: dict, additional claims to add to\n the payload of the JWT.\n Returns:\n An AccessTokenInfo with the signed jwt\n \"\"\"\n if additional_claims is None:\n if self.access_token is None or self.access_token_expired:\n self.refresh(None)\n return client.AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())\n else:\n token, unused_expiry = self._create_token(additional_claims)\n return client.AccessTokenInfo(access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def get_access_token(self, http=None, additional_claims=None): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def authorize(self, http): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001260.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": null, "focal_method": "get_access_token", "tests": "import unittest\n\nclass Test_get_access_token(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n @mock.patch('time.time')\n def test_get_access_token_no_claims(self, time, utcnow):\n utcnow.return_value = T1_DATE\n time.return_value = T1\n token_info = self.jwt.get_access_token()\n certs = {'key': datafile('public_cert.pem')}\n payload = crypt.verify_signed_jwt_with_certs(token_info.access_token, certs, audience=self.url)\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], self.service_account_email)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(payload['aud'], self.url)\n self.assertEqual(token_info.expires_in, T1_EXPIRY - T1)\n utcnow.return_value = T2_DATE\n token_info = self.jwt.get_access_token()\n payload = crypt.verify_signed_jwt_with_certs(token_info.access_token, {'key': datafile('public_cert.pem')}, audience=self.url)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(token_info.expires_in, T1_EXPIRY - T2)\n utcnow.return_value = T3_DATE\n time.return_value = T3\n token_info = self.jwt.get_access_token()\n payload = crypt.verify_signed_jwt_with_certs(token_info.access_token, {'key': datafile('public_cert.pem')}, audience=self.url)\n expires_in = token_info.expires_in\n self.assertEqual(payload['iat'], T3)\n self.assertEqual(payload['exp'], T3_EXPIRY)\n self.assertEqual(expires_in, T3_EXPIRY - T3)\n\n @mock.patch('oauth2client.client._UTCNOW')\n @mock.patch('time.time')\n def test_get_access_token_additional_claims(self, time, utcnow):\n utcnow.return_value = T1_DATE\n time.return_value = T1\n audience = 'https://test2.url.com'\n subject = 'dummy2@google.com'\n claims = {'aud': audience, 'sub': subject}\n token_info = self.jwt.get_access_token(additional_claims=claims)\n certs = {'key': datafile('public_cert.pem')}\n payload = crypt.verify_signed_jwt_with_certs(token_info.access_token, certs, audience=audience)\n expires_in = token_info.expires_in\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], subject)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(payload['aud'], audience)\n self.assertEqual(expires_in, T1_EXPIRY - T1)\n", "method_code": " def get_access_token(self, http=None, additional_claims=None):\n \"\"\"Create a signed jwt.\n \n Args:\n http: unused\n additional_claims: dict, additional claims to add to\n the payload of the JWT.\n Returns:\n An AccessTokenInfo with the signed jwt\n \"\"\"\n if additional_claims is None:\n if self.access_token is None or self.access_token_expired:\n self.refresh(None)\n return client.AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in())\n else:\n token, unused_expiry = self._create_token(additional_claims)\n return client.AccessTokenInfo(access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def get_access_token(self, http=None, additional_claims=None): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def authorize(self, http): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001261.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": null, "focal_method": "revoke", "tests": "import unittest\n\nclass Test_revoke(unittest.TestCase):\n def test_revoke(self):\n self.jwt.revoke(None)\n", "method_code": " def revoke(self, http):\n \"\"\"Cannot revoke JWTAccessCredentials tokens.\"\"\"\n pass\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def revoke(self, http): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def authorize(self, http): ...\n def get_access_token(self, http=None, additional_claims=None): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_revoke", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001262.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": null, "focal_method": "authorize", "tests": "import unittest\n\nclass Test_authorize(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n @mock.patch('time.time')\n def test_authorize_success(self, time, utcnow):\n utcnow.return_value = T1_DATE\n time.return_value = T1\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, b''), ({'status': http_client.OK}, b'')])\n self.jwt.authorize(http)\n transport.request(http, self.url)\n utcnow.return_value = T2_DATE\n transport.request(http, self.url)\n certs = {'key': datafile('public_cert.pem')}\n self.assertEqual(len(http.requests), 2)\n for info in http.requests:\n self.assertEqual(info['method'], 'GET')\n self.assertEqual(info['uri'], self.url)\n self.assertIsNone(info['body'])\n self.assertEqual(len(info['headers']), 1)\n bearer, token = info['headers'][b'Authorization'].split()\n self.assertEqual(bearer, b'Bearer')\n payload = crypt.verify_signed_jwt_with_certs(token, certs, audience=self.url)\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], self.service_account_email)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(payload['aud'], self.url)\n\n @mock.patch('oauth2client.client._UTCNOW')\n def test_authorize_401(self, utcnow):\n utcnow.return_value = T1_DATE\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, b''), ({'status': http_client.UNAUTHORIZED}, b''), ({'status': http_client.OK}, b'')])\n self.jwt.authorize(http)\n transport.request(http, self.url)\n token_1 = self.jwt.access_token\n utcnow.return_value = T2_DATE\n response, _ = transport.request(http, self.url)\n self.assertEquals(response.status, http_client.OK)\n token_2 = self.jwt.access_token\n self.assertNotEqual(token_1, token_2)\n certs = {'key': datafile('public_cert.pem')}\n self.assertEqual(len(http.requests), 3)\n issued_at_vals = (T1, T1, T2)\n exp_vals = (T1_EXPIRY, T1_EXPIRY, T2_EXPIRY)\n for info, issued_at, exp_val in zip(http.requests, issued_at_vals, exp_vals):\n self.assertEqual(info['uri'], self.url)\n self.assertEqual(info['method'], 'GET')\n self.assertIsNone(info['body'])\n self.assertEqual(len(info['headers']), 1)\n bearer, token = info['headers'][b'Authorization'].split()\n self.assertEqual(bearer, b'Bearer')\n with mock.patch('oauth2client.crypt._verify_time_range', return_value=True):\n payload = crypt.verify_signed_jwt_with_certs(token, certs, audience=self.url)\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], self.service_account_email)\n self.assertEqual(payload['iat'], issued_at)\n self.assertEqual(payload['exp'], exp_val)\n self.assertEqual(payload['aud'], self.url)\n", "method_code": " def authorize(self, http):\n \"\"\"Authorize an httplib2.Http instance with a JWT assertion.\n \n Unless specified, the 'aud' of the assertion will be the base\n uri of the request.\n \n Args:\n http: An instance of ``httplib2.Http`` or something that acts\n like it.\n Returns:\n A modified instance of http that was passed in.\n Example::\n h = httplib2.Http()\n h = credentials.authorize(h)\n \"\"\"\n transport.wrap_http_for_jwt_access(self, http)\n return http\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def authorize(self, http): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def get_access_token(self, http=None, additional_claims=None): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001263.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": "oauth2client.service_account._JWTAccessCredentials", "focal_method": "authorize", "tests": "import unittest\n\nclass Test_oauth2client_service_account_JWTAccessCredentials_authorize(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n @mock.patch('time.time')\n def test_authorize_no_aud(self, time, utcnow):\n utcnow.return_value = T1_DATE\n time.return_value = T1\n jwt = service_account._JWTAccessCredentials(self.service_account_email, self.signer, private_key_id=self.private_key_id, client_id=self.client_id)\n http = http_mock.HttpMockSequence([({'status': http_client.OK}, b'')])\n jwt.authorize(http)\n transport.request(http, self.url)\n self.assertIsNone(jwt.access_token)\n self.assertEqual(len(http.requests), 1)\n info = http.requests[0]\n self.assertEqual(info['method'], 'GET')\n self.assertEqual(info['uri'], self.url)\n self.assertIsNone(info['body'])\n self.assertEqual(len(info['headers']), 1)\n bearer, token = info['headers'][b'Authorization'].split()\n self.assertEqual(bearer, b'Bearer')\n certs = {'key': datafile('public_cert.pem')}\n payload = crypt.verify_signed_jwt_with_certs(token, certs, audience=self.url)\n self.assertEqual(len(payload), 5)\n self.assertEqual(payload['iss'], self.service_account_email)\n self.assertEqual(payload['sub'], self.service_account_email)\n self.assertEqual(payload['iat'], T1)\n self.assertEqual(payload['exp'], T1_EXPIRY)\n self.assertEqual(payload['aud'], self.url)\n", "method_code": " def authorize(self, http):\n \"\"\"Authorize an httplib2.Http instance with a JWT assertion.\n \n Unless specified, the 'aud' of the assertion will be the base\n uri of the request.\n \n Args:\n http: An instance of ``httplib2.Http`` or something that acts\n like it.\n Returns:\n A modified instance of http that was passed in.\n Example::\n h = httplib2.Http()\n h = credentials.authorize(h)\n \"\"\"\n transport.wrap_http_for_jwt_access(self, http)\n return http\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def authorize(self, http): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def get_access_token(self, http=None, additional_claims=None): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def refresh(self, http): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001264.py"} {"focal_file": "vendor/oauth2client/service_account.py", "focal_class": null, "focal_method": "refresh", "tests": "import unittest\n\nclass Test_refresh(unittest.TestCase):\n @mock.patch('oauth2client.client._UTCNOW')\n def test_refresh(self, utcnow):\n utcnow.return_value = T1_DATE\n token_1 = self.jwt.access_token\n utcnow.return_value = T2_DATE\n self.jwt.refresh(None)\n token_2 = self.jwt.access_token\n self.assertEquals(self.jwt.token_expiry, T2_EXPIRY_DATE)\n self.assertNotEqual(token_1, token_2)\n", "method_code": " def refresh(self, http):\n \"\"\"Refreshes the access_token.\n \n The HTTP object is unused since no request needs to be made to\n get a new token, it can just be generated locally.\n \n Args:\n http: unused HTTP object\n \"\"\"\n self._refresh(None)\n ", "context": "class _JWTAccessCredentials(ServiceAccountCredentials):\n def refresh(self, http): ...\n def __init__(self, service_account_email, signer, scopes=None, private_key_id=None, client_id=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): ...\n def authorize(self, http): ...\n def get_access_token(self, http=None, additional_claims=None): ...\n def revoke(self, http): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): ...\n def _refresh(self, http): ...\n def _create_token(self, additional_claims=None): ...\n\n _MAX_TOKEN_LIFETIME_SECS = 3600\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001265.py"} {"focal_file": "vendor/oauth2client/tools.py", "focal_class": null, "focal_method": "message_if_missing", "tests": "import unittest\n\nclass Test_message_if_missing(unittest.TestCase):\n def test_message_if_missing(self):\n self.assertIn('somefile.txt', tools.message_if_missing('somefile.txt'))\n", "method_code": "def message_if_missing(filename):\n \"\"\"Helpful message to display if the CLIENT_SECRETS file is missing.\"\"\"\n return _CLIENT_SECRETS_MESSAGE.format(file_path=filename)", "context": "def message_if_missing(filename): ...\ndef _CreateArgumentParser(): ...\ndef run_flow(flow, storage, flags=None, http=None): ...\ndef message_if_missing(filename): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_message_if_missing", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001266.py"} {"focal_file": "vendor/oauth2client/transport.py", "focal_class": "oauth2client.transport.MemoryCache", "focal_method": "delete", "tests": "import unittest\n\nclass Test_oauth2client_transport_MemoryCache_delete(unittest.TestCase):\n def test_get_set_delete(self):\n cache = transport.MemoryCache()\n self.assertIsNone(cache.get('foo'))\n self.assertIsNone(cache.delete('foo'))\n cache.set('foo', 'bar')\n self.assertEqual('bar', cache.get('foo'))\n cache.delete('foo')\n self.assertIsNone(cache.get('foo'))\n", "method_code": " def delete(self, key):\n self.cache.pop(key, None)\n ", "context": "class MemoryCache(object):\n def delete(self, key): ...\n def __init__(self): ...\n def get(self, key): ...\n def set(self, key, value): ...\n\n self.cache = {}\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_get_set_delete", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001267.py"} {"focal_file": "vendor/oauth2client/contrib/devshell.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n with self.assertRaises(NotImplementedError):\n devshell.DevshellCredentials.from_json(None)\n", "method_code": " def from_json(cls, json_data):\n raise NotImplementedError('Cannot load Developer Shell credentials from JSON.')\n ", "context": "class DevshellCredentials(client.GoogleCredentials):\n @classmethod\n def from_json(cls, json_data): ...\n def __init__(self, user_agent=None): ...\n def _refresh(self, http): ...\n def user_email(self): ...\n def project_id(self): ...\n def serialization_data(self): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_from_json", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001268.py"} {"focal_file": "vendor/oauth2client/contrib/flask_util.py", "focal_class": "oauth2client.contrib.flask_util.UserOAuth2", "focal_method": "_make_flow", "tests": "import unittest\n\nclass Test_oauth2client_contrib_flask_util_UserOAuth2_make_flow(unittest.TestCase):\n def test_create_flow(self):\n with self.app.test_request_context():\n flow = self.oauth2._make_flow()\n state = json.loads(flow.params['state'])\n self.assertIn('google_oauth2_csrf_token', flask.session)\n self.assertEqual(flask.session['google_oauth2_csrf_token'], state['csrf_token'])\n self.assertEqual(flow.client_id, self.oauth2.client_id)\n self.assertEqual(flow.client_secret, self.oauth2.client_secret)\n self.assertIn('http', flow.redirect_uri)\n self.assertIn('oauth2callback', flow.redirect_uri)\n flow = self.oauth2._make_flow(return_url='/return_url')\n state = json.loads(flow.params['state'])\n self.assertEqual(state['return_url'], '/return_url')\n flow = self.oauth2._make_flow(extra_arg='test')\n self.assertEqual(flow.params['extra_arg'], 'test')\n app = flask.Flask(__name__)\n app.config['SECRET_KEY'] = 'notasecert'\n oauth2 = flask_util.UserOAuth2(app, client_id='client_id', client_secret='secret', extra_arg='test')\n with app.test_request_context():\n flow = oauth2._make_flow()\n self.assertEqual(flow.params['extra_arg'], 'test')\n", "method_code": " def _make_flow(self, return_url=None, **kwargs):\n \"\"\"Creates a Web Server Flow\"\"\"\n csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest()\n session[_CSRF_KEY] = csrf_token\n state = json.dumps({'csrf_token': csrf_token, 'return_url': return_url})\n kw = self.flow_kwargs.copy()\n kw.update(kwargs)\n extra_scopes = kw.pop('scopes', [])\n scopes = set(self.scopes).union(set(extra_scopes))\n flow = client.OAuth2WebServerFlow(client_id=self.client_id, client_secret=self.client_secret, scope=scopes, state=state, redirect_uri=url_for('oauth2.callback', _external=True), **kw)\n flow_key = _FLOW_KEY.format(csrf_token)\n session[flow_key] = pickle.dumps(flow)\n return flow\n ", "context": "class UserOAuth2(object):\n def _make_flow(self, return_url=None, **kwargs): ...\n def __init__(self, app=None, *args, **kwargs): ...\n def init_app(self, app, scopes=None, client_secrets_file=None, client_id=None, client_secret=None, authorize_callback=None, storage=None, **kwargs): ...\n def _load_config(self, client_secrets_file, client_id, client_secret): ...\n def _load_client_secrets(self, filename): ...\n def _create_blueprint(self): ...\n def authorize_view(self): ...\n def callback_view(self): ...\n def credentials(self): ...\n def has_credentials(self): ...\n def email(self): ...\n def user_id(self): ...\n def authorize_url(self, return_url, **kwargs): ...\n def required(self, decorated_function=None, scopes=None, **decorator_kwargs): ...\n def http(self, *args, **kwargs): ...\n\n self.app = app\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_flow", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001269.py"} {"focal_file": "vendor/oauth2client/contrib/flask_util.py", "focal_class": null, "focal_method": "has_credentials", "tests": "import unittest\n\nclass Test_has_credentials(unittest.TestCase):\n def test_no_credentials(self):\n with self.app.test_request_context():\n self.assertFalse(self.oauth2.has_credentials())\n self.assertTrue(self.oauth2.credentials is None)\n self.assertTrue(self.oauth2.user_id is None)\n self.assertTrue(self.oauth2.email is None)\n with self.assertRaises(ValueError):\n self.oauth2.http()\n self.assertFalse(self.oauth2.storage.get())\n self.oauth2.storage.delete()\n\n @mock.patch('oauth2client.client._UTCNOW')\n def test_with_expired_credentials(self, utcnow):\n utcnow.return_value = datetime.datetime(1990, 5, 29)\n credentials = self._generate_credentials()\n credentials.token_expiry = datetime.datetime(1990, 5, 28)\n with self.app.test_request_context():\n self.oauth2.storage.put(credentials)\n self.assertTrue(self.oauth2.has_credentials())\n credentials.refresh_token = None\n with self.app.test_request_context():\n self.oauth2.storage.put(credentials)\n self.assertFalse(self.oauth2.has_credentials())\n", "method_code": " def has_credentials(self):\n \"\"\"Returns True if there are valid credentials for the current user.\"\"\"\n if not self.credentials:\n return False\n elif self.credentials.access_token_expired and (not self.credentials.refresh_token):\n return False\n else:\n return True\n ", "context": "class UserOAuth2(object):\n def has_credentials(self): ...\n def __init__(self, app=None, *args, **kwargs): ...\n def init_app(self, app, scopes=None, client_secrets_file=None, client_id=None, client_secret=None, authorize_callback=None, storage=None, **kwargs): ...\n def _load_config(self, client_secrets_file, client_id, client_secret): ...\n def _load_client_secrets(self, filename): ...\n def _make_flow(self, return_url=None, **kwargs): ...\n def _create_blueprint(self): ...\n def authorize_view(self): ...\n def callback_view(self): ...\n def credentials(self): ...\n def email(self): ...\n def user_id(self): ...\n def authorize_url(self, return_url, **kwargs): ...\n def required(self, decorated_function=None, scopes=None, **decorator_kwargs): ...\n def http(self, *args, **kwargs): ...\n\n self.app = app\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_no_credentials", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001270.py"} {"focal_file": "vendor/oauth2client/contrib/gce.py", "focal_class": "oauth2client.contrib.gce.AppAssertionCredentials", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_oauth2client_contrib_gce_AppAssertionCredentials_to_json(unittest.TestCase):\n def test_to_json(self):\n credentials = gce.AppAssertionCredentials()\n with self.assertRaises(NotImplementedError):\n credentials.to_json()\n", "method_code": " def to_json(self):\n raise NotImplementedError('Cannot serialize credentials for GCE service accounts.')\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def to_json(self): ...\n def __init__(self, email=None, *args, **kwargs): ...\n def from_json(cls, json_data): ...\n def retrieve_scopes(self, http): ...\n def _retrieve_info(self, http): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def sign_blob(self, blob): ...\n\n self.service_account_email = email\n self.scopes = None\n self.invalid = True\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_to_json", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001271.py"} {"focal_file": "vendor/oauth2client/contrib/gce.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n with self.assertRaises(NotImplementedError):\n gce.AppAssertionCredentials.from_json({})\n", "method_code": " def from_json(cls, json_data):\n raise NotImplementedError('Cannot serialize credentials for GCE service accounts.')\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n @classmethod\n def from_json(cls, json_data): ...\n def __init__(self, email=None, *args, **kwargs): ...\n def to_json(self): ...\n def retrieve_scopes(self, http): ...\n def _retrieve_info(self, http): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def sign_blob(self, blob): ...\n\n self.service_account_email = email\n self.scopes = None\n self.invalid = True\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_from_json", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001272.py"} {"focal_file": "vendor/oauth2client/contrib/gce.py", "focal_class": "oauth2client.contrib.gce.AppAssertionCredentials", "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_oauth2client_contrib_gce_AppAssertionCredentials_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required(self):\n credentials = gce.AppAssertionCredentials()\n self.assertFalse(credentials.create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n return False\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def create_scoped_required(self): ...\n def __init__(self, email=None, *args, **kwargs): ...\n def from_json(cls, json_data): ...\n def to_json(self): ...\n def retrieve_scopes(self, http): ...\n def _retrieve_info(self, http): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def sign_blob(self, blob): ...\n\n self.service_account_email = email\n self.scopes = None\n self.invalid = True\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_scoped_required", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001273.py"} {"focal_file": "vendor/oauth2client/contrib/gce.py", "focal_class": "oauth2client.contrib.gce.AppAssertionCredentials", "focal_method": "retrieve_scopes", "tests": "import unittest\n\nclass Test_oauth2client_contrib_gce_AppAssertionCredentials_retrieve_scopes(unittest.TestCase):\n @mock.patch('oauth2client.contrib._metadata.get_service_account_info', return_value=SERVICE_ACCOUNT_INFO)\n def test_retrieve_scopes(self, metadata):\n http_mock = object()\n credentials = gce.AppAssertionCredentials()\n self.assertTrue(credentials.invalid)\n self.assertIsNone(credentials.scopes)\n scopes = credentials.retrieve_scopes(http_mock)\n self.assertEqual(scopes, SERVICE_ACCOUNT_INFO['scopes'])\n self.assertFalse(credentials.invalid)\n credentials.retrieve_scopes(http_mock)\n metadata.assert_called_once_with(http_mock, service_account='default')\n\n @mock.patch('oauth2client.contrib._metadata.get_service_account_info', side_effect=http_client.HTTPException('No Such Email'))\n def test_retrieve_scopes_bad_email(self, metadata):\n http_mock = object()\n credentials = gce.AppAssertionCredentials(email='b@example.com')\n with self.assertRaises(http_client.HTTPException):\n credentials.retrieve_scopes(http_mock)\n metadata.assert_called_once_with(http_mock, service_account='b@example.com')\n", "method_code": " def retrieve_scopes(self, http):\n \"\"\"Retrieves the canonical list of scopes for this access token.\n \n Overrides client.Credentials.retrieve_scopes. Fetches scopes info\n from the metadata server.\n \n Args:\n http: httplib2.Http, an http object to be used to make the refresh\n request.\n \n Returns:\n A set of strings containing the canonical list of scopes.\n \"\"\"\n self._retrieve_info(http)\n return self.scopes\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def retrieve_scopes(self, http): ...\n def __init__(self, email=None, *args, **kwargs): ...\n def from_json(cls, json_data): ...\n def to_json(self): ...\n def _retrieve_info(self, http): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def sign_blob(self, blob): ...\n\n self.service_account_email = email\n self.scopes = None\n self.invalid = True\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001274.py"} {"focal_file": "vendor/oauth2client/contrib/keyring_storage.py", "focal_class": "oauth2client.contrib.keyring_storage.Storage", "focal_method": "locked_get", "tests": "import unittest\n\nclass Test_oauth2client_contrib_keyring_storage_Storage_locked_get(unittest.TestCase):\n def test_locked_get(self):\n service_name = 'my_unit_test'\n user_name = 'me'\n mock_content = (object(), 'mock_content')\n mock_return_creds = mock.Mock()\n mock_return_creds.set_store = set_store = mock.Mock(name='set_store')\n with mock.patch.object(keyring, 'get_password', return_value=mock_content, autospec=True) as get_password:\n class_name = 'oauth2client.client.Credentials'\n with mock.patch(class_name) as MockCreds:\n MockCreds.new_from_json = new_from_json = mock.Mock(name='new_from_json', return_value=mock_return_creds)\n store = keyring_storage.Storage(service_name, user_name)\n credentials = store.locked_get()\n new_from_json.assert_called_once_with(mock_content)\n get_password.assert_called_once_with(service_name, user_name)\n self.assertEqual(credentials, mock_return_creds)\n set_store.assert_called_once_with(store)\n", "method_code": " def locked_get(self):\n \"\"\"Retrieve Credential from file.\n \n Returns:\n oauth2client.client.Credentials\n \"\"\"\n credentials = None\n content = keyring.get_password(self._service_name, self._user_name)\n if content is not None:\n try:\n credentials = client.Credentials.new_from_json(content)\n credentials.set_store(self)\n except ValueError:\n pass\n return credentials\n ", "context": "class Storage(client.Storage):\n def locked_get(self): ...\n def __init__(self, service_name, user_name): ...\n def locked_put(self, credentials): ...\n def locked_delete(self): ...\n\n self._service_name = service_name\n self._user_name = user_name\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_locked_get", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001275.py"} {"focal_file": "vendor/oauth2client/contrib/keyring_storage.py", "focal_class": "oauth2client.contrib.keyring_storage.Storage", "focal_method": "locked_put", "tests": "import unittest\n\nclass Test_oauth2client_contrib_keyring_storage_Storage_locked_put(unittest.TestCase):\n def test_locked_put(self):\n service_name = 'my_unit_test'\n user_name = 'me'\n store = keyring_storage.Storage(service_name, user_name)\n with mock.patch.object(keyring, 'set_password', return_value=None, autospec=True) as set_password:\n credentials = mock.Mock()\n to_json_ret = object()\n credentials.to_json = to_json = mock.Mock(name='to_json', return_value=to_json_ret)\n store.locked_put(credentials)\n to_json.assert_called_once_with()\n set_password.assert_called_once_with(service_name, user_name, to_json_ret)\n", "method_code": " def locked_put(self, credentials):\n \"\"\"Write Credentials to file.\n \n Args:\n credentials: Credentials, the credentials to store.\n \"\"\"\n keyring.set_password(self._service_name, self._user_name, credentials.to_json())\n ", "context": "class Storage(client.Storage):\n def locked_put(self, credentials): ...\n def __init__(self, service_name, user_name): ...\n def locked_get(self): ...\n def locked_delete(self): ...\n\n self._service_name = service_name\n self._user_name = user_name\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_locked_put", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001276.py"} {"focal_file": "vendor/oauth2client/contrib/keyring_storage.py", "focal_class": "oauth2client.contrib.keyring_storage.Storage", "focal_method": "locked_delete", "tests": "import unittest\n\nclass Test_oauth2client_contrib_keyring_storage_Storage_locked_delete(unittest.TestCase):\n def test_locked_delete(self):\n service_name = 'my_unit_test'\n user_name = 'me'\n store = keyring_storage.Storage(service_name, user_name)\n with mock.patch.object(keyring, 'set_password', return_value=None, autospec=True) as set_password:\n store.locked_delete()\n set_password.assert_called_once_with(service_name, user_name, '')\n", "method_code": " def locked_delete(self):\n \"\"\"Delete Credentials file.\n \n Args:\n credentials: Credentials, the credentials to store.\n \"\"\"\n keyring.set_password(self._service_name, self._user_name, '')\n ", "context": "class Storage(client.Storage):\n def locked_delete(self): ...\n def __init__(self, service_name, user_name): ...\n def locked_get(self): ...\n def locked_put(self, credentials): ...\n\n self._service_name = service_name\n self._user_name = user_name\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_locked_delete", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001277.py"} {"focal_file": "vendor/oauth2client/contrib/_metadata.py", "focal_class": null, "focal_method": "get_service_account_info", "tests": "import unittest\n\nclass Test_get_service_account_info(unittest.TestCase):\n def test_service_account_info(self):\n http = request_mock(http_client.OK, 'application/json', json.dumps(DATA))\n info = _metadata.get_service_account_info(http)\n self.assertEqual(info, DATA)\n self.assertEqual(http.requests, 1)\n self.assertEqual(http.uri, EXPECTED_URL + '/?recursive=True')\n self.assertEqual(http.method, 'GET')\n self.assertIsNone(http.body)\n self.assertEqual(http.headers, _metadata.METADATA_HEADERS)\n", "method_code": "def get_service_account_info(http, service_account='default'):\n \"\"\"Get information about a service account from the metadata server.\n\n Args:\n http: an object to be used to make HTTP requests.\n service_account: An email specifying the service account for which to\n look up information. Default will be information for the \"default\"\n service account of the current compute engine instance.\n\n Returns:\n A dictionary with information about the specified service account,\n for example:\n\n {\n 'email': '...',\n 'scopes': ['scope', ...],\n 'aliases': ['default', '...']\n }\n \"\"\"\n return get(http, 'instance/service-accounts/{0}/'.format(service_account), recursive=True)", "context": "def get_service_account_info(http, service_account='default'): ...\ndef get(http, path, root=METADATA_ROOT, recursive=None): ...\ndef get_service_account_info(http, service_account='default'): ...\ndef get_token(http, service_account='default'): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_service_account_info", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001278.py"} {"focal_file": "vendor/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_create_file_if_needed", "tests": "import unittest\n\nclass Test_create_file_if_needed(unittest.TestCase):\n def test__create_file_if_needed(self):\n self.assertFalse(multiprocess_file_storage._create_file_if_needed(self.filename))\n os.unlink(self.filename)\n self.assertTrue(multiprocess_file_storage._create_file_if_needed(self.filename))\n self.assertTrue(os.path.exists(self.filename))\n", "method_code": "def _create_file_if_needed(filename):\n \"\"\"Creates the an empty file if it does not already exist.\n\n Returns:\n True if the file was created, False otherwise.\n \"\"\"\n if os.path.exists(filename):\n return False\n else:\n open(filename, 'a+b').close()\n logger.info('Credential file {0} created'.format(filename))\n return True", "context": "def _create_file_if_needed(filename): ...\ndef _create_file_if_needed(filename): ...\ndef _load_credentials_file(credentials_file): ...\ndef _write_credentials_file(credentials_file, credentials): ...\ndef _get_backend(filename): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__create_file_if_needed", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001279.py"} {"focal_file": "vendor/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_get_backend", "tests": "import unittest\n\nclass Test_get_backend(unittest.TestCase):\n def test__get_backend(self):\n backend_one = multiprocess_file_storage._get_backend('file_a')\n backend_two = multiprocess_file_storage._get_backend('file_a')\n backend_three = multiprocess_file_storage._get_backend('file_b')\n self.assertIs(backend_one, backend_two)\n self.assertIsNot(backend_one, backend_three)\n", "method_code": "def _get_backend(filename):\n \"\"\"A helper method to get or create a backend with thread locking.\n\n This ensures that only one backend is used per-file per-process, so that\n thread and process locks are appropriately shared.\n\n Args:\n filename: The full path to the credential storage file.\n\n Returns:\n An instance of :class:`_MultiprocessStorageBackend`.\n \"\"\"\n filename = os.path.abspath(filename)\n with _backends_lock:\n if filename not in _backends:\n _backends[filename] = _MultiprocessStorageBackend(filename)\n return _backends[filename]", "context": "def _get_backend(filename): ...\ndef _create_file_if_needed(filename): ...\ndef _load_credentials_file(credentials_file): ...\ndef _write_credentials_file(credentials_file, credentials): ...\ndef _get_backend(filename): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__get_backend", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001280.py"} {"focal_file": "vendor/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_write_credentials_file", "tests": "import unittest\n\nclass Test_write_credentials_file(unittest.TestCase):\n def test__read_write_credentials_file(self):\n credentials = _create_test_credentials()\n contents = six.StringIO()\n multiprocess_file_storage._write_credentials_file(contents, {'key': credentials})\n contents.seek(0)\n data = json.load(contents)\n self.assertEqual(data['file_version'], 2)\n self.assertTrue(data['credentials']['key'])\n contents.seek(0)\n results = multiprocess_file_storage._load_credentials_file(contents)\n self.assertEqual(results['key'].access_token, credentials.access_token)\n data['credentials']['invalid'] = '123'\n results = multiprocess_file_storage._load_credentials_file(six.StringIO(json.dumps(data)))\n self.assertNotIn('invalid', results)\n self.assertEqual(results['key'].access_token, credentials.access_token)\n", "method_code": "def _write_credentials_file(credentials_file, credentials):\n \"\"\"Writes credentials to a file.\n\n Refer to :func:`_load_credentials_file` for the format.\n\n Args:\n credentials_file: An open file handle, must be read/write.\n credentials: A dictionary mapping user-defined keys to an instance of\n :class:`oauth2client.client.Credentials`.\n \"\"\"\n data = {'file_version': 2, 'credentials': {}}\n for key, credential in iteritems(credentials):\n credential_json = credential.to_json()\n encoded_credential = _helpers._from_bytes(base64.b64encode(_helpers._to_bytes(credential_json)))\n data['credentials'][key] = encoded_credential\n credentials_file.seek(0)\n json.dump(data, credentials_file)\n credentials_file.truncate()", "context": "def _write_credentials_file(credentials_file, credentials): ...\ndef _create_file_if_needed(filename): ...\ndef _load_credentials_file(credentials_file): ...\ndef _write_credentials_file(credentials_file, credentials): ...\ndef _get_backend(filename): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__read_write_credentials_file", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001281.py"} {"focal_file": "vendor/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_load_credentials", "tests": "import unittest\n\nclass Test_load_credentials(unittest.TestCase):\n def test__load_credentials_no_open_file(self):\n backend = multiprocess_file_storage._get_backend(self.filename)\n backend._credentials = mock.Mock()\n backend._credentials.update.side_effect = AssertionError()\n backend._load_credentials()\n", "method_code": " def _load_credentials(self):\n \"\"\"(Re-)loads the credentials from the file.\"\"\"\n if not self._file:\n return\n loaded_credentials = _load_credentials_file(self._file)\n self._credentials.update(loaded_credentials)\n logger.debug('Read credential file')\n ", "context": "class _MultiprocessStorageBackend(object):\n def _load_credentials(self): ...\n def __init__(self, filename): ...\n def _write_credentials(self): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def _refresh_predicate(self, credentials): ...\n def locked_get(self, key): ...\n def locked_put(self, key, credentials): ...\n def locked_delete(self, key): ...\n\n self._file = None\n self._filename = filename\n self._process_lock = fasteners.InterProcessLock('{0}.lock'.format(filename))\n self._thread_lock = threading.Lock()\n self._read_only = False\n self._credentials = {}\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__load_credentials_no_open_file", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001282.py"} {"focal_file": "vendor/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "release_lock", "tests": "import unittest\n\nclass Test_release_lock(unittest.TestCase):\n def test_release_lock_with_no_file(self):\n backend = multiprocess_file_storage._get_backend(self.filename)\n backend._file = None\n backend._read_only = True\n backend._thread_lock.acquire()\n backend.release_lock()\n", "method_code": " def release_lock(self):\n if self._file is not None:\n self._file.close()\n self._file = None\n if not self._read_only:\n self._process_lock.release()\n self._thread_lock.release()\n ", "context": "class _MultiprocessStorageBackend(object):\n def release_lock(self): ...\n def __init__(self, filename): ...\n def _load_credentials(self): ...\n def _write_credentials(self): ...\n def acquire_lock(self): ...\n def _refresh_predicate(self, credentials): ...\n def locked_get(self, key): ...\n def locked_put(self, key, credentials): ...\n def locked_delete(self, key): ...\n\n self._file = None\n self._filename = filename\n self._process_lock = fasteners.InterProcessLock('{0}.lock'.format(filename))\n self._thread_lock = threading.Lock()\n self._read_only = False\n self._credentials = {}\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_release_lock_with_no_file", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001283.py"} {"focal_file": "vendor/oauth2client/contrib/multiprocess_file_storage.py", "focal_class": null, "focal_method": "_refresh_predicate", "tests": "import unittest\n\nclass Test_refresh_predicate(unittest.TestCase):\n def test__refresh_predicate(self):\n backend = multiprocess_file_storage._get_backend(self.filename)\n credentials = _create_test_credentials()\n self.assertFalse(backend._refresh_predicate(credentials))\n credentials.invalid = True\n self.assertTrue(backend._refresh_predicate(credentials))\n credentials = _create_test_credentials(expiration=datetime.datetime.utcnow() - datetime.timedelta(seconds=3600))\n self.assertTrue(backend._refresh_predicate(credentials))\n", "method_code": " def _refresh_predicate(self, credentials):\n if credentials is None:\n return True\n elif credentials.invalid:\n return True\n elif credentials.access_token_expired:\n return True\n else:\n return False\n ", "context": "class _MultiprocessStorageBackend(object):\n def _refresh_predicate(self, credentials): ...\n def __init__(self, filename): ...\n def _load_credentials(self): ...\n def _write_credentials(self): ...\n def acquire_lock(self): ...\n def release_lock(self): ...\n def locked_get(self, key): ...\n def locked_put(self, key, credentials): ...\n def locked_delete(self, key): ...\n\n self._file = None\n self._filename = filename\n self._process_lock = fasteners.InterProcessLock('{0}.lock'.format(filename))\n self._thread_lock = threading.Lock()\n self._read_only = False\n self._credentials = {}\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__refresh_predicate", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001284.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.AppAssertionCredentials", "focal_method": "create_scoped_required", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_AppAssertionCredentials_create_scoped_required(unittest.TestCase):\n def test_create_scoped_required_without_scopes(self):\n credentials = appengine.AppAssertionCredentials([])\n self.assertTrue(credentials.create_scoped_required())\n\n def test_create_scoped_required_with_scopes(self):\n credentials = appengine.AppAssertionCredentials(['dummy_scope'])\n self.assertFalse(credentials.create_scoped_required())\n", "method_code": " def create_scoped_required(self):\n return not self.scope\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def create_scoped_required(self): ...\n def __init__(self, scope, **kwargs): ...\n def from_json(cls, json_data): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped(self, scopes): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n\n self.scope = _helpers.scopes_to_string(scope)\n self._kwargs = kwargs\n self.service_account_id = kwargs.get('service_account_id', None)\n self._service_account_email = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_scoped_required_without_scopes", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001285.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.AppAssertionCredentials", "focal_method": "create_scoped", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_AppAssertionCredentials_create_scoped(unittest.TestCase):\n def test_create_scoped(self):\n credentials = appengine.AppAssertionCredentials([])\n new_credentials = credentials.create_scoped(['dummy_scope'])\n self.assertNotEqual(credentials, new_credentials)\n self.assertIsInstance(new_credentials, appengine.AppAssertionCredentials)\n self.assertEqual('dummy_scope', new_credentials.scope)\n", "method_code": " def create_scoped(self, scopes):\n return AppAssertionCredentials(scopes, **self._kwargs)\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def create_scoped(self, scopes): ...\n def __init__(self, scope, **kwargs): ...\n def from_json(cls, json_data): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def sign_blob(self, blob): ...\n def service_account_email(self): ...\n\n self.scope = _helpers.scopes_to_string(scope)\n self._kwargs = kwargs\n self.service_account_id = kwargs.get('service_account_id', None)\n self._service_account_email = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_create_scoped", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001286.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.AppAssertionCredentials", "focal_method": "sign_blob", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_AppAssertionCredentials_sign_blob(unittest.TestCase):\n def test_sign_blob(self):\n key_name = b'1234567890'\n sig_bytes = b'himom'\n app_identity_stub = self.AppIdentityStubImpl(key_name=key_name, sig_bytes=sig_bytes)\n apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()\n apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', app_identity_stub)\n credentials = appengine.AppAssertionCredentials([])\n to_sign = b'blob'\n self.assertEqual(app_identity_stub._sign_calls, [])\n result = credentials.sign_blob(to_sign)\n self.assertEqual(result, (key_name, sig_bytes))\n self.assertEqual(app_identity_stub._sign_calls, [to_sign])\n", "method_code": " def sign_blob(self, blob):\n \"\"\"Cryptographically sign a blob (of bytes).\n \n Implements abstract method\n :meth:`oauth2client.client.AssertionCredentials.sign_blob`.\n \n Args:\n blob: bytes, Message to be signed.\n \n Returns:\n tuple, A pair of the private key ID used to sign the blob and\n the signed contents.\n \"\"\"\n return app_identity.sign_blob(blob)\n ", "context": "class AppAssertionCredentials(client.AssertionCredentials):\n def sign_blob(self, blob): ...\n def __init__(self, scope, **kwargs): ...\n def from_json(cls, json_data): ...\n def _refresh(self, http): ...\n def serialization_data(self): ...\n def create_scoped_required(self): ...\n def create_scoped(self, scopes): ...\n def service_account_email(self): ...\n\n self.scope = _helpers.scopes_to_string(scope)\n self._kwargs = kwargs\n self.service_account_id = kwargs.get('service_account_id', None)\n self._service_account_email = None\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_sign_blob", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001287.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.FlowProperty", "focal_method": "make_value_from_datastore", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_FlowProperty_make_value_from_datastore(unittest.TestCase):\n def test_make_value_from_datastore_none(self):\n self.assertIsNone(appengine.FlowProperty().make_value_from_datastore(None))\n", "method_code": " def make_value_from_datastore(self, value):\n if value is None:\n return None\n return pickle.loads(value)\n ", "context": "class FlowProperty(db.Property):\n def make_value_from_datastore(self, value): ...\n def get_value_for_datastore(self, model_instance): ...\n def validate(self, value): ...\n def empty(self, value): ...\n\n data_type = client.Flow\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_make_value_from_datastore_none", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001288.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.CredentialsProperty", "focal_method": "validate", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_CredentialsProperty_validate(unittest.TestCase):\n def test_validate(self):\n appengine.CredentialsProperty().validate(self.credentials)\n appengine.CredentialsProperty().validate(None)\n with self.assertRaises(db.BadValueError):\n appengine.CredentialsProperty().validate(42)\n", "method_code": " def validate(self, value):\n if value is not None and (not isinstance(value, client.Flow)):\n raise db.BadValueError('Property {0} must be convertible to a FlowThreeLegged instance ({1})'.format(self.name, value))\n return super(FlowProperty, self).validate(value)\n ", "context": "class FlowProperty(db.Property):\n def validate(self, value): ...\n def get_value_for_datastore(self, model_instance): ...\n def make_value_from_datastore(self, value): ...\n def empty(self, value): ...\n\n data_type = client.Flow\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_validate", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001289.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.CredentialsProperty", "focal_method": "make_value_from_datastore", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_CredentialsProperty_make_value_from_datastore(unittest.TestCase):\n def test_make_value_from_datastore(self):\n self.assertIsNone(appengine.CredentialsProperty().make_value_from_datastore(None))\n self.assertIsNone(appengine.CredentialsProperty().make_value_from_datastore(''))\n self.assertIsNone(appengine.CredentialsProperty().make_value_from_datastore('{'))\n decoded = appengine.CredentialsProperty().make_value_from_datastore(self.credentials.to_json())\n self.assertEqual(self.credentials.to_json(), decoded.to_json())\n", "method_code": " def make_value_from_datastore(self, value):\n if value is None:\n return None\n return pickle.loads(value)\n ", "context": "class FlowProperty(db.Property):\n def make_value_from_datastore(self, value): ...\n def get_value_for_datastore(self, model_instance): ...\n def validate(self, value): ...\n def empty(self, value): ...\n\n data_type = client.Flow\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_make_value_from_datastore", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001290.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.StorageByKeyName", "focal_method": "_is_ndb", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_StorageByKeyName_is_ndb(unittest.TestCase):\n def test__is_ndb(self):\n storage = appengine.StorageByKeyName(object(), 'foo', 'credentials')\n with self.assertRaises(TypeError):\n storage._is_ndb()\n storage._model = type(object)\n with self.assertRaises(TypeError):\n storage._is_ndb()\n storage._model = appengine.CredentialsModel\n self.assertFalse(storage._is_ndb())\n storage._model = appengine.CredentialsNDBModel\n self.assertTrue(storage._is_ndb())\n", "method_code": " def _is_ndb(self):\n \"\"\"Determine whether the model of the instance is an NDB model.\n \n Returns:\n Boolean indicating whether or not the model is an NDB or DB model.\n \"\"\"\n if isinstance(self._model, type):\n if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL):\n return True\n elif issubclass(self._model, db.Model):\n return False\n raise TypeError('Model class not an NDB or DB model: {0}.'.format(self._model))\n ", "context": "class StorageByKeyName(client.Storage):\n def _is_ndb(self): ...\n def __init__(self, model, key_name, property_name, cache=None, user=None): ...\n def _get_entity(self): ...\n def _delete_entity(self): ...\n def locked_get(self): ...\n def locked_put(self, credentials): ...\n def locked_delete(self): ...\n\n self._model = model\n self._key_name = key_name\n self._property_name = property_name\n self._cache = cache\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test__is_ndb", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001291.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": "oauth2client.contrib.appengine.StorageByKeyName", "focal_method": "get", "tests": "import unittest\n\nclass Test_oauth2client_contrib_appengine_StorageByKeyName_get(unittest.TestCase):\n def test_get_and_put_mixed_ndb_storage_db_get(self):\n storage = appengine.StorageByKeyName(appengine.CredentialsNDBModel, 'foo', 'credentials')\n self.assertEqual(None, storage.get())\n self.credentials.set_store(storage)\n http = http_mock.HttpMock(data=BASIC_RESP)\n self.credentials._refresh(http)\n credmodel = appengine.CredentialsModel.get_by_key_name('foo')\n self.assertEqual(BASIC_TOKEN, credmodel.credentials.access_token)\n self.assertEqual(self.credentials.to_json(), credmodel.credentials.to_json())\n self._verify_basic_refresh(http)\n\n def test_get_and_put_mixed_db_storage_ndb_get(self):\n storage = appengine.StorageByKeyName(appengine.CredentialsModel, 'foo', 'credentials')\n self.assertEqual(None, storage.get())\n self.credentials.set_store(storage)\n http = http_mock.HttpMock(data=BASIC_RESP)\n self.credentials._refresh(http)\n credmodel = appengine.CredentialsNDBModel.get_by_id('foo')\n self.assertEqual(BASIC_TOKEN, credmodel.credentials.access_token)\n self.assertEqual(self.credentials.to_json(), credmodel.credentials.to_json())\n self._verify_basic_refresh(http)\n", "method_code": " def get(self):\n error = self.request.get('error')\n if error:\n errormsg = self.request.get('error_description', error)\n self.response.out.write('The authorization request failed: {0}'.format(_safe_html(errormsg)))\n else:\n user = users.get_current_user()\n decorator._create_flow(self)\n credentials = decorator.flow.step2_exchange(self.request.params)\n decorator._storage_class(decorator._credentials_class, None, decorator._credentials_property_name, user=user).put(credentials)\n redirect_uri = _parse_state_value(str(self.request.get('state')), user)\n if redirect_uri is None:\n self.response.out.write('The authorization request failed')\n return\n if decorator._token_response_param and credentials.token_response:\n resp_json = json.dumps(credentials.token_response)\n redirect_uri = _helpers._add_query_parameter(redirect_uri, decorator._token_response_param, resp_json)\n self.redirect(redirect_uri)\n ", "context": "class OAuth2Handler(webapp.RequestHandler):\n @login_required\n def get(self): ...", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_get_and_put_mixed_ndb_storage_db_get", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001292.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": null, "focal_method": "callback_application", "tests": "import unittest\n\nclass Test_callback_application(unittest.TestCase):\n def test_callback_application(self):\n app = self.decorator.callback_application()\n self.assertEqual(app.router.match_routes[0].handler.__name__, 'OAuth2Handler')\n", "method_code": " def callback_application(self):\n \"\"\"WSGI application for handling the OAuth 2.0 redirect callback.\n \n If you need finer grained control use `callback_handler` which returns\n just the webapp.RequestHandler.\n \n Returns:\n A webapp.WSGIApplication that handles the redirect back from the\n server during the OAuth 2.0 dance.\n \"\"\"\n return webapp.WSGIApplication([(self.callback_path, self.callback_handler())])\n ", "context": "class OAuth2Decorator(object):\n def callback_application(self): ...\n def set_credentials(self, credentials): ...\n def get_credentials(self): ...\n def set_flow(self, flow): ...\n def get_flow(self): ...\n def __init__(self, client_id, client_secret, scope, auth_uri=oauth2client.GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, user_agent=None, message=None, callback_path='/oauth2callback', token_response_param=None, _storage_class=StorageByKeyName, _credentials_class=CredentialsModel, _credentials_property_name='credentials', **kwargs): ...\n def _display_error_message(self, request_handler): ...\n def oauth_required(self, method): ...\n def _create_flow(self, request_handler): ...\n def oauth_aware(self, method): ...\n def has_credentials(self): ...\n def authorize_url(self): ...\n def http(self, *args, **kwargs): ...\n def callback_path(self): ...\n def callback_handler(self): ...\n\n self._tls = threading.local()\n self.flow = None\n self.credentials = None\n self._client_id = client_id\n self._client_secret = client_secret\n self._scope = _helpers.scopes_to_string(scope)\n self._auth_uri = auth_uri\n self._token_uri = token_uri\n self._revoke_uri = revoke_uri\n self._user_agent = user_agent\n self._kwargs = kwargs\n self._message = message\n self._in_error = False\n self._callback_path = callback_path\n self._token_response_param = token_response_param\n self._storage_class = _storage_class\n self._credentials_class = _credentials_class\n self._credentials_property_name = _credentials_property_name\n\n credentials = property(get_credentials, set_credentials)\n flow = property(get_flow, set_flow)\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_callback_application", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001293.py"} {"focal_file": "vendor/oauth2client/contrib/appengine.py", "focal_class": null, "focal_method": "oauth2decorator_from_clientsecrets", "tests": "import unittest\n\nclass Test_oauth2decorator_from_clientsecrets(unittest.TestCase):\n def test_decorator_from_client_secrets_toplevel(self):\n decorator_patch = mock.patch('oauth2client.contrib.appengine.OAuth2DecoratorFromClientSecrets')\n with decorator_patch as decorator_mock:\n filename = datafile('client_secrets.json')\n appengine.oauth2decorator_from_clientsecrets(filename, scope='foo_scope')\n decorator_mock.assert_called_once_with(filename, 'foo_scope', cache=None, message=None)\n", "method_code": "def oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None):\n \"\"\"Creates an OAuth2Decorator populated from a clientsecrets file.\n\n Args:\n filename: string, File name of client secrets.\n scope: string or list of strings, scope(s) of the credentials being\n requested.\n message: string, A friendly string to display to the user if the\n clientsecrets file is missing or invalid. The message may\n contain HTML and will be presented on the web interface for\n any method that uses the decorator.\n cache: An optional cache service client that implements get() and set()\n methods. See clientsecrets.loadfile() for details.\n\n Returns: An OAuth2Decorator\n \"\"\"\n return OAuth2DecoratorFromClientSecrets(filename, scope, message=message, cache=cache)", "context": "@_helpers.positional(2)\ndef oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None): ...\ndef _safe_html(s): ...\ndef _generate_new_xsrf_secret_key(): ...\ndef xsrf_secret_key(): ...\ndef _build_state_value(request_handler, user): ...\ndef _parse_state_value(state, user): ...\ndef oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_decorator_from_client_secrets_toplevel", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001294.py"} {"focal_file": "vendor/oauth2client/contrib/django_util/models.py", "focal_class": null, "focal_method": "from_db_value", "tests": "import unittest\n\nclass Test_from_db_value(unittest.TestCase):\n def test_from_db_value(self):\n value = self.field.from_db_value(self.pickle_str, None, None, None)\n self.assertIsInstance(value, client.Credentials)\n", "method_code": " def from_db_value(self, value, expression, connection, context):\n \"\"\"Overrides ``models.Field`` method. This converts the value\n returned from the database to an instance of this class.\n \"\"\"\n return self.to_python(value)\n ", "context": "class CredentialsField(models.Field):\n def from_db_value(self, value, expression, connection, context): ...\n def __init__(self, *args, **kwargs): ...\n def get_internal_type(self): ...\n def to_python(self, value): ...\n def get_prep_value(self, value): ...\n def value_to_string(self, obj): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_from_db_value", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001295.py"} {"focal_file": "vendor/oauth2client/contrib/django_util/models.py", "focal_class": null, "focal_method": "value_to_string", "tests": "import unittest\n\nclass Test_value_to_string(unittest.TestCase):\n def test_field_value_to_string(self):\n self.fake_model.credentials = self.credentials\n value_str = self.fake_model_field.value_to_string(self.fake_model)\n self.assertEqual(value_str, self.pickle_str)\n\n def test_field_value_to_string_none(self):\n self.fake_model.credentials = None\n value_str = self.fake_model_field.value_to_string(self.fake_model)\n self.assertIsNone(value_str)\n", "method_code": " def value_to_string(self, obj):\n \"\"\"Convert the field value from the provided model to a string.\n \n Used during model serialization.\n \n Args:\n obj: db.Model, model object\n \n Returns:\n string, the serialized field value\n \"\"\"\n value = self._get_val_from_obj(obj)\n return self.get_prep_value(value)\n ", "context": "class CredentialsField(models.Field):\n def value_to_string(self, obj): ...\n def __init__(self, *args, **kwargs): ...\n def get_internal_type(self): ...\n def from_db_value(self, value, expression, connection, context): ...\n def to_python(self, value): ...\n def get_prep_value(self, value): ...\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "test_field_value_to_string", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001296.py"} {"focal_file": "vendor/oauth2client/contrib/django_util/storage.py", "focal_class": null, "focal_method": "locked_get", "tests": "import unittest\n\nclass Test_locked_get(unittest.TestCase):\n @mock.patch('django.db.models')\n def test_locked_get(self, djangoModel):\n fake_model_with_credentials = FakeCredentialsModelMock()\n entities = [fake_model_with_credentials]\n filter_mock = mock.Mock(return_value=entities)\n object_mock = mock.Mock()\n object_mock.filter = filter_mock\n FakeCredentialsModelMock.objects = object_mock\n storage = Storage(FakeCredentialsModelMock, self.key_name, self.key_value, self.property_name)\n credential = storage.locked_get()\n self.assertEqual(credential, fake_model_with_credentials.credentials)\n\n @mock.patch('django.db.models')\n def test_locked_get_no_entities(self, djangoModel):\n entities = []\n filter_mock = mock.Mock(return_value=entities)\n object_mock = mock.Mock()\n object_mock.filter = filter_mock\n FakeCredentialsModelMock.objects = object_mock\n storage = Storage(FakeCredentialsModelMock, self.key_name, self.key_value, self.property_name)\n credential = storage.locked_get()\n self.assertIsNone(credential)\n\n @mock.patch('django.db.models')\n def test_locked_get_no_set_store(self, djangoModel):\n fake_model_with_credentials = FakeCredentialsModelMockNoSet()\n entities = [fake_model_with_credentials]\n filter_mock = mock.Mock(return_value=entities)\n object_mock = mock.Mock()\n object_mock.filter = filter_mock\n FakeCredentialsModelMockNoSet.objects = object_mock\n storage = Storage(FakeCredentialsModelMockNoSet, self.key_name, self.key_value, self.property_name)\n credential = storage.locked_get()\n self.assertEqual(credential, fake_model_with_credentials.credentials)\n", "method_code": " def locked_get(self):\n \"\"\"Retrieve stored credential from the Django ORM.\n \n Returns:\n oauth2client.Credentials retrieved from the Django ORM, associated\n with the ``model``, ``key_value``->``key_name`` pair used to query\n for the model, and ``property_name`` identifying the\n ``CredentialsProperty`` field, all of which are defined in the\n constructor for this Storage object.\n \n \"\"\"\n query = {self.key_name: self.key_value}\n entities = self.model_class.objects.filter(**query)\n if len(entities) > 0:\n credential = getattr(entities[0], self.property_name)\n if getattr(credential, 'set_store', None) is not None:\n credential.set_store(self)\n return credential\n else:\n return None\n ", "context": "class DjangoORMStorage(client.Storage):\n def locked_get(self): ...\n def __init__(self, model_class, key_name, key_value, property_name): ...\n def locked_put(self, credentials): ...\n def locked_delete(self): ...\n\n self.model_class = model_class\n self.key_name = key_name\n self.key_value = key_value\n self.property_name = property_name\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001297.py"} {"focal_file": "vendor/oauth2client/contrib/django_util/storage.py", "focal_class": null, "focal_method": "locked_put", "tests": "import unittest\n\nclass Test_locked_put(unittest.TestCase):\n @mock.patch('django.db.models')\n def test_locked_put(self, djangoModel):\n entity_mock = mock.Mock(credentials=None)\n objects = mock.Mock(get_or_create=mock.Mock(return_value=(entity_mock, None)))\n FakeCredentialsModelMock.objects = objects\n storage = Storage(FakeCredentialsModelMock, self.key_name, self.key_value, self.property_name)\n storage.locked_put(self.credentials)\n", "method_code": " def locked_put(self, credentials):\n \"\"\"Write a Credentials to the Django datastore.\n \n Args:\n credentials: Credentials, the credentials to store.\n \"\"\"\n entity, _ = self.model_class.objects.get_or_create(**{self.key_name: self.key_value})\n setattr(entity, self.property_name, credentials)\n entity.save()\n ", "context": "class DjangoORMStorage(client.Storage):\n def locked_put(self, credentials): ...\n def __init__(self, model_class, key_name, key_value, property_name): ...\n def locked_get(self): ...\n def locked_delete(self): ...\n\n self.model_class = model_class\n self.key_name = key_name\n self.key_value = key_value\n self.property_name = property_name\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001298.py"} {"focal_file": "vendor/oauth2client/contrib/django_util/storage.py", "focal_class": null, "focal_method": "locked_delete", "tests": "import unittest\n\nclass Test_locked_delete(unittest.TestCase):\n @mock.patch('django.db.models')\n def test_locked_delete(self, djangoModel):\n\n class FakeEntities(object):\n\n def __init__(self):\n self.deleted = False\n\n def delete(self):\n self.deleted = True\n fake_entities = FakeEntities()\n entities = fake_entities\n filter_mock = mock.Mock(return_value=entities)\n object_mock = mock.Mock()\n object_mock.filter = filter_mock\n FakeCredentialsModelMock.objects = object_mock\n storage = Storage(FakeCredentialsModelMock, self.key_name, self.key_value, self.property_name)\n storage.locked_delete()\n self.assertTrue(fake_entities.deleted)\n", "method_code": " def locked_delete(self):\n \"\"\"Delete Credentials from the datastore.\"\"\"\n query = {self.key_name: self.key_value}\n self.model_class.objects.filter(**query).delete()\n ", "context": "class DjangoORMStorage(client.Storage):\n def locked_delete(self): ...\n def __init__(self, model_class, key_name, key_value, property_name): ...\n def locked_get(self): ...\n def locked_put(self, credentials): ...\n\n self.model_class = model_class\n self.key_name = key_name\n self.key_value = key_value\n self.property_name = property_name\n", "repository": "tsuyopooon/detectImage-linebot-service", "test_name": "", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001299.py"} {"focal_file": "src/booze/util.py", "focal_class": null, "focal_method": "singleton", "tests": "import unittest\n\nclass Test_singleton(unittest.TestCase):\n def test_singleton(self):\n\n class Cls:\n pass\n singleton = util.singleton(Cls)\n self.assertIsInstance(singleton, Cls)\n", "method_code": "def singleton(cls):\n \"\"\"Define a singleton class.\n\n A singleton class has only one instance.\n\n Example:\n\n @singleton\n class my_singleton:\n\n __counter = 0\n\n def inc(self):\n self.__counter += 1\n return self.__counter\n\n assert my_singleton.inc() == 1\n assert my_singleton.inc() == 2\n\n Args:\n cls: Class for which there will be only one instance.\n\n Returns:\n Singleton class instance.\n \"\"\"\n return cls()", "context": "def singleton(cls): ...\ndef singleton(cls): ...\ndef calculated_property(method): ...\n", "repository": "slobberchops/booze", "test_name": "test_singleton", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001300.py"} {"focal_file": "src/booze/gin/local_vars.py", "focal_class": null, "focal_method": "invoke", "tests": "import unittest\n\nclass Test_invoke(unittest.TestCase):\n def test_invoke(self):\n\n class SimpleLocals:\n pass\n locals_instance = SimpleLocals()\n self.assertEqual(10, self.action.invoke(1, 2, 3, a='a', b='b', c='c', vars=locals_instance))\n self.assertEqual(10, locals_instance.my_name)\n", "method_code": " def invoke(self, *args, vars=None, **kwargs):\n if vars is None:\n raise TypeError(\"Must provide 'vars' parameter\")\n return getattr(vars, whiskey.invoke(self.__name, *args, locals=locals, **kwargs))\n ", "context": "class GetVarAttr(whiskey.Action):\n def invoke(self, *args, vars=None, **kwargs): ...\n def __init__(self, name): ...\n def name(self): ...\n def __getitem__(self, value): ...\n\n self.__name = name\n", "repository": "slobberchops/booze", "test_name": "test_invoke", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001301.py"} {"focal_file": "src/booze/gin/local_vars.py", "focal_class": "booze.gin.local_vars.SetVarAttr", "focal_method": "invoke", "tests": "import unittest\n\nclass Test_booze_gin_local_vars_SetVarAttr_invoke(unittest.TestCase):\n def test_invoke_name_action(self):\n\n class SimpleLocals:\n pass\n locals_instance = SimpleLocals()\n test_action = local_vars.SetVarAttr(whiskey.p[0], 10)\n self.assertEqual(10, test_action.invoke('one', 2, 3, a='a', b='b', c='c', vars=locals_instance))\n self.assertEqual(10, locals_instance.one)\n test_action = local_vars.SetVarAttr(whiskey.p.a, 20)\n self.assertEqual(20, test_action.invoke(1, 2, 3, a='a', b='b', c='c', vars=locals_instance))\n self.assertEqual(20, locals_instance.a)\n\n def test_invoke_value_action(self):\n\n class SimpleLocals:\n pass\n locals_instance = SimpleLocals()\n test_action = local_vars.SetVarAttr('my_name', whiskey.p[0])\n self.assertEqual(1, test_action.invoke(1, 2, 3, a='a', b='b', c='c', vars=locals_instance))\n self.assertEqual(1, locals_instance.my_name)\n test_action = local_vars.SetVarAttr('my_name', whiskey.p.a)\n self.assertEqual('a', test_action.invoke(1, 2, 3, a='a', b='b', c='c', vars=locals_instance))\n self.assertEqual('a', locals_instance.my_name)\n", "method_code": " def invoke(self, *args, vars=None, **kwargs):\n if vars is None:\n raise TypeError(\"Must provide 'vars' parameter\")\n return getattr(vars, whiskey.invoke(self.__name, *args, locals=locals, **kwargs))\n ", "context": "class GetVarAttr(whiskey.Action):\n def invoke(self, *args, vars=None, **kwargs): ...\n def __init__(self, name): ...\n def name(self): ...\n def __getitem__(self, value): ...\n\n self.__name = name\n", "repository": "slobberchops/booze", "test_name": "test_invoke_name_action", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001302.py"} {"focal_file": "src/booze/gin/parser.py", "focal_class": "booze.gin.parser.Char", "focal_method": "parse", "tests": "import unittest\n\nclass Test_booze_gin_parser_Char_parse(unittest.TestCase):\n def test_parser(self):\n p = parser.as_parser(parser.Char('a'))\n s = io.StringIO('a')\n self.assertEqual((True, 'a'), p.parse(s))\n\n def test_parse(self):\n p = parser.not_predicate[parser.Char('b')]\n s = io.StringIO('abcd')\n self.assertEqual((True, parser.UNUSED), p.parse(s))\n self.assertEqual(0, s.tell())\n", "method_code": " def parse(self, parser_input, skipper=None):\n if skipper is not None and isinstance(parser_input, ParserState):\n raise TypeError('May not provide ParserState and new skipper')\n if not isinstance(parser_input, ParserState):\n parser_input = ParserState(parser_input, skipper)\n with parser_input.open_transaction() as state:\n if state.skipper:\n status = True\n skipper = state.skipper\n state.skipper = None\n try:\n while status:\n with state.open_transaction():\n status, _ = skipper.parse(state)\n if status:\n state.commit()\n finally:\n state.skipper = skipper\n self._parse(state)\n return (state.successful, state.value if state.successful else None)\n ", "context": "class Parser():\n def parse(self, parser_input, skipper=None): ...\n def attr_type(self): ...\n def _parse(self, state): ...\n def __lshift__(self, other): ...\n def __rlshift__(self, other): ...\n def __or__(self, other): ...\n def __ror__(self, other): ...\n def __getitem__(self, func): ...\n def __neg__(self): ...\n def __pos__(self): ...\n def __invert__(self): ...\n", "repository": "slobberchops/booze", "test_name": "test_parser", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001303.py"} {"focal_file": "src/booze/gin/parser.py", "focal_class": null, "focal_method": "commit", "tests": "import unittest\n\nclass Test_commit(unittest.TestCase):\n def test_read_and_commit(self):\n with self.state.open_transaction():\n self.assertEqual('a', self.state.read(1))\n self.assertEqual(1, self.input.tell())\n self.assertEqual('b', self.state.read(1))\n self.assertEqual('c', self.state.read(1))\n self.assertEqual(3, self.input.tell())\n self.assertEqual('', self.state.read(1))\n self.assertFalse(self.state.committed)\n self.assertFalse(self.state.successful)\n self.state.commit('a value')\n self.assertTrue(self.state.committed)\n self.assertTrue(self.state.successful)\n self.assertEqual(3, self.input.tell())\n\n def test_commit(self):\n with self.state.open_transaction():\n self.state.commit('a value')\n self.assertTrue(self.state.committed)\n self.assertTrue(self.state.successful)\n self.assertEqual('a value', self.state.value)\n\n def test_uncommit(self):\n with self.state.open_transaction():\n self.state.commit('a value')\n self.state.uncommit()\n self.assertFalse(self.state.committed)\n self.assertTrue(self.state.successful)\n self.assertEqual('a value', self.state.value)\n", "method_code": " def commit(self, value=UNUSED):\n self.value = value\n self._tx.commit = True\n ", "context": "class ParserState():\n def commit(self, value=UNUSED): ...\n def __init__(self, state_input, skipper=None): ...\n def input(self): ...\n def skipper(self): ...\n def skipper(self, skipper): ...\n def _tx(self): ...\n def committed(self): ...\n def successful(self): ...\n def value(self): ...\n def scope(self): ...\n def value(self, value): ...\n def read(self, *args, **kwargs): ...\n def succeed(self, value=UNUSED): ...\n def rollback(self): ...\n def uncommit(self): ...\n def open_scope(self, *args, **kwargs): ...\n def open_transaction(self): ...\n def invoke(self, value): ...\n\n self.skipper = skipper\n self.__tx = None\n self.__scope = None\n", "repository": "slobberchops/booze", "test_name": "test_read_and_commit", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001304.py"} {"focal_file": "src/booze/gin/parser.py", "focal_class": null, "focal_method": "rollback", "tests": "import unittest\n\nclass Test_rollback(unittest.TestCase):\n def test_rollback(self):\n with self.state.open_transaction():\n self.state.commit('a value')\n self.state.rollback()\n self.assertFalse(self.state.committed)\n self.assertFalse(self.state.successful)\n self.assertEqual(parser.UNUSED, self.state.value)\n", "method_code": " def rollback(self):\n self._tx.commit = False\n self._tx.success = False\n del self._tx.value\n ", "context": "class ParserState():\n def rollback(self): ...\n def __init__(self, state_input, skipper=None): ...\n def input(self): ...\n def skipper(self): ...\n def skipper(self, skipper): ...\n def _tx(self): ...\n def committed(self): ...\n def successful(self): ...\n def value(self): ...\n def scope(self): ...\n def value(self, value): ...\n def read(self, *args, **kwargs): ...\n def commit(self, value=UNUSED): ...\n def succeed(self, value=UNUSED): ...\n def uncommit(self): ...\n def open_scope(self, *args, **kwargs): ...\n def open_transaction(self): ...\n def invoke(self, value): ...\n\n self.skipper = skipper\n self.__tx = None\n self.__scope = None\n", "repository": "slobberchops/booze", "test_name": "test_rollback", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001305.py"} {"focal_file": "src/booze/gin/parser.py", "focal_class": null, "focal_method": "open_scope", "tests": "import unittest\n\nclass Test_open_scope(unittest.TestCase):\n def test_invoke_scope(self):\n with self.state.open_scope(1, 2, 3, a='a', b='b', c='c'):\n self.assertEqual(10, self.state.invoke(10))\n l = lambda *args, **kwargs: (args, kwargs)\n self.assertEqual(l, self.state.invoke(l))\n a = TestAction()\n self.assertEqual('invoked', self.state.invoke(a))\n self.assertSequenceEqual((1, 2, 3), a.args)\n self.assertDictEqual({'a': 'a', 'b': 'b', 'c': 'c', 'vars': local_vars.Vars()}, a.kwargs)\n\n def test_scope(self):\n self.assertIsNone(self.state.scope)\n with self.state.open_scope(1, 2, 3, a='a', b='b', c='c') as scope:\n self.assertIsInstance(scope, local_vars.LocalScope)\n self.assertSequenceEqual((1, 2, 3), scope.args)\n self.assertDictEqual({'a': 'a', 'b': 'b', 'c': 'c'}, scope.kwargs)\n self.assertIsNone(self.state.scope)\n", "method_code": " def open_scope(self, *args, **kwargs):\n previous_scope = self.__scope\n self.__scope = local_vars.LocalScope(*args, **kwargs)\n try:\n yield self.__scope\n finally:\n self.__scope = previous_scope\n ", "context": "class ParserState():\n @contextlib.contextmanager\n def open_scope(self, *args, **kwargs): ...\n def __init__(self, state_input, skipper=None): ...\n def input(self): ...\n def skipper(self): ...\n def skipper(self, skipper): ...\n def _tx(self): ...\n def committed(self): ...\n def successful(self): ...\n def value(self): ...\n def scope(self): ...\n def value(self, value): ...\n def read(self, *args, **kwargs): ...\n def commit(self, value=UNUSED): ...\n def succeed(self, value=UNUSED): ...\n def rollback(self): ...\n def uncommit(self): ...\n def open_transaction(self): ...\n def invoke(self, value): ...\n\n self.skipper = skipper\n self.__tx = None\n self.__scope = None\n", "repository": "slobberchops/booze", "test_name": "test_invoke_scope", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001306.py"} {"focal_file": "src/booze/gin/parser.py", "focal_class": null, "focal_method": "compatible", "tests": "import unittest\n\nclass Test_compatible(unittest.TestCase):\n def test_compatible(self):\n self.assertTrue(parser.AttrType.UNUSED.compatible(object()))\n self.assertTrue(parser.AttrType.OBJECT.compatible(object()))\n self.assertTrue(parser.AttrType.STRING.compatible('a string'))\n self.assertTrue(parser.AttrType.TUPLE.compatible(('a', 'tuple')))\n\n def test_not_compatible(self):\n self.assertFalse(parser.AttrType.STRING.compatible(object()))\n self.assertFalse(parser.AttrType.TUPLE.compatible('a string'))\n", "method_code": " def compatible(self, value):\n if self in (AttrType.UNUSED, AttrType.OBJECT):\n return True\n elif isinstance(value, str) and self == AttrType.STRING:\n return True\n elif isinstance(value, tuple) and self == AttrType.TUPLE:\n return True\n else:\n return False\n ", "context": "class AttrType(enum.Enum):\n def compatible(self, value): ...\n def check_compatible(self, value): ...\n def type_for(value): ...\n\n UNUSED = 1\n OBJECT = 2\n STRING = 3\n TUPLE = 4\n", "repository": "slobberchops/booze", "test_name": "test_compatible", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001307.py"} {"focal_file": "src/booze/gin/parser.py", "focal_class": null, "focal_method": "check_compatible", "tests": "import unittest\n\nclass Test_check_compatible(unittest.TestCase):\n def test_check_compatible(self):\n parser.AttrType.UNUSED.check_compatible(object())\n parser.AttrType.OBJECT.check_compatible(object())\n parser.AttrType.STRING.check_compatible('a string')\n parser.AttrType.TUPLE.check_compatible(('a', 'tuple'))\n\n def test_check_not_compatible(self):\n with self.assertRaisesRegexp(TypeError, 'Value 10 incompatible with AttrType\\\\.STRING'):\n parser.AttrType.STRING.check_compatible(10)\n with self.assertRaisesRegexp(TypeError, \"Value \\\\'a string\\\\' incompatible with AttrType\\\\.TUPLE\"):\n parser.AttrType.TUPLE.check_compatible('a string')\n", "method_code": " def check_compatible(self, value):\n if not self.compatible(value):\n raise TypeError('Value {} incompatible with AttrType.{}'.format(repr(value), self.name))\n ", "context": "class AttrType(enum.Enum):\n def check_compatible(self, value): ...\n def compatible(self, value): ...\n def type_for(value): ...\n\n UNUSED = 1\n OBJECT = 2\n STRING = 3\n TUPLE = 4\n", "repository": "slobberchops/booze", "test_name": "test_check_compatible", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001308.py"} {"focal_file": "src/booze/gin/parser.py", "focal_class": null, "focal_method": "type_for", "tests": "import unittest\n\nclass Test_type_for(unittest.TestCase):\n def test_type_for(self):\n self.assertEqual(parser.AttrType.UNUSED, parser.AttrType.type_for(parser.UNUSED))\n self.assertEqual(parser.AttrType.OBJECT, parser.AttrType.type_for(10))\n self.assertEqual(parser.AttrType.STRING, parser.AttrType.type_for('a string'))\n self.assertEqual(parser.AttrType.TUPLE, parser.AttrType.type_for(('a', 'string')))\n", "method_code": " def type_for(value):\n if value is UNUSED:\n return AttrType.UNUSED\n if isinstance(value, str):\n return AttrType.STRING\n elif isinstance(value, tuple):\n return AttrType.TUPLE\n else:\n return AttrType.OBJECT\n ", "context": "class AttrType(enum.Enum):\n @staticmethod\n def type_for(value): ...\n def compatible(self, value): ...\n def check_compatible(self, value): ...\n\n UNUSED = 1\n OBJECT = 2\n STRING = 3\n TUPLE = 4\n", "repository": "slobberchops/booze", "test_name": "test_type_for", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001309.py"} {"focal_file": "src/booze/gin/parser.py", "focal_class": "booze.gin.parser.ParserState", "focal_method": "open_scope", "tests": "import unittest\n\nclass Test_booze_gin_parser_ParserState_open_scope(unittest.TestCase):\n def test_parse_with_scope(self):\n s = parser.ParserState('b')\n with s.open_scope():\n p = parser.SemanticAction(parser.Char('abc'), lambda v, vars: str((v, str(vars))))\n self.assertEqual((True, \"('b', '')\"), p.parse(s))\n self.assertEqual(1, s.input.tell())\n", "method_code": " def open_scope(self, *args, **kwargs):\n previous_scope = self.__scope\n self.__scope = local_vars.LocalScope(*args, **kwargs)\n try:\n yield self.__scope\n finally:\n self.__scope = previous_scope\n ", "context": "class ParserState():\n @contextlib.contextmanager\n def open_scope(self, *args, **kwargs): ...\n def __init__(self, state_input, skipper=None): ...\n def input(self): ...\n def skipper(self): ...\n def skipper(self, skipper): ...\n def _tx(self): ...\n def committed(self): ...\n def successful(self): ...\n def value(self): ...\n def scope(self): ...\n def value(self, value): ...\n def read(self, *args, **kwargs): ...\n def commit(self, value=UNUSED): ...\n def succeed(self, value=UNUSED): ...\n def rollback(self): ...\n def uncommit(self): ...\n def open_transaction(self): ...\n def invoke(self, value): ...\n\n self.skipper = skipper\n self.__tx = None\n self.__scope = None\n", "repository": "slobberchops/booze", "test_name": "test_parse_with_scope", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001310.py"} {"focal_file": "src/booze/whiskey/action.py", "focal_class": "booze.whiskey.action.KwArg", "focal_method": "invoke", "tests": "import unittest\n\nclass Test_booze_whiskey_action_KwArg_invoke(unittest.TestCase):\n def test_invoke(self):\n self.assertEqual('a', action.KwArg('a').invoke(1, 2, 3, a='a', b='b', c='c'))\n self.assertEqual('b', action.KwArg('b').invoke(1, 2, 3, a='a', b='b', c='c'))\n self.assertEqual('c', action.KwArg('c').invoke(1, 2, 3, a='a', b='b', c='c'))\n", "method_code": "def invoke(value, *args, **kwargs):\n \"\"\"Get value of invoking against a value with arguments.\n\n Useful as short hand for condition invocation. For example:\n\n if isinstance(value, Action):\n value.invoke(1, 2, 3, a='a', b='b', c='c')\n\n is the same as:\n\n invoke(value, 1, 2, 3, a='a', b='b', c='c')\n\n Args:\n value: Value to be invoked against. May be Action or non-action.\n args: Index based arguments.\n kwargs: Keyword based arguments.\n\n Returns:\n Result from invoking value if value is action, else just the value.\n \"\"\"\n if isinstance(value, Action):\n return value.invoke(*args, **kwargs)\n else:\n return value", "context": "def invoke(value, *args, **kwargs): ...\ndef invoke(value, *args, **kwargs): ...\ndef func(real_func): ...\n", "repository": "slobberchops/booze", "test_name": "test_invoke", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001311.py"} {"focal_file": "datalab/utils/_http.py", "focal_class": null, "focal_method": "request", "tests": "import unittest\n\nclass Test_request(unittest.TestCase):\n @mock.patch('httplib2.Response')\n @mock.patch('datalab.utils._http.Http.http.request')\n def test_formats_json_request(self, mock_request, mock_response):\n TestCases._setup_mocks(mock_request, mock_response, '{}')\n data = {'abc': 123}\n Http.request('http://www.example.org', data=data)\n self.assertEqual(mock_request.call_args[1]['body'], '{\"abc\": 123}')\n self.assertEqual(mock_request.call_args[1]['headers']['Content-Type'], 'application/json')\n", "method_code": " def request(url, args=None, data=None, headers=None, method=None, credentials=None, raw_response=False, stats=None):\n \"\"\"Issues HTTP requests.\n \n Args:\n url: the URL to request.\n args: optional query string arguments.\n data: optional data to be sent within the request.\n headers: optional headers to include in the request.\n method: optional HTTP method to use. If unspecified this is inferred\n (GET or POST) based on the existence of request data.\n credentials: optional set of credentials to authorize the request.\n raw_response: whether the raw response content should be returned as-is.\n stats: an optional dictionary that, if provided, will be populated with some\n useful info about the request, like 'duration' in seconds and 'data_size' in\n bytes. These may be useful optimizing the access to rate-limited APIs.\n Returns:\n The parsed response object.\n Raises:\n Exception when the HTTP request fails or the response cannot be processed.\n \"\"\"\n if headers is None:\n headers = {}\n headers['user-agent'] = 'GoogleCloudDataLab/1.0'\n if args is not None:\n qs = urllib.parse.urlencode(args)\n url = url + '?' + qs\n if data is not None:\n if method is None:\n method = 'POST'\n if data != '':\n if 'Content-Type' not in headers:\n data = json.dumps(data)\n headers['Content-Type'] = 'application/json'\n headers['Content-Length'] = str(len(data))\n elif method == 'POST':\n headers['Content-Length'] = '0'\n if method is None:\n method = 'GET'\n http = Http.http\n if credentials is not None:\n http = copy.copy(http)\n http = google_auth_httplib2.AuthorizedHttp(credentials)\n if stats is not None:\n stats['duration'] = datetime.datetime.utcnow()\n response = None\n try:\n log.debug('request: method[%(method)s], url[%(url)s], body[%(data)s]' % locals())\n response, content = http.request(url, method=method, body=data, headers=headers)\n if 200 <= response.status < 300:\n if raw_response:\n return content\n if type(content) == str:\n return json.loads(content)\n else:\n return json.loads(str(content, encoding='UTF-8'))\n else:\n raise RequestException(response.status, content)\n except ValueError:\n raise Exception('Failed to process HTTP response.')\n except httplib2.HttpLib2Error:\n raise Exception('Failed to send HTTP request.')\n finally:\n if stats is not None:\n stats['data_size'] = len(data)\n stats['status'] = response.status\n stats['duration'] = (datetime.datetime.utcnow() - stats['duration']).total_seconds()\n ", "context": "class Http(object):\n @staticmethod\n def request(url, args=None, data=None, headers=None, method=None, credentials=None, raw_response=False, stats=None): ...\n def __init__(self): ...\n\n http = httplib2.Http()\n http.disable_ssl_certificate_validation = True\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001312.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "jobs_insert_load", "tests": "import unittest\n\nclass Test_jobs_insert_load(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_jobs_insert_load(self, mock_http_request):\n api = TestCases._create_api()\n api.jobs_insert_load('SOURCE', datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n self.maxDiff = None\n expected_data = {'kind': 'bigquery#job', 'configuration': {'load': {'sourceUris': ['SOURCE'], 'destinationTable': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'createDisposition': 'CREATE_NEVER', 'writeDisposition': 'WRITE_EMPTY', 'sourceFormat': 'CSV', 'fieldDelimiter': ',', 'allowJaggedRows': False, 'allowQuotedNewlines': False, 'encoding': 'UTF-8', 'ignoreUnknownValues': False, 'maxBadRecords': 0, 'quote': '\"', 'skipLeadingRows': 0}}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/jobs/', expected_data=expected_data)\n api.jobs_insert_load('SOURCE2', datalab.bigquery._utils.TableName('p2', 'd2', 't2', ''), append=True, create=True, allow_jagged_rows=True, allow_quoted_newlines=True, ignore_unknown_values=True, source_format='JSON', max_bad_records=1)\n expected_data = {'kind': 'bigquery#job', 'configuration': {'load': {'sourceUris': ['SOURCE2'], 'destinationTable': {'projectId': 'p2', 'datasetId': 'd2', 'tableId': 't2'}, 'createDisposition': 'CREATE_IF_NEEDED', 'writeDisposition': 'WRITE_APPEND', 'sourceFormat': 'JSON', 'ignoreUnknownValues': True, 'maxBadRecords': 1}}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p2/jobs/', expected_data=expected_data)\n", "method_code": " def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0):\n \"\"\" Issues a request to load data from GCS to a BQ table\n \n Args:\n source: the URL of the source bucket(s). Can include wildcards, and can be a single\n string argument or a list.\n table_name: a tuple representing the full name of the destination table.\n append: if True append onto existing table contents.\n overwrite: if True overwrite existing table contents.\n create: if True, create the table if it doesn't exist\n source_format: the format of the data; default 'CSV'. Other options are DATASTORE_BACKUP\n or NEWLINE_DELIMITED_JSON.\n field_delimiter: The separator for fields in a CSV file. BigQuery converts the string to\n ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data\n as raw binary (default ',').\n allow_jagged_rows: If True, accept rows in CSV files that are missing trailing optional\n columns; the missing values are treated as nulls (default False).\n allow_quoted_newlines: If True, allow quoted data sections in CSV files that contain newline\n characters (default False).\n encoding: The character encoding of the data, either 'UTF-8' (the default) or 'ISO-8859-1'.\n ignore_unknown_values: If True, accept rows that contain values that do not match the schema;\n the unknown values are ignored (default False).\n max_bad_records: The maximum number of bad records that are allowed (and ignored) before\n returning an 'invalid' error in the Job result (default 0).\n quote: The value used to quote data sections in a CSV file; default '\"'. If your data does\n not contain quoted sections, set the property value to an empty string. If your data\n contains quoted newline characters, you must also enable allow_quoted_newlines.\n skip_leading_rows: A number of rows at the top of a CSV file to skip (default 0).\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._JOBS_PATH % (table_name.project_id, '')\n if isinstance(source, basestring):\n source = [source]\n write_disposition = 'WRITE_EMPTY'\n if overwrite:\n write_disposition = 'WRITE_TRUNCATE'\n if append:\n write_disposition = 'WRITE_APPEND'\n data = {'kind': 'bigquery#job', 'configuration': {'load': {'sourceUris': source, 'destinationTable': {'projectId': table_name.project_id, 'datasetId': table_name.dataset_id, 'tableId': table_name.table_id}, 'createDisposition': 'CREATE_IF_NEEDED' if create else 'CREATE_NEVER', 'writeDisposition': write_disposition, 'sourceFormat': source_format, 'ignoreUnknownValues': ignore_unknown_values, 'maxBadRecords': max_bad_records}}}\n if source_format == 'CSV':\n load_config = data['configuration']['load']\n load_config.update({'fieldDelimiter': field_delimiter, 'allowJaggedRows': allow_jagged_rows, 'allowQuotedNewlines': allow_quoted_newlines, 'quote': quote, 'encoding': encoding, 'skipLeadingRows': skip_leading_rows})\n return datalab.utils.Http.request(url, data=data, credentials=self._credentials)\n ", "context": "class Api(object):\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001313.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "jobs_insert_query", "tests": "import unittest\n\nclass Test_jobs_insert_query(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_jobs_insert_query(self, mock_http_request):\n api = TestCases._create_api()\n api.jobs_insert_query('SQL')\n expected_data = {'kind': 'bigquery#job', 'configuration': {'query': {'query': 'SQL', 'useQueryCache': True, 'userDefinedFunctionResources': [], 'allowLargeResults': False, 'useLegacySql': True}, 'dryRun': False, 'priority': 'BATCH'}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/test/jobs/', expected_data=expected_data)\n api.jobs_insert_query('SQL2', ['CODE'], table_name=datalab.bigquery._utils.TableName('p', 'd', 't', ''), append=True, dry_run=True, use_cache=False, batch=False, allow_large_results=True, dialect='standard', billing_tier=1)\n expected_data = {'kind': 'bigquery#job', 'configuration': {'query': {'query': 'SQL2', 'useQueryCache': False, 'allowLargeResults': True, 'useLegacySql': False, 'maximumBillingTier': 1, 'destinationTable': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'writeDisposition': 'WRITE_APPEND', 'userDefinedFunctionResources': [{'inlineCode': 'CODE'}]}, 'dryRun': True, 'priority': 'INTERACTIVE'}}\n self.maxDiff = None\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/test/jobs/', expected_data=expected_data)\n", "method_code": " def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None):\n \"\"\"Issues a request to insert a query job.\n \n Args:\n sql: the SQL string representing the query to execute.\n code: code for Javascript UDFs, if any.\n imports: a list of GCS URLs containing additional Javascript UDF support code, if any.\n table_name: None for an anonymous table, or a name parts tuple for a long-lived table.\n append: if True, append to the table if it is non-empty; else the request will fail if table\n is non-empty unless overwrite is True.\n overwrite: if the table already exists, truncate it instead of appending or raising an\n Exception.\n dry_run: whether to actually execute the query or just dry run it.\n use_cache: whether to use past query results or ignore cache. Has no effect if destination is\n specified.\n batch: whether to run this as a batch job (lower priority) or as an interactive job (high\n priority, more expensive).\n allow_large_results: whether to allow large results (slower with some restrictions but\n can handle big jobs).\n table_definitions: a list of JSON external table definitions for any external tables\n referenced in the query.\n dialect : {'legacy', 'standard'}, default 'legacy'\n 'legacy' : Use BigQuery's legacy SQL dialect.\n 'standard' : Use BigQuery's standard SQL (beta), which is\n compliant with the SQL 2011 standard.\n billing_tier: Limits the billing tier for this job. Queries that have resource\n usage beyond this tier will fail (without incurring a charge). If unspecified, this\n will be set to your project default. This can also be used to override your\n project-wide default billing tier on a per-query basis.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._JOBS_PATH % (self._project_id, '')\n if dialect is None:\n dialect = datalab.bigquery.Dialect.default().bq_dialect\n data = {'kind': 'bigquery#job', 'configuration': {'query': {'query': sql, 'useQueryCache': use_cache, 'allowLargeResults': allow_large_results, 'useLegacySql': dialect == 'legacy'}, 'dryRun': dry_run, 'priority': 'BATCH' if batch else 'INTERACTIVE'}}\n query_config = data['configuration']['query']\n resources = []\n if code:\n resources.extend([{'inlineCode': fragment} for fragment in code])\n if imports:\n resources.extend([{'resourceUri': uri} for uri in imports])\n query_config['userDefinedFunctionResources'] = resources\n if table_definitions:\n query_config['tableDefinitions'] = table_definitions\n if table_name:\n query_config['destinationTable'] = {'projectId': table_name.project_id, 'datasetId': table_name.dataset_id, 'tableId': table_name.table_id}\n if append:\n query_config['writeDisposition'] = 'WRITE_APPEND'\n elif overwrite:\n query_config['writeDisposition'] = 'WRITE_TRUNCATE'\n if billing_tier:\n query_config['maximumBillingTier'] = billing_tier\n return datalab.utils.Http.request(url, data=data, credentials=self._credentials)\n ", "context": "class Api(object):\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001314.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "jobs_query_results", "tests": "import unittest\n\nclass Test_jobs_query_results(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_jobs_query_results(self, mock_http_request):\n api = TestCases._create_api()\n api.jobs_query_results('JOB', 'PROJECT', 10, 20, 30)\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/PROJECT/queries/JOB', expected_args={'maxResults': 10, 'timeoutMs': 20, 'startIndex': 30})\n", "method_code": " def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0):\n \"\"\"Issues a request to the jobs/getQueryResults method.\n \n Args:\n job_id: the id of job from a previously executed query.\n project_id: the project id to use to fetch the results; use None for the default project.\n page_size: limit to the number of rows to fetch.\n timeout: duration (in milliseconds) to wait for the query to complete.\n start_index: the index of the row (0-based) at which to start retrieving the page of result\n rows.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if timeout is None:\n timeout = Api._DEFAULT_TIMEOUT\n if project_id is None:\n project_id = self._project_id\n args = {'maxResults': page_size, 'timeoutMs': timeout, 'startIndex': start_index}\n url = Api._ENDPOINT + Api._QUERIES_PATH % (project_id, job_id)\n return datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001315.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "jobs_get", "tests": "import unittest\n\nclass Test_jobs_get(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_jobs_get(self, mock_http_request):\n api = TestCases._create_api()\n api.jobs_get('JOB', 'PROJECT')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/PROJECT/jobs/JOB')\n", "method_code": " def jobs_get(self, job_id, project_id=None):\n \"\"\"Issues a request to retrieve information about a job.\n \n Args:\n job_id: the id of the job\n project_id: the project id to use to fetch the results; use None for the default project.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if project_id is None:\n project_id = self._project_id\n url = Api._ENDPOINT + Api._JOBS_PATH % (project_id, job_id)\n return datalab.utils.Http.request(url, credentials=self._credentials)\n ", "context": "class Api(object):\n def jobs_get(self, job_id, project_id=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001316.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_insert", "tests": "import unittest\n\nclass Test_datasets_insert(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_datasets_insert(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_insert(datalab.bigquery._utils.DatasetName('p', 'd'))\n expected_data = {'kind': 'bigquery#dataset', 'datasetReference': {'projectId': 'p', 'datasetId': 'd'}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/', expected_data=expected_data)\n api.datasets_insert(datalab.bigquery._utils.DatasetName('p', 'd'), 'FRIENDLY', 'DESCRIPTION')\n expected_data = {'kind': 'bigquery#dataset', 'datasetReference': {'projectId': 'p', 'datasetId': 'd'}, 'friendlyName': 'FRIENDLY', 'description': 'DESCRIPTION'}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/', expected_data=expected_data)\n", "method_code": " def datasets_insert(self, dataset_name, friendly_name=None, description=None):\n \"\"\"Issues a request to create a dataset.\n \n Args:\n dataset_name: the name of the dataset to create.\n friendly_name: (optional) the friendly name for the dataset\n description: (optional) a description for the dataset\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._DATASETS_PATH % (dataset_name.project_id, '')\n data = {'kind': 'bigquery#dataset', 'datasetReference': {'projectId': dataset_name.project_id, 'datasetId': dataset_name.dataset_id}}\n if friendly_name:\n data['friendlyName'] = friendly_name\n if description:\n data['description'] = description\n return datalab.utils.Http.request(url, data=data, credentials=self._credentials)\n ", "context": "class Api(object):\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001317.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_delete", "tests": "import unittest\n\nclass Test_datasets_delete(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_datasets_delete(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_delete(datalab.bigquery._utils.DatasetName('p', 'd'), False)\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d', expected_args={}, expected_method='DELETE')\n api.datasets_delete(datalab.bigquery._utils.DatasetName('p', 'd'), True)\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d', expected_args={'deleteContents': True}, expected_method='DELETE')\n", "method_code": " def datasets_delete(self, dataset_name, delete_contents):\n \"\"\"Issues a request to delete a dataset.\n \n Args:\n dataset_name: the name of the dataset to delete.\n delete_contents: if True, any tables in the dataset will be deleted. If False and the\n dataset is non-empty an exception will be raised.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._DATASETS_PATH % dataset_name\n args = {}\n if delete_contents:\n args['deleteContents'] = True\n return datalab.utils.Http.request(url, method='DELETE', args=args, credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def datasets_delete(self, dataset_name, delete_contents): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001318.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_update", "tests": "import unittest\n\nclass Test_datasets_update(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_datasets_update(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_update(datalab.bigquery._utils.DatasetName('p', 'd'), 'INFO')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d', expected_method='PUT', expected_data='INFO')\n", "method_code": " def datasets_update(self, dataset_name, dataset_info):\n \"\"\"Updates the Dataset info.\n \n Args:\n dataset_name: the name of the dataset to update as a tuple of components.\n dataset_info: the Dataset resource with updated fields.\n \"\"\"\n url = Api._ENDPOINT + Api._DATASETS_PATH % dataset_name\n return datalab.utils.Http.request(url, method='PUT', data=dataset_info, credentials=self._credentials)\n ", "context": "class Api(object):\n def datasets_update(self, dataset_name, dataset_info): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001319.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_get", "tests": "import unittest\n\nclass Test_datasets_get(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_datasets_get(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_get(datalab.bigquery._utils.DatasetName('p', 'd'))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d')\n", "method_code": " def datasets_get(self, dataset_name):\n \"\"\"Issues a request to retrieve information about a dataset.\n \n Args:\n dataset_name: the name of the dataset\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._DATASETS_PATH % dataset_name\n return datalab.utils.Http.request(url, credentials=self._credentials)\n ", "context": "class Api(object):\n def datasets_get(self, dataset_name): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001320.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_list", "tests": "import unittest\n\nclass Test_datasets_list(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_datasets_list(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_list()\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/test/datasets/', expected_args={})\n api.datasets_list('PROJECT', 10, 'TOKEN')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/PROJECT/datasets/', expected_args={'maxResults': 10, 'pageToken': 'TOKEN'})\n", "method_code": " def datasets_list(self, project_id=None, max_results=0, page_token=None):\n \"\"\"Issues a request to list the datasets in the project.\n \n Args:\n project_id: the project id to use to fetch the results; use None for the default project.\n max_results: an optional maximum number of tables to retrieve.\n page_token: an optional token to continue the retrieval.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if project_id is None:\n project_id = self._project_id\n url = Api._ENDPOINT + Api._DATASETS_PATH % (project_id, '')\n args = {}\n if max_results != 0:\n args['maxResults'] = max_results\n if page_token is not None:\n args['pageToken'] = page_token\n return datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001321.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tables_get", "tests": "import unittest\n\nclass Test_tables_get(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_tables_get(self, mock_http_request):\n api = TestCases._create_api()\n api.tables_get(datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t')\n", "method_code": " def tables_get(self, table_name):\n \"\"\"Issues a request to retrieve information about a table.\n \n Args:\n table_name: a tuple representing the full name of the table.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % table_name\n return datalab.utils.Http.request(url, credentials=self._credentials)\n ", "context": "class Api(object):\n def tables_get(self, table_name): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001322.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tables_list", "tests": "import unittest\n\nclass Test_tables_list(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_tables_list(self, mock_http_request):\n api = TestCases._create_api()\n api.tables_list(datalab.bigquery._utils.DatasetName('p', 'd'))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/', expected_args={})\n api.tables_list(datalab.bigquery._utils.DatasetName('p', 'd'), 10, 'TOKEN')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/', expected_args={'maxResults': 10, 'pageToken': 'TOKEN'})\n", "method_code": " def tables_list(self, dataset_name, max_results=0, page_token=None):\n \"\"\"Issues a request to retrieve a list of tables.\n \n Args:\n dataset_name: the name of the dataset to enumerate.\n max_results: an optional maximum number of tables to retrieve.\n page_token: an optional token to continue the retrieval.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % (dataset_name.project_id, dataset_name.dataset_id, '', '')\n args = {}\n if max_results != 0:\n args['maxResults'] = max_results\n if page_token is not None:\n args['pageToken'] = page_token\n return datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001323.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tables_insert", "tests": "import unittest\n\nclass Test_tables_insert(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_tables_insert(self, mock_http_request):\n api = TestCases._create_api()\n api.tables_insert(datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n expected_data = {'kind': 'bigquery#table', 'tableReference': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/', expected_data=expected_data)\n api.tables_insert(datalab.bigquery._utils.TableName('p', 'd', 't', ''), 'SCHEMA', 'QUERY', 'FRIENDLY', 'DESCRIPTION')\n expected_data = {'kind': 'bigquery#table', 'tableReference': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'schema': {'fields': 'SCHEMA'}, 'view': {'query': 'QUERY'}, 'friendlyName': 'FRIENDLY', 'description': 'DESCRIPTION'}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/', expected_data=expected_data)\n", "method_code": " def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None):\n \"\"\"Issues a request to create a table or view in the specified dataset with the specified id.\n A schema must be provided to create a Table, or a query must be provided to create a View.\n \n Args:\n table_name: the name of the table as a tuple of components.\n schema: the schema, if this is a Table creation.\n query: the query, if this is a View creation.\n friendly_name: an optional friendly name.\n description: an optional description.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % (table_name.project_id, table_name.dataset_id, '', '')\n data = {'kind': 'bigquery#table', 'tableReference': {'projectId': table_name.project_id, 'datasetId': table_name.dataset_id, 'tableId': table_name.table_id}}\n if schema:\n data['schema'] = {'fields': schema}\n if query:\n data['view'] = {'query': query}\n if friendly_name:\n data['friendlyName'] = friendly_name\n if description:\n data['description'] = description\n return datalab.utils.Http.request(url, data=data, credentials=self._credentials)\n ", "context": "class Api(object):\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001324.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tabledata_insert_all", "tests": "import unittest\n\nclass Test_tabledata_insert_all(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_tabledata_insertAll(self, mock_http_request):\n api = TestCases._create_api()\n api.tabledata_insert_all(datalab.bigquery._utils.TableName('p', 'd', 't', ''), 'ROWS')\n expected_data = {'kind': 'bigquery#tableDataInsertAllRequest', 'rows': 'ROWS'}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t/insertAll', expected_data=expected_data)\n", "method_code": " def tabledata_insert_all(self, table_name, rows):\n \"\"\"Issues a request to insert data into a table.\n \n Args:\n table_name: the name of the table as a tuple of components.\n rows: the data to populate the table, as a list of dictionaries.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % table_name + '/insertAll'\n data = {'kind': 'bigquery#tableDataInsertAllRequest', 'rows': rows}\n return datalab.utils.Http.request(url, data=data, credentials=self._credentials)\n ", "context": "class Api(object):\n def tabledata_insert_all(self, table_name, rows): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001325.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tabledata_list", "tests": "import unittest\n\nclass Test_tabledata_list(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_tabledata_list(self, mock_http_request):\n api = TestCases._create_api()\n api.tabledata_list(datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t/data', expected_args={})\n api.tabledata_list(datalab.bigquery._utils.TableName('p', 'd', 't', ''), 10, 20, 'TOKEN')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t/data', expected_args={'startIndex': 10, 'maxResults': 20, 'pageToken': 'TOKEN'})\n", "method_code": " def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None):\n \"\"\" Retrieves the contents of a table.\n \n Args:\n table_name: the name of the table as a tuple of components.\n start_index: the index of the row at which to start retrieval.\n max_results: an optional maximum number of rows to retrieve.\n page_token: an optional token to continue the retrieval.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLEDATA_PATH % table_name\n args = {}\n if start_index:\n args['startIndex'] = start_index\n if max_results:\n args['maxResults'] = max_results\n if page_token is not None:\n args['pageToken'] = page_token\n return datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001326.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "table_delete", "tests": "import unittest\n\nclass Test_table_delete(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_table_delete(self, mock_http_request):\n api = TestCases._create_api()\n api.table_delete(datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t', expected_method='DELETE')\n", "method_code": " def table_delete(self, table_name):\n \"\"\"Issues a request to delete a table.\n \n Args:\n table_name: the name of the table as a tuple of components.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % table_name\n return datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def table_delete(self, table_name): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001327.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "table_extract", "tests": "import unittest\n\nclass Test_table_extract(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_table_extract(self, mock_http_request):\n api = TestCases._create_api()\n api.table_extract(datalab.bigquery._utils.TableName('p', 'd', 't', ''), 'DEST')\n expected_data = {'kind': 'bigquery#job', 'configuration': {'extract': {'sourceTable': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'compression': 'GZIP', 'fieldDelimiter': ',', 'printHeader': True, 'destinationUris': ['DEST'], 'destinationFormat': 'CSV'}}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/jobs/', expected_data=expected_data)\n api.table_extract(datalab.bigquery._utils.TableName('p', 'd', 't', ''), ['DEST'], format='JSON', compress=False, field_delimiter=':', print_header=False)\n expected_data = {'kind': 'bigquery#job', 'configuration': {'extract': {'sourceTable': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'compression': 'NONE', 'fieldDelimiter': ':', 'printHeader': False, 'destinationUris': ['DEST'], 'destinationFormat': 'JSON'}}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/jobs/', expected_data=expected_data)\n", "method_code": " def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True):\n \"\"\"Exports the table to GCS.\n \n Args:\n table_name: the name of the table as a tuple of components.\n destination: the destination URI(s). Can be a single URI or a list.\n format: the format to use for the exported data; one of CSV, NEWLINE_DELIMITED_JSON or AVRO.\n Defaults to CSV.\n compress: whether to compress the data on export. Compression is not supported for\n AVRO format. Defaults to False.\n field_delimiter: for CSV exports, the field delimiter to use. Defaults to ','\n print_header: for CSV exports, whether to include an initial header line. Default true.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._JOBS_PATH % (table_name.project_id, '')\n if isinstance(destination, basestring):\n destination = [destination]\n data = {'kind': 'bigquery#job', 'configuration': {'extract': {'sourceTable': {'projectId': table_name.project_id, 'datasetId': table_name.dataset_id, 'tableId': table_name.table_id}, 'compression': 'GZIP' if compress else 'NONE', 'fieldDelimiter': field_delimiter, 'printHeader': print_header, 'destinationUris': destination, 'destinationFormat': format}}}\n return datalab.utils.Http.request(url, data=data, credentials=self._credentials)\n ", "context": "class Api(object):\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_update(self, table_name, table_info): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001328.py"} {"focal_file": "datalab/bigquery/_api.py", "focal_class": null, "focal_method": "table_update", "tests": "import unittest\n\nclass Test_table_update(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_table_update(self, mock_http_request):\n api = TestCases._create_api()\n api.table_update(datalab.bigquery._utils.TableName('p', 'd', 't', ''), 'INFO')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t', expected_method='PUT', expected_data='INFO')\n", "method_code": " def table_update(self, table_name, table_info):\n \"\"\"Updates the Table info.\n \n Args:\n table_name: the name of the table to update as a tuple of components.\n table_info: the Table resource with updated fields.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % table_name\n return datalab.utils.Http.request(url, method='PUT', data=table_info, credentials=self._credentials)\n ", "context": "class Api(object):\n def table_update(self, table_name, table_info): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, dialect=None, billing_tier=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001329.py"} {"focal_file": "datalab/stackdriver/commands/_monitoring.py", "focal_class": null, "focal_method": "_list_metric_descriptors", "tests": "import unittest\n\nclass Test_list_metric_descriptors(unittest.TestCase):\n @mock.patch('datalab.stackdriver.commands._monitoring._render_dataframe')\n @mock.patch('datalab.stackdriver.monitoring.MetricDescriptors')\n def test_list_metric_descriptors(self, mock_metric_descriptors, mock_render_dataframe):\n METRIC_TYPES = ['compute.googleapis.com/instances/cpu/utilization', 'compute.googleapis.com/instances/cpu/usage_time']\n DATAFRAME = pandas.DataFrame(METRIC_TYPES, columns=['Metric type'])\n PATTERN = 'compute*cpu*'\n mock_metric_class = mock_metric_descriptors.return_value\n mock_metric_class.as_dataframe.return_value = DATAFRAME\n monitoring_commands._list_metric_descriptors({'project': PROJECT, 'type': PATTERN}, None)\n mock_metric_descriptors.assert_called_once_with(project_id=PROJECT)\n mock_metric_class.as_dataframe.assert_called_once_with(pattern=PATTERN)\n mock_render_dataframe.assert_called_once_with(DATAFRAME)\n", "method_code": "def _list_metric_descriptors(args, _):\n \"\"\"Lists the metric descriptors in the project.\"\"\"\n project_id = args['project']\n pattern = args['type'] or '*'\n descriptors = gcm.MetricDescriptors(project_id=project_id)\n dataframe = descriptors.as_dataframe(pattern=pattern)\n return _render_dataframe(dataframe)", "context": "def _list_metric_descriptors(args, _): ...\ndef monitoring(line, cell=None): ...\ndef _list_metric_descriptors(args, _): ...\ndef _list_resource_descriptors(args, _): ...\ndef _list_groups(args, _): ...\ndef _render_dataframe(dataframe): ...\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001330.py"} {"focal_file": "datalab/stackdriver/commands/_monitoring.py", "focal_class": null, "focal_method": "_list_resource_descriptors", "tests": "import unittest\n\nclass Test_list_resource_descriptors(unittest.TestCase):\n @mock.patch('datalab.stackdriver.commands._monitoring._render_dataframe')\n @mock.patch('datalab.stackdriver.monitoring.ResourceDescriptors')\n def test_list_resource_descriptors(self, mock_resource_descriptors, mock_render_dataframe):\n RESOURCE_TYPES = ['gce_instance', 'aws_ec2_instance']\n DATAFRAME = pandas.DataFrame(RESOURCE_TYPES, columns=['Resource type'])\n PATTERN = '*instance*'\n mock_resource_class = mock_resource_descriptors.return_value\n mock_resource_class.as_dataframe.return_value = DATAFRAME\n monitoring_commands._list_resource_descriptors({'project': PROJECT, 'type': PATTERN}, None)\n mock_resource_descriptors.assert_called_once_with(project_id=PROJECT)\n mock_resource_class.as_dataframe.assert_called_once_with(pattern=PATTERN)\n mock_render_dataframe.assert_called_once_with(DATAFRAME)\n", "method_code": "def _list_resource_descriptors(args, _):\n \"\"\"Lists the resource descriptors in the project.\"\"\"\n project_id = args['project']\n pattern = args['type'] or '*'\n descriptors = gcm.ResourceDescriptors(project_id=project_id)\n dataframe = descriptors.as_dataframe(pattern=pattern)\n return _render_dataframe(dataframe)", "context": "def _list_resource_descriptors(args, _): ...\ndef monitoring(line, cell=None): ...\ndef _list_metric_descriptors(args, _): ...\ndef _list_resource_descriptors(args, _): ...\ndef _list_groups(args, _): ...\ndef _render_dataframe(dataframe): ...\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001331.py"} {"focal_file": "datalab/stackdriver/commands/_monitoring.py", "focal_class": null, "focal_method": "_list_groups", "tests": "import unittest\n\nclass Test_list_groups(unittest.TestCase):\n @mock.patch('datalab.stackdriver.commands._monitoring._render_dataframe')\n @mock.patch('datalab.stackdriver.monitoring.Groups')\n def test_list_groups(self, mock_groups, mock_render_dataframe):\n GROUP_IDS = ['GROUP-205', 'GROUP-101']\n DATAFRAME = pandas.DataFrame(GROUP_IDS, columns=['Group ID'])\n PATTERN = 'GROUP-*'\n mock_group_class = mock_groups.return_value\n mock_group_class.as_dataframe.return_value = DATAFRAME\n monitoring_commands._list_groups({'project': PROJECT, 'name': PATTERN}, None)\n mock_groups.assert_called_once_with(project_id=PROJECT)\n mock_group_class.as_dataframe.assert_called_once_with(pattern=PATTERN)\n mock_render_dataframe.assert_called_once_with(DATAFRAME)\n", "method_code": "def _list_groups(args, _):\n \"\"\"Lists the groups in the project.\"\"\"\n project_id = args['project']\n pattern = args['name'] or '*'\n groups = gcm.Groups(project_id=project_id)\n dataframe = groups.as_dataframe(pattern=pattern)\n return _render_dataframe(dataframe)", "context": "def _list_groups(args, _): ...\ndef monitoring(line, cell=None): ...\ndef _list_metric_descriptors(args, _): ...\ndef _list_resource_descriptors(args, _): ...\ndef _list_groups(args, _): ...\ndef _render_dataframe(dataframe): ...\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001332.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "buckets_insert", "tests": "import unittest\n\nclass Test_buckets_insert(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_buckets_insert(self, mock_http_request):\n api = TestCases._create_api()\n api.buckets_insert('foo')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/', expected_args={'project': 'test'}, expected_data={'name': 'foo'})\n api.buckets_insert('foo', 'bar')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/', expected_args={'project': 'bar'}, expected_data={'name': 'foo'})\n", "method_code": " def buckets_insert(self, bucket, project_id=None):\n \"\"\"Issues a request to create a new bucket.\n \n Args:\n bucket: the name of the bucket.\n project_id: the project to use when inserting the bucket.\n Returns:\n A parsed bucket information dictionary.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n args = {'project': project_id if project_id else self._project_id}\n data = {'name': bucket}\n url = Api._ENDPOINT + Api._BUCKET_PATH % ''\n return datalab.utils.Http.request(url, args=args, data=data, credentials=self._credentials)\n ", "context": "class Api(object):\n def buckets_insert(self, bucket, project_id=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001333.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "buckets_delete", "tests": "import unittest\n\nclass Test_buckets_delete(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_buckets_delete(self, mock_http_request):\n api = TestCases._create_api()\n api.buckets_delete('foo')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/foo', expected_method='DELETE')\n", "method_code": " def buckets_delete(self, bucket):\n \"\"\"Issues a request to delete a bucket.\n \n Args:\n bucket: the name of the bucket.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._BUCKET_PATH % bucket\n datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def buckets_delete(self, bucket): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001334.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "buckets_get", "tests": "import unittest\n\nclass Test_buckets_get(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_buckets_get(self, mock_http_request):\n api = TestCases._create_api()\n api.buckets_get('foo')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/foo', expected_args={'projection': 'noAcl'})\n api.buckets_get('foo', 'bar')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/foo', expected_args={'projection': 'bar'})\n", "method_code": " def buckets_get(self, bucket, projection='noAcl'):\n \"\"\"Issues a request to retrieve information about a bucket.\n \n Args:\n bucket: the name of the bucket.\n projection: the projection of the bucket information to retrieve.\n Returns:\n A parsed bucket information dictionary.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n args = {'projection': projection}\n url = Api._ENDPOINT + Api._BUCKET_PATH % bucket\n return datalab.utils.Http.request(url, credentials=self._credentials, args=args)\n ", "context": "class Api(object):\n def buckets_get(self, bucket, projection='noAcl'): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001335.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "buckets_list", "tests": "import unittest\n\nclass Test_buckets_list(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_buckets_list(self, mock_http_request):\n api = TestCases._create_api()\n api.buckets_list()\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/', expected_args={'project': 'test', 'projection': 'noAcl', 'maxResults': 100})\n api.buckets_list(projection='foo', max_results=99, page_token='xyz', project_id='bar')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/', expected_args={'project': 'bar', 'maxResults': 99, 'projection': 'foo', 'pageToken': 'xyz'})\n", "method_code": " def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None):\n \"\"\"Issues a request to retrieve the list of buckets.\n \n Args:\n projection: the projection of the bucket information to retrieve.\n max_results: an optional maximum number of objects to retrieve.\n page_token: an optional token to continue the retrieval.\n project_id: the project whose buckets should be listed.\n Returns:\n A parsed list of bucket information dictionaries.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if max_results == 0:\n max_results = Api._MAX_RESULTS\n args = {'project': project_id if project_id else self._project_id, 'maxResults': max_results}\n if projection is not None:\n args['projection'] = projection\n if page_token is not None:\n args['pageToken'] = page_token\n url = Api._ENDPOINT + Api._BUCKET_PATH % ''\n return datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001336.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "object_download", "tests": "import unittest\n\nclass Test_object_download(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_object_download(self, mock_http_request):\n api = TestCases._create_api()\n api.object_download('foo', 'bar')\n self.validate(mock_http_request, 'https://www.googleapis.com/download/storage/v1/b/foo/o/bar', expected_args={'alt': 'media'})\n", "method_code": " def object_download(self, bucket, key, start_offset=0, byte_count=None):\n \"\"\"Reads the contents of an object as text.\n \n Args:\n bucket: the name of the bucket containing the object.\n key: the key of the object to be read.\n start_offset: the start offset of bytes to read.\n byte_count: the number of bytes to read. If None, it reads to the end.\n Returns:\n The text content within the object.\n Raises:\n Exception if the object could not be read from.\n \"\"\"\n args = {'alt': 'media'}\n headers = {}\n if start_offset > 0 or byte_count is not None:\n header = 'bytes=%d-' % start_offset\n if byte_count is not None:\n header += '%d' % byte_count\n headers['Range'] = header\n url = Api._DOWNLOAD_ENDPOINT + Api._OBJECT_PATH % (bucket, Api._escape_key(key))\n return datalab.utils.Http.request(url, args=args, headers=headers, credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001337.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "object_upload", "tests": "import unittest\n\nclass Test_object_upload(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_object_upload(self, mock_http_request):\n api = TestCases._create_api()\n api.object_upload('b', 'k', 'c', 't')\n self.validate(mock_http_request, 'https://www.googleapis.com/upload/storage/v1/b/b/o/', expected_args={'uploadType': 'media', 'name': 'k'}, expected_data='c', expected_headers={'Content-Type': 't'})\n", "method_code": " def object_upload(self, bucket, key, content, content_type):\n \"\"\"Writes text content to the object.\n \n Args:\n bucket: the name of the bucket containing the object.\n key: the key of the object to be written.\n content: the text content to be written.\n content_type: the type of text content.\n Raises:\n Exception if the object could not be written to.\n \"\"\"\n args = {'uploadType': 'media', 'name': key}\n headers = {'Content-Type': content_type}\n url = Api._UPLOAD_ENDPOINT + Api._OBJECT_PATH % (bucket, '')\n return datalab.utils.Http.request(url, args=args, data=content, headers=headers, credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def object_upload(self, bucket, key, content, content_type): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001338.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_copy", "tests": "import unittest\n\nclass Test_objects_copy(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_objects_copy(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_copy('sb', 'sk', 'tb', 'tk')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/sb/o/sk/copyTo/b/tb/o/tk', expected_method='POST')\n", "method_code": " def objects_copy(self, source_bucket, source_key, target_bucket, target_key):\n \"\"\"Updates the metadata associated with an object.\n \n Args:\n source_bucket: the name of the bucket containing the source object.\n source_key: the key of the source object being copied.\n target_bucket: the name of the bucket that will contain the copied object.\n target_key: the key of the copied object.\n Returns:\n A parsed object information dictionary.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._OBJECT_COPY_PATH % (source_bucket, Api._escape_key(source_key), target_bucket, Api._escape_key(target_key))\n return datalab.utils.Http.request(url, method='POST', credentials=self._credentials)\n ", "context": "class Api(object):\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001339.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_delete", "tests": "import unittest\n\nclass Test_objects_delete(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_objects_delete(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_delete('b', 'k')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/k', expected_method='DELETE')\n", "method_code": " def objects_delete(self, bucket, key):\n \"\"\"Deletes the specified object.\n \n Args:\n bucket: the name of the bucket.\n key: the key of the object within the bucket.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._OBJECT_PATH % (bucket, Api._escape_key(key))\n datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def objects_delete(self, bucket, key): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001340.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_get", "tests": "import unittest\n\nclass Test_objects_get(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_objects_get(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_get('b', 'k')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/k', expected_args={'projection': 'noAcl'})\n api.objects_get('b', 'k', 'p')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/k', expected_args={'projection': 'p'})\n", "method_code": " def objects_get(self, bucket, key, projection='noAcl'):\n \"\"\"Issues a request to retrieve information about an object.\n \n Args:\n bucket: the name of the bucket.\n key: the key of the object within the bucket.\n projection: the projection of the object to retrieve.\n Returns:\n A parsed object information dictionary.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n args = {}\n if projection is not None:\n args['projection'] = projection\n url = Api._ENDPOINT + Api._OBJECT_PATH % (bucket, Api._escape_key(key))\n return datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001341.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_list", "tests": "import unittest\n\nclass Test_objects_list(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_objects_list(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_list('b')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/', expected_args={'projection': 'noAcl', 'maxResults': 100})\n api.objects_list('b', 'p', 'd', 'pr', True, 99, 'foo')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/', expected_args={'projection': 'pr', 'maxResults': 99, 'prefix': 'p', 'delimiter': 'd', 'versions': 'true', 'pageToken': 'foo'})\n", "method_code": " def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None):\n \"\"\"Issues a request to retrieve information about an object.\n \n Args:\n bucket: the name of the bucket.\n prefix: an optional key prefix.\n delimiter: an optional key delimiter.\n projection: the projection of the objects to retrieve.\n versions: whether to list each version of a file as a distinct object.\n max_results: an optional maximum number of objects to retrieve.\n page_token: an optional token to continue the retrieval.\n Returns:\n A parsed list of object information dictionaries.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if max_results == 0:\n max_results = Api._MAX_RESULTS\n args = {'maxResults': max_results}\n if prefix is not None:\n args['prefix'] = prefix\n if delimiter is not None:\n args['delimiter'] = delimiter\n if projection is not None:\n args['projection'] = projection\n if versions:\n args['versions'] = 'true'\n if page_token is not None:\n args['pageToken'] = page_token\n url = Api._ENDPOINT + Api._OBJECT_PATH % (bucket, '')\n return datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001342.py"} {"focal_file": "datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_patch", "tests": "import unittest\n\nclass Test_objects_patch(unittest.TestCase):\n @mock.patch('datalab.utils.Http.request')\n def test_objects_patch(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_patch('b', 'k', 'i')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/k', expected_method='PATCH', expected_data='i')\n", "method_code": " def objects_patch(self, bucket, key, info):\n \"\"\"Updates the metadata associated with an object.\n \n Args:\n bucket: the name of the bucket containing the object.\n key: the key of the object being updated.\n info: the metadata to update.\n Returns:\n A parsed object information dictionary.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._OBJECT_PATH % (bucket, Api._escape_key(key))\n return datalab.utils.Http.request(url, method='PATCH', data=info, credentials=self._credentials)\n ", "context": "class Api(object):\n def objects_patch(self, bucket, key, info): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001343.py"} {"focal_file": "google/datalab/utils/_utils.py", "focal_class": null, "focal_method": "get_default_project_id", "tests": "import unittest\n\nclass Test_get_default_project_id(unittest.TestCase):\n @mock.patch('google.datalab.utils._utils.get_credentials')\n @mock.patch('google.datalab.utils._utils.get_default_project_id')\n @mock.patch('google.datalab.utils._utils.save_project_id')\n def test_default_project(self, mock_save_project_id, mock_get_default_project_id, mock_get_credentials):\n global default_project\n default_project = ''\n\n def save_project(project=None):\n global default_project\n default_project = project\n\n def get_project():\n global default_project\n return default_project\n mock_save_project_id.side_effect = save_project\n mock_get_default_project_id.side_effect = get_project\n mock_get_credentials.return_value = ''\n c = Context.default()\n dummy_project = 'test_project3'\n c.set_project_id(dummy_project)\n self.assertEqual(du.get_default_project_id(), dummy_project)\n\n @mock.patch('subprocess.Popen')\n @mock.patch('os.path.exists')\n def test_get_default_project_id(self, mock_path_exists, mock_subprocess_call):\n mock_subprocess_call.return_value.communicate.return_value = ('test-project', '')\n mock_subprocess_call.return_value.poll.return_value = 0\n self.assertEquals(_utils.get_default_project_id(), 'test-project')\n mock_subprocess_call.assert_called_with(['gcloud', 'config', 'list', '--format', 'value(core.project)'], stdout=-1)\n mock_subprocess_call.side_effect = Exception\n test_config = '\\n {\\n \"project_id\": \"test-project2\"\\n }\\n '\n opener = mock.mock_open(read_data=test_config)\n with mock.patch('google.datalab.utils._utils.open', opener):\n self.assertEquals(_utils.get_default_project_id(), 'test-project2')\n mock_path_exists.return_value = False\n self.assertIsNone(_utils.get_default_project_id())\n with mock.patch.dict(os.environ, {'PROJECT_ID': 'test-project3'}):\n self.assertEquals(_utils.get_default_project_id(), 'test-project3')\n", "method_code": "def get_default_project_id():\n \"\"\" Get default project id from config or environment var.\n\n Returns: the project id if available, or None.\n \"\"\"\n try:\n proc = subprocess.Popen(['gcloud', 'config', 'list', '--format', 'value(core.project)'], stdout=subprocess.PIPE)\n stdout, _ = proc.communicate()\n value = stdout.strip()\n if proc.poll() == 0 and value:\n if isinstance(value, six.string_types):\n return value\n else:\n return value.decode()\n except:\n pass\n config_file = os.path.join(get_config_dir(), 'config.json')\n if os.path.exists(config_file):\n with open(config_file) as f:\n config = json.loads(f.read())\n if 'project_id' in config and config['project_id']:\n return str(config['project_id'])\n if os.getenv('PROJECT_ID') is not None:\n return os.getenv('PROJECT_ID')\n return None", "context": "def get_default_project_id(): ...\ndef print_exception_with_last_stack(e): ...\ndef get_item(env, name, default=None): ...\ndef compare_datetimes(d1, d2): ...\ndef pick_unused_port(): ...\ndef is_http_running_on(port): ...\ndef gcs_copy_file(source, dest): ...\ndef _in_datalab_docker(): ...\ndef get_config_dir(): ...\ndef _convert_oauth2client_creds(credentials): ...\ndef get_credentials(): ...\ndef save_project_id(project_id): ...\ndef get_default_project_id(): ...\ndef _construct_context_for_args(args): ...\ndef python_portable_string(string, encoding='utf-8'): ...\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001344.py"} {"focal_file": "google/datalab/utils/_http.py", "focal_class": null, "focal_method": "request", "tests": "import unittest\n\nclass Test_request(unittest.TestCase):\n @mock.patch('httplib2.Response')\n @mock.patch('google.datalab.utils._http.Http.http.request')\n def test_formats_json_request(self, mock_request, mock_response):\n TestCases._setup_mocks(mock_request, mock_response, '{}')\n data = {'abc': 123}\n Http.request('http://www.example.org', data=data)\n self.assertEqual(mock_request.call_args[1]['body'], '{\"abc\": 123}')\n self.assertEqual(mock_request.call_args[1]['headers']['Content-Type'], 'application/json')\n", "method_code": " def request(url, args=None, data=None, headers=None, method=None, credentials=None, raw_response=False, stats=None):\n \"\"\"Issues HTTP requests.\n \n Args:\n url: the URL to request.\n args: optional query string arguments.\n data: optional data to be sent within the request.\n headers: optional headers to include in the request.\n method: optional HTTP method to use. If unspecified this is inferred\n (GET or POST) based on the existence of request data.\n credentials: optional set of credentials to authorize the request.\n raw_response: whether the raw response content should be returned as-is.\n stats: an optional dictionary that, if provided, will be populated with some\n useful info about the request, like 'duration' in seconds and 'data_size' in\n bytes. These may be useful optimizing the access to rate-limited APIs.\n Returns:\n The parsed response object.\n Raises:\n Exception when the HTTP request fails or the response cannot be processed.\n \"\"\"\n if headers is None:\n headers = {}\n headers['user-agent'] = 'GoogleCloudDataLab/1.0'\n if args is not None:\n qs = urllib.parse.urlencode(args)\n url = url + '?' + qs\n if data is not None:\n if method is None:\n method = 'POST'\n if data != '':\n if 'Content-Type' not in headers:\n data = json.dumps(data)\n headers['Content-Type'] = 'application/json'\n headers['Content-Length'] = str(len(data))\n elif method == 'POST':\n headers['Content-Length'] = '0'\n if method is None:\n method = 'GET'\n http = Http.http\n if credentials is not None:\n http = copy.copy(http)\n http = google_auth_httplib2.AuthorizedHttp(credentials)\n if stats is not None:\n stats['duration'] = datetime.datetime.utcnow()\n response = None\n try:\n log.debug('request: method[%(method)s], url[%(url)s], body[%(data)s]' % locals())\n response, content = http.request(url, method=method, body=data, headers=headers)\n if 200 <= response.status < 300:\n if raw_response:\n return content\n if type(content) == str:\n return json.loads(content)\n else:\n return json.loads(str(content, encoding='UTF-8'))\n else:\n raise RequestException(response.status, content)\n except ValueError:\n raise Exception('Failed to process HTTP response.')\n except httplib2.HttpLib2Error:\n raise Exception('Failed to send HTTP request.')\n finally:\n if stats is not None:\n stats['data_size'] = len(data)\n stats['status'] = response.status\n stats['duration'] = (datetime.datetime.utcnow() - stats['duration']).total_seconds()\n ", "context": "class Http(object):\n @staticmethod\n def request(url, args=None, data=None, headers=None, method=None, credentials=None, raw_response=False, stats=None): ...\n def __init__(self): ...\n\n http = httplib2.Http()\n http.disable_ssl_certificate_validation = True\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001345.py"} {"focal_file": "google/datalab/utils/_utils.py", "focal_class": null, "focal_method": "compare_datetimes", "tests": "import unittest\n\nclass Test_compare_datetimes(unittest.TestCase):\n def test_compare_datetimes(self):\n t1, t2 = (datetime(2017, 2, 2, 12, 0, 0), datetime(2017, 2, 2, 12, 0, 0))\n self.assertEquals(_utils.compare_datetimes(t1, t2), 0)\n t2 = t2.replace(hour=11)\n self.assertEquals(_utils.compare_datetimes(t1, t2), 1)\n\n def test_compare_datetimes_tz(self):\n t1 = datetime(2017, 2, 2, 12, 0, 0)\n t2 = datetime(2017, 2, 2, 12, 0, 0, tzinfo=pytz.timezone('US/Eastern'))\n self.assertEquals(_utils.compare_datetimes(t1, t2), -1)\n t1 = t1.replace(tzinfo=pytz.timezone('US/Pacific'))\n self.assertEquals(_utils.compare_datetimes(t1, t2), 1)\n", "method_code": "def compare_datetimes(d1, d2):\n \"\"\" Compares two datetimes safely, whether they are timezone-naive or timezone-aware.\n\n If either datetime is naive it is converted to an aware datetime assuming UTC.\n\n Args:\n d1: first datetime.\n d2: second datetime.\n\n Returns:\n -1 if d1 < d2, 0 if they are the same, or +1 is d1 > d2.\n \"\"\"\n if d1.tzinfo is None or d1.tzinfo.utcoffset(d1) is None:\n d1 = d1.replace(tzinfo=pytz.UTC)\n if d2.tzinfo is None or d2.tzinfo.utcoffset(d2) is None:\n d2 = d2.replace(tzinfo=pytz.UTC)\n if d1 < d2:\n return -1\n elif d1 > d2:\n return 1\n return 0", "context": "def compare_datetimes(d1, d2): ...\ndef print_exception_with_last_stack(e): ...\ndef get_item(env, name, default=None): ...\ndef compare_datetimes(d1, d2): ...\ndef pick_unused_port(): ...\ndef is_http_running_on(port): ...\ndef gcs_copy_file(source, dest): ...\ndef _in_datalab_docker(): ...\ndef get_config_dir(): ...\ndef _convert_oauth2client_creds(credentials): ...\ndef get_credentials(): ...\ndef save_project_id(project_id): ...\ndef get_default_project_id(): ...\ndef _construct_context_for_args(args): ...\ndef python_portable_string(string, encoding='utf-8'): ...\n", "repository": "googledatalab/pydatalab", "test_name": "test_compare_datetimes", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001346.py"} {"focal_file": "google/datalab/utils/_utils.py", "focal_class": null, "focal_method": "get_config_dir", "tests": "import unittest\n\nclass Test_get_config_dir(unittest.TestCase):\n @mock.patch('os.path.expanduser')\n def test_get_config_dir(self, mock_expand_user):\n mock_expand_user.return_value = 'user/relative/path'\n with mock.patch.dict(os.environ, {'CLOUDSDK_CONFIG': 'test/path'}):\n self.assertEquals(_utils.get_config_dir(), 'test/path')\n self.assertEquals(_utils.get_config_dir(), 'user/relative/path/.config/gcloud')\n\n @mock.patch('os.name', 'nt')\n @mock.patch('os.path.join')\n def test_get_config_dir_win(self, mock_path_join):\n mock_path_join.side_effect = lambda x, y: x + y\n self.assertEquals(_utils.get_config_dir(), 'C:\\\\gcloud')\n mock_path_join.side_effect = lambda x, y: x + '\\\\' + y\n with mock.patch.dict(os.environ, {'APPDATA': 'test\\\\path'}):\n self.assertEquals(_utils.get_config_dir(), 'test\\\\path\\\\gcloud')\n", "method_code": "def get_config_dir():\n config_dir = os.getenv('CLOUDSDK_CONFIG')\n if config_dir is None:\n if os.name == 'nt':\n try:\n config_dir = os.path.join(os.environ['APPDATA'], 'gcloud')\n except KeyError:\n drive = os.environ.get('SystemDrive', 'C:')\n config_dir = os.path.join(drive, '\\\\gcloud')\n else:\n config_dir = os.path.join(os.path.expanduser('~'), '.config/gcloud')\n return config_dir", "context": "def get_config_dir(): ...\ndef print_exception_with_last_stack(e): ...\ndef get_item(env, name, default=None): ...\ndef compare_datetimes(d1, d2): ...\ndef pick_unused_port(): ...\ndef is_http_running_on(port): ...\ndef gcs_copy_file(source, dest): ...\ndef _in_datalab_docker(): ...\ndef get_config_dir(): ...\ndef _convert_oauth2client_creds(credentials): ...\ndef get_credentials(): ...\ndef save_project_id(project_id): ...\ndef get_default_project_id(): ...\ndef _construct_context_for_args(args): ...\ndef python_portable_string(string, encoding='utf-8'): ...\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001347.py"} {"focal_file": "google/datalab/utils/_utils.py", "focal_class": null, "focal_method": "get_credentials", "tests": "import unittest\n\nclass Test_get_credentials(unittest.TestCase):\n @mock.patch('google.datalab.utils._utils._in_datalab_docker')\n @mock.patch('google.auth.credentials.with_scopes_if_required')\n @mock.patch('google.auth.default')\n @mock.patch('os.path.exists')\n def test_get_credentials_from_file(self, mock_path_exists, mock_google_auth_default, mock_with_scopes_if_required, mock_in_datalab):\n creds = mock.Mock(spec=google.auth.credentials.Credentials)\n mock_google_auth_default.return_value = [creds, '']\n _utils.get_credentials()\n mock_google_auth_default.assert_called_once()\n mock_with_scopes_if_required.assert_called_once()\n test_creds = '\\n {\\n \"data\": [{\\n \"key\": {\\n \"type\": \"google-cloud-sdk\"\\n },\\n \"credential\": {\\n \"access_token\": \"test-access-token\",\\n \"client_id\": \"test-id\",\\n \"client_secret\": \"test-secret\",\\n \"refresh_token\": \"test-token\",\\n \"token_expiry\": \"test-expiry\",\\n \"token_uri\": \"test-url\",\\n \"user_agent\": \"test-agent\",\\n \"invalid\": \"false\"\\n }\\n }]\\n }\\n '\n with mock.patch('google.datalab.utils._utils.open', mock.mock_open(read_data=test_creds)):\n mock_google_auth_default.side_effect = Exception\n cred = _utils.get_credentials()\n self.assertEquals(cred.token, 'test-access-token')\n mock_path_exists.return_value = False\n with self.assertRaises(Exception):\n cred = _utils.get_credentials()\n mock_google_auth_default.side_effect = google.auth.exceptions.DefaultCredentialsError\n with self.assertRaisesRegexp(Exception, 'No application credentials found. Perhaps you should sign in'):\n cred = _utils.get_credentials()\n", "method_code": "def get_credentials():\n \"\"\" Get the credentials to use. We try application credentials first, followed by\n user credentials. The path to the application credentials can be overridden\n by pointing the GOOGLE_APPLICATION_CREDENTIALS environment variable to some file;\n the path to the user credentials can be overridden by pointing the CLOUDSDK_CONFIG\n environment variable to some directory (after which we will look for the file\n $CLOUDSDK_CONFIG/gcloud/credentials). Unless you have specific reasons for\n overriding these the defaults should suffice.\n \"\"\"\n try:\n authDefaultLogger = logging.getLogger('google.auth._default')\n previousLevel = authDefaultLogger.getEffectiveLevel()\n authDefaultLogger.setLevel(logging.ERROR)\n credentials, _ = google.auth.default()\n credentials = google.auth.credentials.with_scopes_if_required(credentials, CREDENTIAL_SCOPES)\n authDefaultLogger.setLevel(previousLevel)\n return credentials\n except Exception as e:\n cred_file = get_config_dir() + '/credentials'\n if os.path.exists(cred_file):\n with open(cred_file) as f:\n creds = json.loads(f.read())\n for entry in creds['data']:\n if entry['key']['type'] == 'google-cloud-sdk':\n creds = oauth2client.client.OAuth2Credentials.from_json(json.dumps(entry['credential']))\n return _convert_oauth2client_creds(creds)\n if type(e) == google.auth.exceptions.DefaultCredentialsError:\n if _in_datalab_docker():\n raise Exception('No application credentials found. Perhaps you should sign in.')\n raise e", "context": "def get_credentials(): ...\ndef print_exception_with_last_stack(e): ...\ndef get_item(env, name, default=None): ...\ndef compare_datetimes(d1, d2): ...\ndef pick_unused_port(): ...\ndef is_http_running_on(port): ...\ndef gcs_copy_file(source, dest): ...\ndef _in_datalab_docker(): ...\ndef get_config_dir(): ...\ndef _convert_oauth2client_creds(credentials): ...\ndef get_credentials(): ...\ndef save_project_id(project_id): ...\ndef get_default_project_id(): ...\ndef _construct_context_for_args(args): ...\ndef python_portable_string(string, encoding='utf-8'): ...\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001348.py"} {"focal_file": "google/datalab/utils/_utils.py", "focal_class": null, "focal_method": "save_project_id", "tests": "import unittest\n\nclass Test_save_project_id(unittest.TestCase):\n @mock.patch('subprocess.call')\n @mock.patch('os.path.exists')\n def test_save_project_id(self, mock_path_exists, mock_subprocess_call):\n _utils.save_project_id('test-project')\n mock_subprocess_call.assert_called_with(['gcloud', 'config', 'set', 'project', 'test-project'])\n mock_subprocess_call.side_effect = Exception\n test_config = '\\n {\\n \"project_id\": \"\"\\n }\\n '\n opener = mock.mock_open(read_data=test_config)\n with mock.patch('google.datalab.utils._utils.open', opener):\n _utils.save_project_id('test-project')\n opener.assert_has_calls([mock.call().write('{\"project_id\": \"test-project\"}')])\n", "method_code": "def save_project_id(project_id):\n \"\"\" Save project id to config file.\n\n Args:\n project_id: the project_id to save.\n \"\"\"\n try:\n subprocess.call(['gcloud', 'config', 'set', 'project', project_id])\n except:\n config_file = os.path.join(get_config_dir(), 'config.json')\n config = {}\n if os.path.exists(config_file):\n with open(config_file) as f:\n config = json.loads(f.read())\n config['project_id'] = project_id\n with open(config_file, 'w') as f:\n f.write(json.dumps(config))", "context": "def save_project_id(project_id): ...\ndef print_exception_with_last_stack(e): ...\ndef get_item(env, name, default=None): ...\ndef compare_datetimes(d1, d2): ...\ndef pick_unused_port(): ...\ndef is_http_running_on(port): ...\ndef gcs_copy_file(source, dest): ...\ndef _in_datalab_docker(): ...\ndef get_config_dir(): ...\ndef _convert_oauth2client_creds(credentials): ...\ndef get_credentials(): ...\ndef save_project_id(project_id): ...\ndef get_default_project_id(): ...\ndef _construct_context_for_args(args): ...\ndef python_portable_string(string, encoding='utf-8'): ...\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001349.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "jobs_insert_load", "tests": "import unittest\n\nclass Test_jobs_insert_load(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_jobs_insert_load(self, mock_http_request):\n api = TestCases._create_api()\n api.jobs_insert_load('SOURCE', google.datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n self.maxDiff = None\n expected_data = {'kind': 'bigquery#job', 'configuration': {'load': {'sourceUris': ['SOURCE'], 'destinationTable': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'createDisposition': 'CREATE_NEVER', 'writeDisposition': 'WRITE_EMPTY', 'sourceFormat': 'CSV', 'fieldDelimiter': ',', 'allowJaggedRows': False, 'allowQuotedNewlines': False, 'encoding': 'UTF-8', 'ignoreUnknownValues': False, 'maxBadRecords': 0, 'quote': '\"', 'skipLeadingRows': 0}}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/jobs/', expected_data=expected_data)\n api.jobs_insert_load('SOURCE2', google.datalab.bigquery._utils.TableName('p2', 'd2', 't2', ''), append=True, create=True, allow_jagged_rows=True, allow_quoted_newlines=True, ignore_unknown_values=True, source_format='JSON', max_bad_records=1)\n expected_data = {'kind': 'bigquery#job', 'configuration': {'load': {'sourceUris': ['SOURCE2'], 'destinationTable': {'projectId': 'p2', 'datasetId': 'd2', 'tableId': 't2'}, 'createDisposition': 'CREATE_IF_NEEDED', 'writeDisposition': 'WRITE_APPEND', 'sourceFormat': 'JSON', 'ignoreUnknownValues': True, 'maxBadRecords': 1}}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p2/jobs/', expected_data=expected_data)\n", "method_code": " def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0):\n \"\"\" Issues a request to load data from GCS to a BQ table\n \n Args:\n source: the URL of the source bucket(s). Can include wildcards, and can be a single\n string argument or a list.\n table_name: a tuple representing the full name of the destination table.\n append: if True append onto existing table contents.\n overwrite: if True overwrite existing table contents.\n create: if True, create the table if it doesn't exist\n source_format: the format of the data; default 'CSV'. Other options are DATASTORE_BACKUP\n or NEWLINE_DELIMITED_JSON.\n field_delimiter: The separator for fields in a CSV file. BigQuery converts the string to\n ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data\n as raw binary (default ',').\n allow_jagged_rows: If True, accept rows in CSV files that are missing trailing optional\n columns; the missing values are treated as nulls (default False).\n allow_quoted_newlines: If True, allow quoted data sections in CSV files that contain newline\n characters (default False).\n encoding: The character encoding of the data, either 'UTF-8' (the default) or 'ISO-8859-1'.\n ignore_unknown_values: If True, accept rows that contain values that do not match the schema;\n the unknown values are ignored (default False).\n max_bad_records: The maximum number of bad records that are allowed (and ignored) before\n returning an 'invalid' error in the Job result (default 0).\n quote: The value used to quote data sections in a CSV file; default '\"'. If your data does\n not contain quoted sections, set the property value to an empty string. If your data\n contains quoted newline characters, you must also enable allow_quoted_newlines.\n skip_leading_rows: A number of rows at the top of a CSV file to skip (default 0).\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._JOBS_PATH % (table_name.project_id, '')\n if isinstance(source, basestring):\n source = [source]\n write_disposition = 'WRITE_EMPTY'\n if overwrite:\n write_disposition = 'WRITE_TRUNCATE'\n if append:\n write_disposition = 'WRITE_APPEND'\n data = {'kind': 'bigquery#job', 'configuration': {'load': {'sourceUris': source, 'destinationTable': {'projectId': table_name.project_id, 'datasetId': table_name.dataset_id, 'tableId': table_name.table_id}, 'createDisposition': 'CREATE_IF_NEEDED' if create else 'CREATE_NEVER', 'writeDisposition': write_disposition, 'sourceFormat': source_format, 'ignoreUnknownValues': ignore_unknown_values, 'maxBadRecords': max_bad_records}}}\n if source_format == 'CSV':\n load_config = data['configuration']['load']\n load_config.update({'fieldDelimiter': field_delimiter, 'allowJaggedRows': allow_jagged_rows, 'allowQuotedNewlines': allow_quoted_newlines, 'quote': quote, 'encoding': encoding, 'skipLeadingRows': skip_leading_rows})\n return google.datalab.utils.Http.request(url, data=data, credentials=self.credentials)\n ", "context": "class Api(object):\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001350.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "jobs_insert_query", "tests": "import unittest\n\nclass Test_jobs_insert_query(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_jobs_insert_query(self, mock_http_request):\n context = TestCases._create_context()\n context.config['bigquery_billing_tier'] = None\n api = TestCases._create_api(context)\n api.jobs_insert_query('SQL')\n expected_data = {'kind': 'bigquery#job', 'configuration': {'query': {'query': 'SQL', 'useQueryCache': True, 'allowLargeResults': False, 'useLegacySql': False}, 'dryRun': False, 'priority': 'BATCH'}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/test/jobs/', expected_data=expected_data)\n context.config['bigquery_billing_tier'] = 1\n api.jobs_insert_query('SQL2', table_name=google.datalab.bigquery._utils.TableName('p', 'd', 't', ''), append=True, dry_run=True, use_cache=False, batch=False, allow_large_results=True)\n expected_data = {'kind': 'bigquery#job', 'configuration': {'query': {'query': 'SQL2', 'useQueryCache': False, 'allowLargeResults': True, 'useLegacySql': False, 'maximumBillingTier': 1, 'destinationTable': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'writeDisposition': 'WRITE_APPEND'}, 'dryRun': True, 'priority': 'INTERACTIVE'}}\n self.maxDiff = None\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/test/jobs/', expected_data=expected_data)\n", "method_code": " def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None):\n \"\"\"Issues a request to insert a query job.\n \n Args:\n sql: the SQL string representing the query to execute.\n table_name: None for an anonymous table, or a name parts tuple for a long-lived table.\n append: if True, append to the table if it is non-empty; else the request will fail if table\n is non-empty unless overwrite is True.\n overwrite: if the table already exists, truncate it instead of appending or raising an\n Exception.\n dry_run: whether to actually execute the query or just dry run it.\n use_cache: whether to use past query results or ignore cache. Has no effect if destination is\n specified.\n batch: whether to run this as a batch job (lower priority) or as an interactive job (high\n priority, more expensive).\n allow_large_results: whether to allow large results (slower with some restrictions but\n can handle big jobs).\n table_definitions: a dictionary of ExternalDataSource names and objects for any external\n tables referenced in the query.\n query_params: a dictionary containing query parameter types and values, passed to BigQuery.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._JOBS_PATH % (self.project_id, '')\n data = {'kind': 'bigquery#job', 'configuration': {'query': {'query': sql, 'useQueryCache': use_cache, 'allowLargeResults': allow_large_results, 'useLegacySql': False}, 'dryRun': dry_run, 'priority': 'BATCH' if batch else 'INTERACTIVE'}}\n query_config = data['configuration']['query']\n if table_definitions:\n expanded_definitions = {}\n for td in table_definitions:\n expanded_definitions[td] = table_definitions[td]._to_query_json()\n query_config['tableDefinitions'] = expanded_definitions\n if table_name:\n query_config['destinationTable'] = {'projectId': table_name.project_id, 'datasetId': table_name.dataset_id, 'tableId': table_name.table_id}\n if append:\n query_config['writeDisposition'] = 'WRITE_APPEND'\n elif overwrite:\n query_config['writeDisposition'] = 'WRITE_TRUNCATE'\n if self.bigquery_billing_tier:\n query_config['maximumBillingTier'] = self.bigquery_billing_tier\n if query_params:\n query_config['queryParameters'] = query_params\n return google.datalab.utils.Http.request(url, data=data, credentials=self.credentials)\n ", "context": "class Api(object):\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001351.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "jobs_query_results", "tests": "import unittest\n\nclass Test_jobs_query_results(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_jobs_query_results(self, mock_http_request):\n api = TestCases._create_api()\n api.jobs_query_results('JOB', 'PROJECT', 10, 20, 30)\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/PROJECT/queries/JOB', expected_args={'maxResults': 10, 'timeoutMs': 20, 'startIndex': 30})\n", "method_code": " def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0):\n \"\"\"Issues a request to the jobs/getQueryResults method.\n \n Args:\n job_id: the id of job from a previously executed query.\n project_id: the project id to use to fetch the results; use None for the default project.\n page_size: limit to the number of rows to fetch.\n timeout: duration (in milliseconds) to wait for the query to complete.\n start_index: the index of the row (0-based) at which to start retrieving the page of result\n rows.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if timeout is None:\n timeout = Api._DEFAULT_TIMEOUT\n if project_id is None:\n project_id = self.project_id\n args = {'maxResults': page_size, 'timeoutMs': timeout, 'startIndex': start_index}\n url = Api._ENDPOINT + Api._QUERIES_PATH % (project_id, job_id)\n return google.datalab.utils.Http.request(url, args=args, credentials=self.credentials)\n ", "context": "class Api(object):\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001352.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "jobs_get", "tests": "import unittest\n\nclass Test_jobs_get(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_jobs_get(self, mock_http_request):\n api = TestCases._create_api()\n api.jobs_get('JOB', 'PROJECT')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/PROJECT/jobs/JOB')\n", "method_code": " def jobs_get(self, job_id, project_id=None):\n \"\"\"Issues a request to retrieve information about a job.\n \n Args:\n job_id: the id of the job\n project_id: the project id to use to fetch the results; use None for the default project.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if project_id is None:\n project_id = self.project_id\n url = Api._ENDPOINT + Api._JOBS_PATH % (project_id, job_id)\n return google.datalab.utils.Http.request(url, credentials=self.credentials)\n ", "context": "class Api(object):\n def jobs_get(self, job_id, project_id=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001353.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_insert", "tests": "import unittest\n\nclass Test_datasets_insert(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_datasets_insert(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_insert(google.datalab.bigquery._utils.DatasetName('p', 'd'))\n expected_data = {'kind': 'bigquery#dataset', 'datasetReference': {'projectId': 'p', 'datasetId': 'd'}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/', expected_data=expected_data)\n api.datasets_insert(google.datalab.bigquery._utils.DatasetName('p', 'd'), 'FRIENDLY', 'DESCRIPTION')\n expected_data = {'kind': 'bigquery#dataset', 'datasetReference': {'projectId': 'p', 'datasetId': 'd'}, 'friendlyName': 'FRIENDLY', 'description': 'DESCRIPTION'}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/', expected_data=expected_data)\n", "method_code": " def datasets_insert(self, dataset_name, friendly_name=None, description=None):\n \"\"\"Issues a request to create a dataset.\n \n Args:\n dataset_name: the name of the dataset to create.\n friendly_name: (optional) the friendly name for the dataset\n description: (optional) a description for the dataset\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._DATASETS_PATH % (dataset_name.project_id, '')\n data = {'kind': 'bigquery#dataset', 'datasetReference': {'projectId': dataset_name.project_id, 'datasetId': dataset_name.dataset_id}}\n if friendly_name:\n data['friendlyName'] = friendly_name\n if description:\n data['description'] = description\n return google.datalab.utils.Http.request(url, data=data, credentials=self.credentials)\n ", "context": "class Api(object):\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001354.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_delete", "tests": "import unittest\n\nclass Test_datasets_delete(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_datasets_delete(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_delete(google.datalab.bigquery._utils.DatasetName('p', 'd'), False)\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d', expected_args={}, expected_method='DELETE')\n api.datasets_delete(google.datalab.bigquery._utils.DatasetName('p', 'd'), True)\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d', expected_args={'deleteContents': True}, expected_method='DELETE')\n", "method_code": " def datasets_delete(self, dataset_name, delete_contents):\n \"\"\"Issues a request to delete a dataset.\n \n Args:\n dataset_name: the name of the dataset to delete.\n delete_contents: if True, any tables in the dataset will be deleted. If False and the\n dataset is non-empty an exception will be raised.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._DATASETS_PATH % dataset_name\n args = {}\n if delete_contents:\n args['deleteContents'] = True\n return google.datalab.utils.Http.request(url, method='DELETE', args=args, credentials=self.credentials, raw_response=True)\n ", "context": "class Api(object):\n def datasets_delete(self, dataset_name, delete_contents): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001355.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_update", "tests": "import unittest\n\nclass Test_datasets_update(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_datasets_update(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_update(google.datalab.bigquery._utils.DatasetName('p', 'd'), 'INFO')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d', expected_method='PUT', expected_data='INFO')\n", "method_code": " def datasets_update(self, dataset_name, dataset_info):\n \"\"\"Updates the Dataset info.\n \n Args:\n dataset_name: the name of the dataset to update as a tuple of components.\n dataset_info: the Dataset resource with updated fields.\n \"\"\"\n url = Api._ENDPOINT + Api._DATASETS_PATH % dataset_name\n return google.datalab.utils.Http.request(url, method='PUT', data=dataset_info, credentials=self.credentials)\n ", "context": "class Api(object):\n def datasets_update(self, dataset_name, dataset_info): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001356.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_get", "tests": "import unittest\n\nclass Test_datasets_get(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_datasets_get(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_get(google.datalab.bigquery._utils.DatasetName('p', 'd'))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d')\n", "method_code": " def datasets_get(self, dataset_name):\n \"\"\"Issues a request to retrieve information about a dataset.\n \n Args:\n dataset_name: the name of the dataset\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._DATASETS_PATH % dataset_name\n return google.datalab.utils.Http.request(url, credentials=self.credentials)\n ", "context": "class Api(object):\n def datasets_get(self, dataset_name): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001357.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "datasets_list", "tests": "import unittest\n\nclass Test_datasets_list(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_datasets_list(self, mock_http_request):\n api = TestCases._create_api()\n api.datasets_list()\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/test/datasets/', expected_args={})\n api.datasets_list('PROJECT', 10, 'TOKEN')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/PROJECT/datasets/', expected_args={'maxResults': 10, 'pageToken': 'TOKEN'})\n", "method_code": " def datasets_list(self, project_id=None, max_results=0, page_token=None):\n \"\"\"Issues a request to list the datasets in the project.\n \n Args:\n project_id: the project id to use to fetch the results; use None for the default project.\n max_results: an optional maximum number of tables to retrieve.\n page_token: an optional token to continue the retrieval.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if project_id is None:\n project_id = self.project_id\n url = Api._ENDPOINT + Api._DATASETS_PATH % (project_id, '')\n args = {}\n if max_results != 0:\n args['maxResults'] = max_results\n if page_token is not None:\n args['pageToken'] = page_token\n return google.datalab.utils.Http.request(url, args=args, credentials=self.credentials)\n ", "context": "class Api(object):\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001358.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tables_get", "tests": "import unittest\n\nclass Test_tables_get(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_tables_get(self, mock_http_request):\n api = TestCases._create_api()\n api.tables_get(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t')\n", "method_code": " def tables_get(self, table_name):\n \"\"\"Issues a request to retrieve information about a table.\n \n Args:\n table_name: a tuple representing the full name of the table.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % table_name\n return google.datalab.utils.Http.request(url, credentials=self.credentials)\n ", "context": "class Api(object):\n def tables_get(self, table_name): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001359.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tables_list", "tests": "import unittest\n\nclass Test_tables_list(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_tables_list(self, mock_http_request):\n api = TestCases._create_api()\n api.tables_list(google.datalab.bigquery._utils.DatasetName('p', 'd'))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/', expected_args={})\n api.tables_list(google.datalab.bigquery._utils.DatasetName('p', 'd'), 10, 'TOKEN')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/', expected_args={'maxResults': 10, 'pageToken': 'TOKEN'})\n", "method_code": " def tables_list(self, dataset_name, max_results=0, page_token=None):\n \"\"\"Issues a request to retrieve a list of tables.\n \n Args:\n dataset_name: the name of the dataset to enumerate.\n max_results: an optional maximum number of tables to retrieve.\n page_token: an optional token to continue the retrieval.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % (dataset_name.project_id, dataset_name.dataset_id, '', '')\n args = {}\n if max_results != 0:\n args['maxResults'] = max_results\n if page_token is not None:\n args['pageToken'] = page_token\n return google.datalab.utils.Http.request(url, args=args, credentials=self.credentials)\n ", "context": "class Api(object):\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001360.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tables_insert", "tests": "import unittest\n\nclass Test_tables_insert(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_tables_insert(self, mock_http_request):\n api = TestCases._create_api()\n api.tables_insert(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n expected_data = {'kind': 'bigquery#table', 'tableReference': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/', expected_data=expected_data)\n api.tables_insert(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''), 'SCHEMA', 'QUERY', 'FRIENDLY', 'DESCRIPTION')\n expected_data = {'kind': 'bigquery#table', 'tableReference': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'schema': {'fields': 'SCHEMA'}, 'view': {'query': 'QUERY'}, 'friendlyName': 'FRIENDLY', 'description': 'DESCRIPTION'}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/', expected_data=expected_data)\n", "method_code": " def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None):\n \"\"\"Issues a request to create a table or view in the specified dataset with the specified id.\n A schema must be provided to create a Table, or a query must be provided to create a View.\n \n Args:\n table_name: the name of the table as a tuple of components.\n schema: the schema, if this is a Table creation.\n query: the query, if this is a View creation.\n friendly_name: an optional friendly name.\n description: an optional description.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % (table_name.project_id, table_name.dataset_id, '', '')\n data = {'kind': 'bigquery#table', 'tableReference': {'projectId': table_name.project_id, 'datasetId': table_name.dataset_id, 'tableId': table_name.table_id}}\n if schema:\n data['schema'] = {'fields': schema}\n if query:\n data['view'] = {'query': query}\n if friendly_name:\n data['friendlyName'] = friendly_name\n if description:\n data['description'] = description\n return google.datalab.utils.Http.request(url, data=data, credentials=self.credentials)\n ", "context": "class Api(object):\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001361.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tabledata_insert_all", "tests": "import unittest\n\nclass Test_tabledata_insert_all(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_tabledata_insertAll(self, mock_http_request):\n api = TestCases._create_api()\n api.tabledata_insert_all(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''), 'ROWS')\n expected_data = {'kind': 'bigquery#tableDataInsertAllRequest', 'rows': 'ROWS'}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t/insertAll', expected_data=expected_data)\n", "method_code": " def tabledata_insert_all(self, table_name, rows):\n \"\"\"Issues a request to insert data into a table.\n \n Args:\n table_name: the name of the table as a tuple of components.\n rows: the data to populate the table, as a list of dictionaries.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % table_name + '/insertAll'\n data = {'kind': 'bigquery#tableDataInsertAllRequest', 'rows': rows}\n return google.datalab.utils.Http.request(url, data=data, credentials=self.credentials)\n ", "context": "class Api(object):\n def tabledata_insert_all(self, table_name, rows): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001362.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "tabledata_list", "tests": "import unittest\n\nclass Test_tabledata_list(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_tabledata_list(self, mock_http_request):\n api = TestCases._create_api()\n api.tabledata_list(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t/data', expected_args={})\n api.tabledata_list(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''), 10, 20, 'TOKEN')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t/data', expected_args={'startIndex': 10, 'maxResults': 20, 'pageToken': 'TOKEN'})\n", "method_code": " def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None):\n \"\"\" Retrieves the contents of a table.\n \n Args:\n table_name: the name of the table as a tuple of components.\n start_index: the index of the row at which to start retrieval.\n max_results: an optional maximum number of rows to retrieve.\n page_token: an optional token to continue the retrieval.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLEDATA_PATH % table_name\n args = {}\n if start_index:\n args['startIndex'] = start_index\n if max_results:\n args['maxResults'] = max_results\n if page_token is not None:\n args['pageToken'] = page_token\n return google.datalab.utils.Http.request(url, args=args, credentials=self.credentials)\n ", "context": "class Api(object):\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001363.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "table_delete", "tests": "import unittest\n\nclass Test_table_delete(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_table_delete(self, mock_http_request):\n api = TestCases._create_api()\n api.table_delete(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''))\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t', expected_method='DELETE')\n", "method_code": " def table_delete(self, table_name):\n \"\"\"Issues a request to delete a table.\n \n Args:\n table_name: the name of the table as a tuple of components.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % table_name\n return google.datalab.utils.Http.request(url, method='DELETE', credentials=self.credentials, raw_response=True)\n ", "context": "class Api(object):\n def table_delete(self, table_name): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001364.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "table_extract", "tests": "import unittest\n\nclass Test_table_extract(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_table_extract(self, mock_http_request):\n api = TestCases._create_api()\n api.table_extract(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''), 'DEST')\n expected_data = {'kind': 'bigquery#job', 'configuration': {'extract': {'sourceTable': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'compression': 'GZIP', 'fieldDelimiter': ',', 'printHeader': True, 'destinationUris': ['DEST'], 'destinationFormat': 'CSV'}}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/jobs/', expected_data=expected_data)\n api.table_extract(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''), ['DEST'], format='JSON', compress=False, field_delimiter=':', print_header=False)\n expected_data = {'kind': 'bigquery#job', 'configuration': {'extract': {'sourceTable': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't'}, 'compression': 'NONE', 'fieldDelimiter': ':', 'printHeader': False, 'destinationUris': ['DEST'], 'destinationFormat': 'JSON'}}}\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/jobs/', expected_data=expected_data)\n", "method_code": " def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True):\n \"\"\"Exports the table to GCS.\n \n Args:\n table_name: the name of the table as a tuple of components.\n destination: the destination URI(s). Can be a single URI or a list.\n format: the format to use for the exported data; one of CSV, NEWLINE_DELIMITED_JSON or AVRO.\n Defaults to CSV.\n compress: whether to compress the data on export. Compression is not supported for\n AVRO format. Defaults to False.\n field_delimiter: for CSV exports, the field delimiter to use. Defaults to ','\n print_header: for CSV exports, whether to include an initial header line. Default true.\n Returns:\n A parsed result object.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._JOBS_PATH % (table_name.project_id, '')\n if isinstance(destination, basestring):\n destination = [destination]\n data = {'kind': 'bigquery#job', 'configuration': {'extract': {'sourceTable': {'projectId': table_name.project_id, 'datasetId': table_name.dataset_id, 'tableId': table_name.table_id}, 'compression': 'GZIP' if compress else 'NONE', 'fieldDelimiter': field_delimiter, 'printHeader': print_header, 'destinationUris': destination, 'destinationFormat': format}}}\n return google.datalab.utils.Http.request(url, data=data, credentials=self.credentials)\n ", "context": "class Api(object):\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_update(self, table_name, table_info): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001365.py"} {"focal_file": "google/datalab/bigquery/_api.py", "focal_class": null, "focal_method": "table_update", "tests": "import unittest\n\nclass Test_table_update(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_table_update(self, mock_http_request):\n api = TestCases._create_api()\n api.table_update(google.datalab.bigquery._utils.TableName('p', 'd', 't', ''), 'INFO')\n self.validate(mock_http_request, 'https://www.googleapis.com/bigquery/v2/projects/p/datasets/d/tables/t', expected_method='PUT', expected_data='INFO')\n", "method_code": " def table_update(self, table_name, table_info):\n \"\"\"Updates the Table info.\n \n Args:\n table_name: the name of the table to update as a tuple of components.\n table_info: the Table resource with updated fields.\n \"\"\"\n url = Api._ENDPOINT + Api._TABLES_PATH % table_name\n return google.datalab.utils.Http.request(url, method='PUT', data=table_info, credentials=self.credentials)\n ", "context": "class Api(object):\n def table_update(self, table_name, table_info): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def credentials(self): ...\n def bigquery_billing_tier(self): ...\n def jobs_insert_load(self, source, table_name, append=False, overwrite=False, create=False, source_format='CSV', field_delimiter=',', allow_jagged_rows=False, allow_quoted_newlines=False, encoding='UTF-8', ignore_unknown_values=False, max_bad_records=0, quote='\"', skip_leading_rows=0): ...\n def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): ...\n def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): ...\n def jobs_get(self, job_id, project_id=None): ...\n def datasets_insert(self, dataset_name, friendly_name=None, description=None): ...\n def datasets_delete(self, dataset_name, delete_contents): ...\n def datasets_update(self, dataset_name, dataset_info): ...\n def datasets_get(self, dataset_name): ...\n def datasets_list(self, project_id=None, max_results=0, page_token=None): ...\n def tables_get(self, table_name): ...\n def tables_list(self, dataset_name, max_results=0, page_token=None): ...\n def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): ...\n def tabledata_insert_all(self, table_name, rows): ...\n def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): ...\n def table_delete(self, table_name): ...\n def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True): ...\n\n self._context = context\n\n _ENDPOINT = 'https://www.googleapis.com/bigquery/v2'\n _JOBS_PATH = '/projects/%s/jobs/%s'\n _QUERIES_PATH = '/projects/%s/queries/%s'\n _DATASETS_PATH = '/projects/%s/datasets/%s'\n _TABLES_PATH = '/projects/%s/datasets/%s/tables/%s%s'\n _TABLEDATA_PATH = '/projects/%s/datasets/%s/tables/%s%s/data'\n _DEFAULT_TIMEOUT = 60000\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001366.py"} {"focal_file": "google/datalab/contrib/bigquery/operators/_bq_load_operator.py", "focal_class": null, "focal_method": "execute", "tests": "import unittest\n\nclass Test_execute(unittest.TestCase):\n @mock.patch('google.datalab.Context.default')\n @mock.patch('google.datalab.bigquery.ExternalDataSource')\n @mock.patch('google.datalab.bigquery.Query')\n @mock.patch('google.datalab.bigquery.QueryOutput.table')\n @mock.patch('google.datalab.bigquery._query_job.QueryJob')\n def test_execute_operator_with_data_source(self, mock_query_job, mock_query_output_table, mock_query_class, mock_external_data_source, mock_context_default):\n mock_context_default.return_value = self._create_context()\n csv_options = {'delimiter': 'f', 'skip': 9, 'strict': True, 'quote': 'l'}\n execute_operator = ExecuteOperator(task_id='test_execute_operator', sql='test_sql', data_source='foo_data_source', path='foo_path', max_bad_records=20, schema=TestCases.test_schema, csv_options=csv_options, format='csv')\n mock_query_instance = mock_query_class.return_value\n mock_query_instance.execute.return_value = mock_query_job\n mock_query_job.result.return_value = google.datalab.bigquery.Table(TestCases.test_table_name)\n self.assertDictEqual(execute_operator.execute(context=None), {'table': TestCases.test_table_name})\n mock_query_output_table.assert_called_with(name=None, use_cache=False, allow_large_results=False)\n mock_query_class.assert_called_with(sql='test_sql', data_sources={'foo_data_source': mock_external_data_source.return_value})\n mock_external_data_source.assert_called_with(source='foo_path', max_bad_records=20, csv_options=mock.ANY, source_format='csv', schema=google.datalab.bigquery.Schema(TestCases.test_schema))\n execute_operator = ExecuteOperator(task_id='test_execute_operator', sql='test_sql', data_source='foo_data_source', path='foo_path', schema=TestCases.test_schema)\n mock_query_instance = mock_query_class.return_value\n mock_query_instance.execute.return_value = mock_query_job\n execute_operator.execute(None)\n mock_query_output_table.assert_called_with(name=None, use_cache=False, allow_large_results=False)\n mock_query_class.assert_called_with(sql='test_sql', data_sources={'foo_data_source': mock_external_data_source.return_value})\n mock_external_data_source.assert_called_with(source='foo_path', schema=google.datalab.bigquery.Schema(TestCases.test_schema))\n", "method_code": " def execute(self, context):\n table = bq.Table(self.table, context=None)\n if not table.exists():\n table.create(schema=self.schema)\n kwargs = {}\n if 'delimiter' in self.csv_options:\n kwargs['delimiter'] = self.csv_options['delimiter']\n if 'skip' in self.csv_options:\n kwargs['skip_leading_rows'] = self.csv_options['skip']\n if 'strict' in self.csv_options:\n kwargs['allow_jagged_rows'] = self.csv_options['strict']\n if 'quote' in self.csv_options:\n kwargs['quote'] = self.csv_options['quote']\n csv_options = bq.CSVOptions(**kwargs)\n job = table.load(self.path, mode=self.mode, source_format='csv' if self.format == 'csv' else 'NEWLINE_DELIMITED_JSON', csv_options=csv_options, ignore_unknown_values=not self.csv_options.get('strict'))\n if job.failed:\n raise Exception('Load failed: %s' % str(job.fatal_error))\n elif job.errors:\n raise Exception('Load completed with errors: %s' % str(job.errors))\n return {'result': job.result()}\n ", "context": "class LoadOperator(BaseOperator):\n def execute(self, context): ...\n def __init__(self, table, path, mode='append', format='csv', schema=None, csv_options=None, *args, **kwargs): ...\n\n self.table = table\n self.path = path\n self.mode = mode\n self.format = format\n self.csv_options = csv_options or {}\n self.schema = schema\n\n template_fields = ('table', 'path')\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001367.py"} {"focal_file": "google/datalab/contrib/bigquery/operators/_bq_load_operator.py", "focal_class": "LoadOperator", "focal_method": "execute", "tests": "import unittest\n\nclass Test_LoadOperator_execute(unittest.TestCase):\n @mock.patch('google.datalab.Context.default')\n @mock.patch('google.datalab.bigquery._api.Api.tables_insert')\n @mock.patch('google.datalab.bigquery.Table.create')\n @mock.patch('google.datalab.bigquery.Table.exists')\n @mock.patch('google.datalab.bigquery.Table.load')\n def test_load_operator(self, mock_table_load, mock_table_exists, mock_table_create, mock_api_tables_insert, mock_context_default):\n mock_context_default.return_value = self._create_context()\n mock_table_exists.return_value = True\n load_operator = LoadOperator(table=TestCases.test_table_name, path='test/path', mode='append', format=None, csv_options=None, schema=None, task_id='test_operator_id')\n mock_job = mock.Mock()\n mock_job.result.return_value = 'test-result'\n mock_job.failed = False\n mock_job.errors = False\n mock_table_load.return_value = mock_job\n load_operator.execute(context=None)\n mock_table_load.assert_called_with('test/path', mode='append', source_format='NEWLINE_DELIMITED_JSON', csv_options=mock.ANY, ignore_unknown_values=True)\n mock_table_exists.return_value = False\n csv_options = {'delimiter': 'f', 'skip': 9, 'strict': True, 'quote': '\"'}\n schema = [{'type': 'INTEGER', 'name': 'key'}, {'type': 'FLOAT', 'name': 'var1'}, {'type': 'FLOAT', 'name': 'var2'}]\n load_operator = LoadOperator(table=TestCases.test_table_name, path='test/path', mode='append', format=None, csv_options=csv_options, schema=schema, task_id='test_operator_id')\n mock_job = mock.Mock()\n mock_job.result.return_value = 'test-result'\n mock_job.failed = False\n mock_job.errors = False\n mock_table_load.return_value = mock_job\n load_operator.execute(context=None)\n mock_table_load.assert_called_with('test/path', mode='append', source_format='NEWLINE_DELIMITED_JSON', csv_options=mock.ANY, ignore_unknown_values=False)\n mock_table_create.assert_called_with(schema=schema)\n load_operator = LoadOperator(table=TestCases.test_table_name, path='test/path', mode='append', format=None, csv_options=None, schema=schema, task_id='test_operator_id')\n mock_job = mock.Mock()\n mock_job.failed = True\n mock_job.fatal_error = 'fatal error'\n mock_table_load.return_value = mock_job\n with self.assertRaisesRegexp(Exception, 'Load failed: fatal error'):\n load_operator.execute(context=None)\n load_operator = LoadOperator(table=TestCases.test_table_name, path='test/path', mode='append', format=None, csv_options=None, schema=TestCases.test_schema, task_id='test_operator_id')\n mock_job = mock.Mock()\n mock_job.failed = False\n mock_job.errors = 'error'\n mock_table_load.return_value = mock_job\n with self.assertRaisesRegexp(Exception, 'Load completed with errors: error'):\n load_operator.execute(context=None)\n", "method_code": " def execute(self, context):\n table = bq.Table(self.table, context=None)\n if not table.exists():\n table.create(schema=self.schema)\n kwargs = {}\n if 'delimiter' in self.csv_options:\n kwargs['delimiter'] = self.csv_options['delimiter']\n if 'skip' in self.csv_options:\n kwargs['skip_leading_rows'] = self.csv_options['skip']\n if 'strict' in self.csv_options:\n kwargs['allow_jagged_rows'] = self.csv_options['strict']\n if 'quote' in self.csv_options:\n kwargs['quote'] = self.csv_options['quote']\n csv_options = bq.CSVOptions(**kwargs)\n job = table.load(self.path, mode=self.mode, source_format='csv' if self.format == 'csv' else 'NEWLINE_DELIMITED_JSON', csv_options=csv_options, ignore_unknown_values=not self.csv_options.get('strict'))\n if job.failed:\n raise Exception('Load failed: %s' % str(job.fatal_error))\n elif job.errors:\n raise Exception('Load completed with errors: %s' % str(job.errors))\n return {'result': job.result()}\n ", "context": "class LoadOperator(BaseOperator):\n def execute(self, context): ...\n def __init__(self, table, path, mode='append', format='csv', schema=None, csv_options=None, *args, **kwargs): ...\n\n self.table = table\n self.path = path\n self.mode = mode\n self.format = format\n self.csv_options = csv_options or {}\n self.schema = schema\n\n template_fields = ('table', 'path')\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001368.py"} {"focal_file": "google/datalab/utils/commands/_utils.py", "focal_class": null, "focal_method": "expand_var", "tests": "import unittest\n\nclass Test_expand_var(unittest.TestCase):\n def test_expand_var(self):\n env = {'var': 'test-var-value'}\n resolved = _utils.expand_var('$var', env)\n self.assertEqual(resolved, env['var'])\n resolved = _utils.expand_var('', env)\n self.assertEqual(resolved, '')\n with self.assertRaisesRegexp(Exception, 'Cannot expand variable'):\n _utils.expand_var('$badname', env)\n", "method_code": "def expand_var(v, env):\n \"\"\" If v is a variable reference (for example: '$myvar'), replace it using the supplied\n env dictionary.\n\n Args:\n v: the variable to replace if needed.\n env: user supplied dictionary.\n\n Raises:\n Exception if v is a variable reference but it is not found in env.\n \"\"\"\n if len(v) == 0:\n return v\n if v[0] == '$':\n v = v[1:]\n if len(v) and v[0] != '$':\n if v in env:\n v = env[v]\n else:\n raise Exception('Cannot expand variable $%s' % v)\n return v", "context": "def expand_var(v, env): ...\ndef notebook_environment(): ...\ndef get_notebook_item(name): ...\ndef render_list(data): ...\ndef render_dictionary(data, headers=None): ...\ndef render_text(text, preformatted=False): ...\ndef get_field_list(fields, schema): ...\ndef _get_cols(fields, schema): ...\ndef _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_lists(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): ...\ndef handle_magic_line(line, cell, parser, namespace=None): ...\ndef expand_var(v, env): ...\ndef replace_vars(config, env): ...\ndef parse_config(config, env, as_dict=True): ...\ndef parse_config_for_selected_keys(content, keys): ...\ndef validate_config(config, required_keys, optional_keys=None): ...\ndef validate_config_must_have(config, required_keys): ...\ndef validate_config_has_one_of(config, one_of_keys): ...\ndef validate_config_value(value, possible_values): ...\ndef get_data_source_index(name): ...\ndef validate_gcs_path(path, require_object): ...\ndef parse_control_options(controls, variable_defaults=None): ...\ndef chart_html(driver_name, chart_type, source, chart_options=None, fields='*', refresh_interval=0, refresh_data=None, control_defaults=None, control_ids=None, schema=None): ...\ndef profile_df(df): ...\n", "repository": "googledatalab/pydatalab", "test_name": "test_expand_var", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001369.py"} {"focal_file": "google/datalab/utils/commands/_utils.py", "focal_class": null, "focal_method": "replace_vars", "tests": "import unittest\n\nclass Test_replace_vars(unittest.TestCase):\n def test_replace_vars(self):\n config = {'var': '$value'}\n env = {'value': 5}\n _utils.replace_vars(config, env)\n self.assertEqual(config, {'var': 5})\n config = ['$value']\n _utils.replace_vars(config, env)\n self.assertEqual(config, [5])\n config = ({'var1': '$value1'}, ['$value2'])\n env = {'value1': 5, 'value2': 'stringvalue'}\n _utils.replace_vars(config, env)\n self.assertEqual(config, ({'var1': 5}, ['stringvalue']))\n", "method_code": "def replace_vars(config, env):\n \"\"\" Replace variable references in config using the supplied env dictionary.\n\n Args:\n config: the config to parse. Can be a tuple, list or dict.\n env: user supplied dictionary.\n\n Raises:\n Exception if any variable references are not found in env.\n \"\"\"\n if isinstance(config, dict):\n for k, v in list(config.items()):\n if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple):\n replace_vars(v, env)\n elif isinstance(v, basestring):\n config[k] = expand_var(v, env)\n elif isinstance(config, list):\n for i, v in enumerate(config):\n if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple):\n replace_vars(v, env)\n elif isinstance(v, basestring):\n config[i] = expand_var(v, env)\n elif isinstance(config, tuple):\n for v in config:\n if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple):\n replace_vars(v, env)", "context": "def replace_vars(config, env): ...\ndef notebook_environment(): ...\ndef get_notebook_item(name): ...\ndef render_list(data): ...\ndef render_dictionary(data, headers=None): ...\ndef render_text(text, preformatted=False): ...\ndef get_field_list(fields, schema): ...\ndef _get_cols(fields, schema): ...\ndef _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_lists(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): ...\ndef handle_magic_line(line, cell, parser, namespace=None): ...\ndef expand_var(v, env): ...\ndef replace_vars(config, env): ...\ndef parse_config(config, env, as_dict=True): ...\ndef parse_config_for_selected_keys(content, keys): ...\ndef validate_config(config, required_keys, optional_keys=None): ...\ndef validate_config_must_have(config, required_keys): ...\ndef validate_config_has_one_of(config, one_of_keys): ...\ndef validate_config_value(value, possible_values): ...\ndef get_data_source_index(name): ...\ndef validate_gcs_path(path, require_object): ...\ndef parse_control_options(controls, variable_defaults=None): ...\ndef chart_html(driver_name, chart_type, source, chart_options=None, fields='*', refresh_interval=0, refresh_data=None, control_defaults=None, control_ids=None, schema=None): ...\ndef profile_df(df): ...\n", "repository": "googledatalab/pydatalab", "test_name": "test_replace_vars", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001370.py"} {"focal_file": "google/datalab/utils/commands/_utils.py", "focal_class": null, "focal_method": "validate_config", "tests": "import unittest\n\nclass Test_validate_config(unittest.TestCase):\n def test_validate_config(self):\n with self.assertRaisesRegexp(Exception, 'config is not dict type'):\n _utils.validate_config([], [])\n config = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n _utils.validate_config(config, ['key1', 'key2'], ['key3'])\n _utils.validate_config(config, [], ['key1', 'key2', 'key3'])\n _utils.validate_config(config, ['key1', 'key2', 'key3'])\n with self.assertRaisesRegexp(Exception, 'Invalid config with unexpected keys'):\n _utils.validate_config(config, ['key1', 'key2'])\n with self.assertRaisesRegexp(Exception, 'Invalid config with missing keys'):\n _utils.validate_config(config, ['key1', 'key2', 'key3', 'key4'])\n", "method_code": "def validate_config(config, required_keys, optional_keys=None):\n \"\"\" Validate a config dictionary to make sure it includes all required keys\n and does not include any unexpected keys.\n\n Args:\n config: the config to validate.\n required_keys: the names of the keys that the config must have.\n optional_keys: the names of the keys that the config can have.\n\n Raises:\n Exception if the config is not a dict or invalid.\n \"\"\"\n if optional_keys is None:\n optional_keys = []\n if not isinstance(config, dict):\n raise Exception('config is not dict type')\n invalid_keys = set(config) - set(required_keys + optional_keys)\n if len(invalid_keys) > 0:\n raise Exception('Invalid config with unexpected keys \"%s\"' % ', '.join((e for e in invalid_keys)))\n missing_keys = set(required_keys) - set(config)\n if len(missing_keys) > 0:\n raise Exception('Invalid config with missing keys \"%s\"' % ', '.join(missing_keys))", "context": "def validate_config(config, required_keys, optional_keys=None): ...\ndef notebook_environment(): ...\ndef get_notebook_item(name): ...\ndef render_list(data): ...\ndef render_dictionary(data, headers=None): ...\ndef render_text(text, preformatted=False): ...\ndef get_field_list(fields, schema): ...\ndef _get_cols(fields, schema): ...\ndef _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_lists(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): ...\ndef handle_magic_line(line, cell, parser, namespace=None): ...\ndef expand_var(v, env): ...\ndef replace_vars(config, env): ...\ndef parse_config(config, env, as_dict=True): ...\ndef parse_config_for_selected_keys(content, keys): ...\ndef validate_config(config, required_keys, optional_keys=None): ...\ndef validate_config_must_have(config, required_keys): ...\ndef validate_config_has_one_of(config, one_of_keys): ...\ndef validate_config_value(value, possible_values): ...\ndef get_data_source_index(name): ...\ndef validate_gcs_path(path, require_object): ...\ndef parse_control_options(controls, variable_defaults=None): ...\ndef chart_html(driver_name, chart_type, source, chart_options=None, fields='*', refresh_interval=0, refresh_data=None, control_defaults=None, control_ids=None, schema=None): ...\ndef profile_df(df): ...\n", "repository": "googledatalab/pydatalab", "test_name": "test_validate_config", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001371.py"} {"focal_file": "google/datalab/utils/commands/_utils.py", "focal_class": null, "focal_method": "validate_config_must_have", "tests": "import unittest\n\nclass Test_validate_config_must_have(unittest.TestCase):\n def test_validate_config_must_have(self):\n config = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n _utils.validate_config_must_have(config, ['key1', 'key2'])\n with self.assertRaisesRegexp(Exception, 'Invalid config with missing keys'):\n _utils.validate_config_must_have(config, ['key1', 'key4'])\n", "method_code": "def validate_config_must_have(config, required_keys):\n \"\"\" Validate a config dictionary to make sure it has all of the specified keys\n\n Args:\n config: the config to validate.\n required_keys: the list of possible keys that config must include.\n\n Raises:\n Exception if the config does not have any of them.\n \"\"\"\n missing_keys = set(required_keys) - set(config)\n if len(missing_keys) > 0:\n raise Exception('Invalid config with missing keys \"%s\"' % ', '.join(missing_keys))", "context": "def validate_config_must_have(config, required_keys): ...\ndef notebook_environment(): ...\ndef get_notebook_item(name): ...\ndef render_list(data): ...\ndef render_dictionary(data, headers=None): ...\ndef render_text(text, preformatted=False): ...\ndef get_field_list(fields, schema): ...\ndef _get_cols(fields, schema): ...\ndef _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_lists(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): ...\ndef handle_magic_line(line, cell, parser, namespace=None): ...\ndef expand_var(v, env): ...\ndef replace_vars(config, env): ...\ndef parse_config(config, env, as_dict=True): ...\ndef parse_config_for_selected_keys(content, keys): ...\ndef validate_config(config, required_keys, optional_keys=None): ...\ndef validate_config_must_have(config, required_keys): ...\ndef validate_config_has_one_of(config, one_of_keys): ...\ndef validate_config_value(value, possible_values): ...\ndef get_data_source_index(name): ...\ndef validate_gcs_path(path, require_object): ...\ndef parse_control_options(controls, variable_defaults=None): ...\ndef chart_html(driver_name, chart_type, source, chart_options=None, fields='*', refresh_interval=0, refresh_data=None, control_defaults=None, control_ids=None, schema=None): ...\ndef profile_df(df): ...\n", "repository": "googledatalab/pydatalab", "test_name": "test_validate_config_must_have", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001372.py"} {"focal_file": "google/datalab/utils/commands/_utils.py", "focal_class": null, "focal_method": "validate_config_has_one_of", "tests": "import unittest\n\nclass Test_validate_config_has_one_of(unittest.TestCase):\n def test_validate_config_has_one_of(self):\n config = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n _utils.validate_config_has_one_of(config, ['key1'])\n with self.assertRaisesRegexp(Exception, 'Only one of the values'):\n _utils.validate_config_has_one_of(config, ['key1', 'key2', 'key3'])\n with self.assertRaisesRegexp(Exception, 'One of the values in'):\n _utils.validate_config_has_one_of(config, ['key4', 'key5'])\n", "method_code": "def validate_config_has_one_of(config, one_of_keys):\n \"\"\" Validate a config dictionary to make sure it has one and only one\n key in one_of_keys.\n\n Args:\n config: the config to validate.\n one_of_keys: the list of possible keys that config can have one and only one.\n\n Raises:\n Exception if the config does not have any of them, or multiple of them.\n \"\"\"\n intersection = set(config).intersection(one_of_keys)\n if len(intersection) > 1:\n raise Exception('Only one of the values in \"%s\" is needed' % ', '.join(intersection))\n if len(intersection) == 0:\n raise Exception('One of the values in \"%s\" is needed' % ', '.join(one_of_keys))", "context": "def validate_config_has_one_of(config, one_of_keys): ...\ndef notebook_environment(): ...\ndef get_notebook_item(name): ...\ndef render_list(data): ...\ndef render_dictionary(data, headers=None): ...\ndef render_text(text, preformatted=False): ...\ndef get_field_list(fields, schema): ...\ndef _get_cols(fields, schema): ...\ndef _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_lists(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): ...\ndef handle_magic_line(line, cell, parser, namespace=None): ...\ndef expand_var(v, env): ...\ndef replace_vars(config, env): ...\ndef parse_config(config, env, as_dict=True): ...\ndef parse_config_for_selected_keys(content, keys): ...\ndef validate_config(config, required_keys, optional_keys=None): ...\ndef validate_config_must_have(config, required_keys): ...\ndef validate_config_has_one_of(config, one_of_keys): ...\ndef validate_config_value(value, possible_values): ...\ndef get_data_source_index(name): ...\ndef validate_gcs_path(path, require_object): ...\ndef parse_control_options(controls, variable_defaults=None): ...\ndef chart_html(driver_name, chart_type, source, chart_options=None, fields='*', refresh_interval=0, refresh_data=None, control_defaults=None, control_ids=None, schema=None): ...\ndef profile_df(df): ...\n", "repository": "googledatalab/pydatalab", "test_name": "test_validate_config_has_one_of", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001373.py"} {"focal_file": "google/datalab/utils/commands/_utils.py", "focal_class": null, "focal_method": "validate_config_value", "tests": "import unittest\n\nclass Test_validate_config_value(unittest.TestCase):\n def test_validate_config_value(self):\n _utils.validate_config_value('val', ['val', 'val1', 'val2'])\n with self.assertRaisesRegexp(Exception, 'Invalid config value'):\n _utils.validate_config_value('val', ['val0', 'val1', 'val2'])\n", "method_code": "def validate_config_value(value, possible_values):\n \"\"\" Validate a config value to make sure it is one of the possible values.\n\n Args:\n value: the config value to validate.\n possible_values: the possible values the value can be\n\n Raises:\n Exception if the value is not one of possible values.\n \"\"\"\n if value not in possible_values:\n raise Exception('Invalid config value \"%s\". Possible values are %s' % (value, ', '.join((e for e in possible_values))))", "context": "def validate_config_value(value, possible_values): ...\ndef notebook_environment(): ...\ndef get_notebook_item(name): ...\ndef render_list(data): ...\ndef render_dictionary(data, headers=None): ...\ndef render_text(text, preformatted=False): ...\ndef get_field_list(fields, schema): ...\ndef _get_cols(fields, schema): ...\ndef _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_lists(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): ...\ndef handle_magic_line(line, cell, parser, namespace=None): ...\ndef expand_var(v, env): ...\ndef replace_vars(config, env): ...\ndef parse_config(config, env, as_dict=True): ...\ndef parse_config_for_selected_keys(content, keys): ...\ndef validate_config(config, required_keys, optional_keys=None): ...\ndef validate_config_must_have(config, required_keys): ...\ndef validate_config_has_one_of(config, one_of_keys): ...\ndef validate_config_value(value, possible_values): ...\ndef get_data_source_index(name): ...\ndef validate_gcs_path(path, require_object): ...\ndef parse_control_options(controls, variable_defaults=None): ...\ndef chart_html(driver_name, chart_type, source, chart_options=None, fields='*', refresh_interval=0, refresh_data=None, control_defaults=None, control_ids=None, schema=None): ...\ndef profile_df(df): ...\n", "repository": "googledatalab/pydatalab", "test_name": "test_validate_config_value", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001374.py"} {"focal_file": "google/datalab/utils/commands/_utils.py", "focal_class": null, "focal_method": "validate_gcs_path", "tests": "import unittest\n\nclass Test_validate_gcs_path(unittest.TestCase):\n def test_validate_gcs_path(self):\n _utils.validate_gcs_path('gs://testbucket/path/to/object', False)\n with self.assertRaisesRegexp(Exception, 'Invalid GCS path'):\n _utils.validate_gcs_path('path/to/object', False)\n _utils.validate_gcs_path('gs://path', False)\n with self.assertRaisesRegexp(Exception, 'It appears the GCS path \"gs://path\" is a bucket'):\n _utils.validate_gcs_path('gs://path', True)\n", "method_code": "def validate_gcs_path(path, require_object):\n \"\"\" Check whether a given path is a valid GCS path.\n\n Args:\n path: the config to check.\n require_object: if True, the path has to be an object path but not bucket path.\n\n Raises:\n Exception if the path is invalid\n \"\"\"\n bucket, key = google.datalab.storage._bucket.parse_name(path)\n if bucket is None:\n raise Exception('Invalid GCS path \"%s\"' % path)\n if require_object and key is None:\n raise Exception('It appears the GCS path \"%s\" is a bucket path but not an object path' % path)", "context": "def validate_gcs_path(path, require_object): ...\ndef notebook_environment(): ...\ndef get_notebook_item(name): ...\ndef render_list(data): ...\ndef render_dictionary(data, headers=None): ...\ndef render_text(text, preformatted=False): ...\ndef get_field_list(fields, schema): ...\ndef _get_cols(fields, schema): ...\ndef _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_list_of_lists(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): ...\ndef get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): ...\ndef handle_magic_line(line, cell, parser, namespace=None): ...\ndef expand_var(v, env): ...\ndef replace_vars(config, env): ...\ndef parse_config(config, env, as_dict=True): ...\ndef parse_config_for_selected_keys(content, keys): ...\ndef validate_config(config, required_keys, optional_keys=None): ...\ndef validate_config_must_have(config, required_keys): ...\ndef validate_config_has_one_of(config, one_of_keys): ...\ndef validate_config_value(value, possible_values): ...\ndef get_data_source_index(name): ...\ndef validate_gcs_path(path, require_object): ...\ndef parse_control_options(controls, variable_defaults=None): ...\ndef chart_html(driver_name, chart_type, source, chart_options=None, fields='*', refresh_interval=0, refresh_data=None, control_defaults=None, control_ids=None, schema=None): ...\ndef profile_df(df): ...\n", "repository": "googledatalab/pydatalab", "test_name": "test_validate_gcs_path", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001375.py"} {"focal_file": "google/datalab/utils/commands/_utils.py", "focal_class": null, "focal_method": "parse_control_options", "tests": "import unittest\n\nclass Test_parse_control_options(unittest.TestCase):\n def test_parse_control_options_badtype(self):\n control = {'label': None, 'type': 'badtype'}\n with self.assertRaisesRegexp(Exception, 'Unknown control type badtype'):\n _utils.parse_control_options({'test-control': control})\n\n def test_parse_control_options_set(self):\n control = {'label': None, 'choices': ['v1', 'v2'], 'min': 0, 'max': 10, 'step': 2}\n defaults = {'test-control': ['value1', 'value2']}\n control_html = _utils.parse_control_options({'test-control': control}, defaults)\n self.assertIn('class=\"gchart-control\"', control_html[0])\n self.assertIn(' 0 or byte_count is not None:\n header = 'bytes=%d-' % start_offset\n if byte_count is not None:\n header += '%d' % byte_count\n headers['Range'] = header\n url = Api._DOWNLOAD_ENDPOINT + Api._OBJECT_PATH % (bucket, Api._escape_key(key))\n return google.datalab.utils.Http.request(url, args=args, headers=headers, credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001394.py"} {"focal_file": "google/datalab/storage/_api.py", "focal_class": null, "focal_method": "object_upload", "tests": "import unittest\n\nclass Test_object_upload(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_object_upload(self, mock_http_request):\n api = TestCases._create_api()\n api.object_upload('b', 'k', 'c', 't')\n self.validate(mock_http_request, 'https://www.googleapis.com/upload/storage/v1/b/b/o/', expected_args={'uploadType': 'media', 'name': 'k'}, expected_data='c', expected_headers={'Content-Type': 't'})\n", "method_code": " def object_upload(self, bucket, key, content, content_type):\n \"\"\"Writes text content to the object.\n \n Args:\n bucket: the name of the bucket containing the object.\n key: the key of the object to be written.\n content: the text content to be written.\n content_type: the type of text content.\n Raises:\n Exception if the object could not be written to.\n \"\"\"\n args = {'uploadType': 'media', 'name': key}\n headers = {'Content-Type': content_type}\n url = Api._UPLOAD_ENDPOINT + Api._OBJECT_PATH % (bucket, '')\n return google.datalab.utils.Http.request(url, args=args, data=content, headers=headers, credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def object_upload(self, bucket, key, content, content_type): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001395.py"} {"focal_file": "google/datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_copy", "tests": "import unittest\n\nclass Test_objects_copy(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_objects_copy(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_copy('sb', 'sk', 'tb', 'tk')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/sb/o/sk/copyTo/b/tb/o/tk', expected_method='POST')\n", "method_code": " def objects_copy(self, source_bucket, source_key, target_bucket, target_key):\n \"\"\"Updates the metadata associated with an object.\n \n Args:\n source_bucket: the name of the bucket containing the source object.\n source_key: the key of the source object being copied.\n target_bucket: the name of the bucket that will contain the copied object.\n target_key: the key of the copied object.\n Returns:\n A parsed object information dictionary.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._OBJECT_COPY_PATH % (source_bucket, Api._escape_key(source_key), target_bucket, Api._escape_key(target_key))\n return google.datalab.utils.Http.request(url, method='POST', credentials=self._credentials)\n ", "context": "class Api(object):\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001396.py"} {"focal_file": "google/datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_delete", "tests": "import unittest\n\nclass Test_objects_delete(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_objects_delete(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_delete('b', 'k')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/k', expected_method='DELETE')\n", "method_code": " def objects_delete(self, bucket, key):\n \"\"\"Deletes the specified object.\n \n Args:\n bucket: the name of the bucket.\n key: the key of the object within the bucket.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._OBJECT_PATH % (bucket, Api._escape_key(key))\n google.datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)\n ", "context": "class Api(object):\n def objects_delete(self, bucket, key): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001397.py"} {"focal_file": "google/datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_get", "tests": "import unittest\n\nclass Test_objects_get(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_objects_get(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_get('b', 'k')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/k', expected_args={'projection': 'noAcl'})\n api.objects_get('b', 'k', 'p')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/k', expected_args={'projection': 'p'})\n", "method_code": " def objects_get(self, bucket, key, projection='noAcl'):\n \"\"\"Issues a request to retrieve information about an object.\n \n Args:\n bucket: the name of the bucket.\n key: the key of the object within the bucket.\n projection: the projection of the object to retrieve.\n Returns:\n A parsed object information dictionary.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n args = {}\n if projection is not None:\n args['projection'] = projection\n url = Api._ENDPOINT + Api._OBJECT_PATH % (bucket, Api._escape_key(key))\n return google.datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001398.py"} {"focal_file": "google/datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_list", "tests": "import unittest\n\nclass Test_objects_list(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_objects_list(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_list('b')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/', expected_args={'projection': 'noAcl', 'maxResults': 100})\n api.objects_list('b', 'p', 'd', 'pr', True, 99, 'foo')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/', expected_args={'projection': 'pr', 'maxResults': 99, 'prefix': 'p', 'delimiter': 'd', 'versions': 'true', 'pageToken': 'foo'})\n", "method_code": " def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None):\n \"\"\"Issues a request to retrieve information about an object.\n \n Args:\n bucket: the name of the bucket.\n prefix: an optional key prefix.\n delimiter: an optional key delimiter.\n projection: the projection of the objects to retrieve.\n versions: whether to list each version of a file as a distinct object.\n max_results: an optional maximum number of objects to retrieve.\n page_token: an optional token to continue the retrieval.\n Returns:\n A parsed list of object information dictionaries.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n if max_results == 0:\n max_results = Api._MAX_RESULTS\n args = {'maxResults': max_results}\n if prefix is not None:\n args['prefix'] = prefix\n if delimiter is not None:\n args['delimiter'] = delimiter\n if projection is not None:\n args['projection'] = projection\n if versions:\n args['versions'] = 'true'\n if page_token is not None:\n args['pageToken'] = page_token\n url = Api._ENDPOINT + Api._OBJECT_PATH % (bucket, '')\n return google.datalab.utils.Http.request(url, args=args, credentials=self._credentials)\n ", "context": "class Api(object):\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_patch(self, bucket, key, info): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001399.py"} {"focal_file": "google/datalab/storage/_api.py", "focal_class": null, "focal_method": "objects_patch", "tests": "import unittest\n\nclass Test_objects_patch(unittest.TestCase):\n @mock.patch('google.datalab.utils.Http.request')\n def test_objects_patch(self, mock_http_request):\n api = TestCases._create_api()\n api.objects_patch('b', 'k', 'i')\n self.validate(mock_http_request, 'https://www.googleapis.com/storage/v1/b/b/o/k', expected_method='PATCH', expected_data='i')\n", "method_code": " def objects_patch(self, bucket, key, info):\n \"\"\"Updates the metadata associated with an object.\n \n Args:\n bucket: the name of the bucket containing the object.\n key: the key of the object being updated.\n info: the metadata to update.\n Returns:\n A parsed object information dictionary.\n Raises:\n Exception if there is an error performing the operation.\n \"\"\"\n url = Api._ENDPOINT + Api._OBJECT_PATH % (bucket, Api._escape_key(key))\n return google.datalab.utils.Http.request(url, method='PATCH', data=info, credentials=self._credentials)\n ", "context": "class Api(object):\n def objects_patch(self, bucket, key, info): ...\n def __init__(self, context): ...\n def project_id(self): ...\n def buckets_insert(self, bucket, project_id=None): ...\n def buckets_delete(self, bucket): ...\n def buckets_get(self, bucket, projection='noAcl'): ...\n def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): ...\n def object_download(self, bucket, key, start_offset=0, byte_count=None): ...\n def object_upload(self, bucket, key, content, content_type): ...\n def objects_copy(self, source_bucket, source_key, target_bucket, target_key): ...\n def objects_delete(self, bucket, key): ...\n def objects_get(self, bucket, key, projection='noAcl'): ...\n def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): ...\n def _escape_key(key): ...\n def verify_permitted_to_read(gs_path): ...\n\n self._credentials = context.credentials\n self._project_id = context.project_id\n\n _ENDPOINT = 'https://www.googleapis.com/storage/v1'\n _DOWNLOAD_ENDPOINT = 'https://www.googleapis.com/download/storage/v1'\n _UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload/storage/v1'\n _BUCKET_PATH = '/b/%s'\n _OBJECT_PATH = '/b/%s/o/%s'\n _OBJECT_COPY_PATH = '/b/%s/o/%s/copyTo/b/%s/o/%s'\n _MAX_RESULTS = 100\n", "repository": "googledatalab/pydatalab", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001400.py"} {"focal_file": "pygom/model/common_models.py", "focal_class": null, "focal_method": "SIR", "tests": "import unittest\n\nclass Test_SIR(unittest.TestCase):\n def test_SIR(self):\n \"\"\"\n Test the SIR model from the set of pre-defined models in common_models\n \"\"\"\n ode = common_models.SIR()\n param_eval = [('beta', 0.5), ('gamma', 1.0 / 3.0)]\n ode.parameters = param_eval\n initial_state = [1, 1.27e-06, 0]\n ode.ode(initial_state, 1)\n ode.jacobian(initial_state, 1)\n ode.grad(initial_state, 1)\n ode.sensitivity(numpy.zeros(6), 1, initial_state)\n ode.linear_ode()\n t = numpy.linspace(1, 150, 100)\n _solution, output = scipy.integrate.odeint(ode.ode, initial_state, t, full_output=True)\n self.assertTrue(output['message'] == 'Integration successful.')\n", "method_code": "def SIR(param=None):\n \"\"\"\n A standard SIR model as per [Brauer2008]_\n\n .. math::\n \\\\frac{dS}{dt} &= -\\\\beta SI \\\\\\\\\n \\\\frac{dI}{dt} &= \\\\beta SI - \\\\gamma I \\\\\\\\\n \\\\frac{dR}{dt} &= \\\\gamma I\n\n\n Examples\n --------\n The model that produced top two graph in Figure 1.3 of the reference above.\n First, when everyone is susceptible and only one individual was infected.\n\n >>> import numpy as np\n >>> from pygom import common_models\n >>> ode = common_models.SIR({'beta':3.6, 'gamma':0.2})\n >>> t = np.linspace(0, 730, 1001)\n >>> N = 7781984.0\n >>> x0 = [1.0, 10/N, 0.0]\n >>> ode.initial_values = (x0, t[0])\n >>> solution = ode.integrate(t[1::])\n >>> ode.plot()\n\n Second model with a more *realistic* scenario\n\n >>> import numpy as np\n >>> from pygom import common_models\n >>> ode = common_models.SIR({'beta':3.6, 'gamma':0.2})\n >>> t = np.linspace(0, 730, 1001)\n >>> N = 7781984.0\n >>> x0 = [0.065, 123*(5.0/30.0)/N, 0.0]\n >>> ode.initial_values = (x0, t[0])\n >>> solution = ode.integrate(t[1::])\n >>> ode.plot()\n\n \"\"\"\n state = ['S', 'I', 'R']\n param_list = ['beta', 'gamma']\n transition = [Transition(origin='S', destination='I', equation='beta*S*I', transition_type=TransitionType.T), Transition(origin='I', destination='R', equation='gamma*I', transition_type=TransitionType.T)]\n ode_obj = DeterministicOde(state, param_list, transition=transition)\n if param is None:\n return ode_obj\n else:\n ode_obj.parameters = param\n return ode_obj", "context": "def SIR(param=None): ...\ndef SIS(param=None): ...\ndef SIS_Periodic(param=None): ...\ndef SIR(param=None): ...\ndef SIR_N(param=None): ...\ndef SIR_Birth_Death(param=None): ...\ndef SEIR(param=None): ...\ndef SEIR_Birth_Death(param=None): ...\ndef SEIR_Birth_Death_Periodic(param=None): ...\ndef SEIR_Multiple(n=2, param=None): ...\ndef Influenza_SLIARN(param=None): ...\ndef Legrand_Ebola_SEIHFR(param=None): ...\ndef Lotka_Volterra(param=None): ...\ndef Lotka_Volterra_4State(param=None): ...\ndef FitzHugh(param=None): ...\ndef Lorenz(param=None): ...\ndef vanDelPol(param=None): ...\ndef Robertson(param=None): ...\n", "repository": "publichealthengland/pygom", "test_name": "test_SIR", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001401.py"} {"focal_file": "bitbake/lib/bb/data.py", "focal_class": null, "focal_method": "keys", "tests": "import unittest\n\nclass Test_keys(unittest.TestCase):\n def test_keys(self):\n keys = list(self.d.keys())\n self.assertCountEqual(keys, ['value_of_foo', 'foo', 'bar'])\n", "method_code": "def keys(d):\n \"\"\"Return a list of keys in d\"\"\"\n return d.keys()", "context": "def keys(d): ...\ndef init(): ...\ndef init_db(parent=None): ...\ndef createCopy(source): ...\ndef initVar(var, d): ...\ndef keys(d): ...\ndef expand(s, d, varname=None): ...\ndef expandKeys(alterdata, readdata=None): ...\ndef inheritFromOS(d, savedenv, permitted): ...\ndef emit_var(var, o=sys.__stdout__, d=init(), all=False): ...\ndef emit_env(o=sys.__stdout__, d=init(), all=False): ...\ndef exported_keys(d): ...\ndef exported_vars(d): ...\ndef emit_func(func, o=sys.__stdout__, d=init()): ...\ndef emit_func_python(func, o=sys.__stdout__, d=init()): ...\ndef update_data(d): ...\ndef build_dependencies(key, keys, shelldeps, varflagsexcl, d): ...\ndef generate_dependencies(d, whitelist): ...\ndef generate_dependency_hash(tasklist, gendeps, lookupcache, whitelist, fn): ...\ndef inherits_class(klass, d): ...\n", "repository": "rugged-board/poky", "test_name": "test_keys", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001402.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": null, "focal_method": "get_class_handlers", "tests": "import unittest\n\nclass Test_get_class_handlers(unittest.TestCase):\n def test_class_handlers(self):\n \"\"\" Test set_class_handlers and get_class_handlers methods \"\"\"\n test_handlers = self._create_test_handlers()\n bb.event.set_class_handlers(test_handlers)\n self.assertEqual(test_handlers, bb.event.get_class_handlers())\n", "method_code": "def get_class_handlers():\n return _handlers", "context": "def get_class_handlers(): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_class_handlers", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001403.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": null, "focal_method": "set_handlers", "tests": "import unittest\n\nclass Test_set_handlers(unittest.TestCase):\n def test_handlers(self):\n \"\"\" Test set_handlers and get_handlers \"\"\"\n test_handlers = self._create_test_handlers()\n bb.event.set_handlers(test_handlers)\n self.assertEqual(test_handlers, bb.event.get_handlers())\n", "method_code": "def set_handlers(handlers):\n global _handlers\n _handlers = handlers", "context": "def set_handlers(handlers): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_handlers", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001404.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": null, "focal_method": "clean_class_handlers", "tests": "import unittest\n\nclass Test_clean_class_handlers(unittest.TestCase):\n def test_clean_class_handlers(self):\n \"\"\" Test clean_class_handlers method \"\"\"\n cleanDict = bb.compat.OrderedDict()\n self.assertEqual(cleanDict, bb.event.clean_class_handlers())\n", "method_code": "def clean_class_handlers():\n return bb.compat.OrderedDict()", "context": "def clean_class_handlers(): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_clean_class_handlers", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001405.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": null, "focal_method": "register", "tests": "import unittest\n\nclass Test_register(unittest.TestCase):\n def test_register(self):\n \"\"\" Test register method for class handlers \"\"\"\n result = bb.event.register('handler', self._test_process.handler)\n self.assertEqual(result, bb.event.Registered)\n handlers_dict = bb.event.get_class_handlers()\n self.assertIn('handler', handlers_dict)\n", "method_code": "def register(name, handler, mask=None, filename=None, lineno=None):\n \"\"\"Register an Event handler\"\"\"\n if name in _handlers:\n return AlreadyRegistered\n if handler is not None:\n if isinstance(handler, str):\n tmp = 'def %s(e):\\n%s' % (name, handler)\n try:\n code = bb.methodpool.compile_cache(tmp)\n if not code:\n if filename is None:\n filename = '%s(e)' % name\n code = compile(tmp, filename, 'exec', ast.PyCF_ONLY_AST)\n if lineno is not None:\n ast.increment_lineno(code, lineno - 1)\n code = compile(code, filename, 'exec')\n bb.methodpool.compile_cache_add(tmp, code)\n except SyntaxError:\n logger.error(\"Unable to register event handler '%s':\\n%s\", name, ''.join(traceback.format_exc(limit=0)))\n _handlers[name] = noop\n return\n env = {}\n bb.utils.better_exec(code, env)\n func = bb.utils.better_eval(name, env)\n _handlers[name] = func\n else:\n _handlers[name] = handler\n if not mask or '*' in mask:\n _catchall_handlers[name] = True\n else:\n for m in mask:\n if _event_handler_map.get(m, None) is None:\n _event_handler_map[m] = {}\n _event_handler_map[m][name] = True\n return Registered", "context": "def register(name, handler, mask=None, filename=None, lineno=None): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_register", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001406.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": null, "focal_method": "remove", "tests": "import unittest\n\nclass Test_remove(unittest.TestCase):\n def test_remove(self):\n \"\"\" Test remove method for class handlers \"\"\"\n test_handlers = self._create_test_handlers()\n bb.event.set_class_handlers(test_handlers)\n count = len(test_handlers)\n bb.event.remove('handler1', None)\n test_handlers = bb.event.get_class_handlers()\n self.assertEqual(len(test_handlers), count - 1)\n with self.assertRaises(KeyError):\n bb.event.remove('handler1', None)\n", "method_code": "def remove(name, handler):\n \"\"\"Remove an Event handler\"\"\"\n _handlers.pop(name)\n if name in _catchall_handlers:\n _catchall_handlers.pop(name)\n for event in _event_handler_map.keys():\n if name in _event_handler_map[event]:\n _event_handler_map[event].pop(name)", "context": "def remove(name, handler): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_remove", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001407.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": "bb.event.OperationProgress", "focal_method": "execute_handler", "tests": "import unittest\n\nclass Test_bb_event_OperationProgress_execute_handler(unittest.TestCase):\n def test_execute_handler(self):\n \"\"\" Test execute_handler method for class handlers \"\"\"\n mask = ['bb.event.OperationProgress']\n result = bb.event.register('event_handler', self._test_process.event_handler, mask)\n self.assertEqual(result, bb.event.Registered)\n event = bb.event.OperationProgress(current=10, total=100)\n bb.event.execute_handler('event_handler', self._test_process.event_handler, event, None)\n self._test_process.event_handler.assert_called_once_with(event)\n", "method_code": "def execute_handler(name, handler, event, d):\n event.data = d\n addedd = False\n if 'd' not in builtins:\n builtins['d'] = d\n addedd = True\n try:\n ret = handler(event)\n except (bb.parse.SkipRecipe, bb.BBHandledException):\n raise\n except Exception:\n etype, value, tb = sys.exc_info()\n logger.error(\"Execution of event handler '%s' failed\" % name, exc_info=(etype, value, tb.tb_next))\n raise\n except SystemExit as exc:\n if exc.code != 0:\n logger.error(\"Execution of event handler '%s' failed\" % name)\n raise\n finally:\n del event.data\n if addedd:\n del builtins['d']", "context": "def execute_handler(name, handler, event, d): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_execute_handler", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001408.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": "bb.event.OperationCompleted", "focal_method": "fire_class_handlers", "tests": "import unittest\n\nclass Test_bb_event_OperationCompleted_fire_class_handlers(unittest.TestCase):\n def test_fire_class_handlers(self):\n \"\"\" Test fire_class_handlers method \"\"\"\n mask = ['bb.event.OperationStarted']\n result = bb.event.register('event_handler1', self._test_process.event_handler1, mask)\n self.assertEqual(result, bb.event.Registered)\n result = bb.event.register('event_handler2', self._test_process.event_handler2, '*')\n self.assertEqual(result, bb.event.Registered)\n event1 = bb.event.OperationStarted()\n event2 = bb.event.OperationCompleted(total=123)\n bb.event.fire_class_handlers(event1, None)\n bb.event.fire_class_handlers(event2, None)\n bb.event.fire_class_handlers(event2, None)\n expected_event_handler1 = [call(event1)]\n expected_event_handler2 = [call(event1), call(event2), call(event2)]\n self.assertEqual(self._test_process.event_handler1.call_args_list, expected_event_handler1)\n self.assertEqual(self._test_process.event_handler2.call_args_list, expected_event_handler2)\n\n def test_class_handler_filters(self):\n \"\"\" Test filters for class handlers \"\"\"\n mask = ['bb.event.OperationStarted']\n result = bb.event.register('event_handler1', self._test_process.event_handler1, mask)\n self.assertEqual(result, bb.event.Registered)\n result = bb.event.register('event_handler2', self._test_process.event_handler2, '*')\n self.assertEqual(result, bb.event.Registered)\n bb.event.set_eventfilter(lambda name, handler, event, d: name == 'event_handler2' and bb.event.getName(event) == 'OperationStarted')\n event1 = bb.event.OperationStarted()\n event2 = bb.event.OperationCompleted(total=123)\n bb.event.fire_class_handlers(event1, None)\n bb.event.fire_class_handlers(event2, None)\n bb.event.fire_class_handlers(event2, None)\n expected_event_handler1 = []\n expected_event_handler2 = [call(event1)]\n self.assertEqual(self._test_process.event_handler1.call_args_list, expected_event_handler1)\n self.assertEqual(self._test_process.event_handler2.call_args_list, expected_event_handler2)\n", "method_code": "def fire_class_handlers(event, d):\n if isinstance(event, logging.LogRecord):\n return\n eid = str(event.__class__)[8:-2]\n evt_hmap = _event_handler_map.get(eid, {})\n for name, handler in list(_handlers.items()):\n if name in _catchall_handlers or name in evt_hmap:\n if _eventfilter:\n if not _eventfilter(name, handler, event, d):\n continue\n execute_handler(name, handler, event, d)", "context": "def fire_class_handlers(event, d): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_fire_class_handlers", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001409.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": null, "focal_method": "register_UIHhandler", "tests": "import unittest\n\nclass Test_register_UIHhandler(unittest.TestCase):\n def test_register_UIHhandler(self):\n \"\"\" Test register_UIHhandler method \"\"\"\n result = bb.event.register_UIHhandler(self._test_ui1, mainui=True)\n self.assertEqual(result, 1)\n\n def test_unregister_UIHhandler(self):\n \"\"\" Test unregister_UIHhandler method \"\"\"\n result = bb.event.register_UIHhandler(self._test_ui1, mainui=True)\n self.assertEqual(result, 1)\n result = bb.event.unregister_UIHhandler(1)\n self.assertIs(result, None)\n", "method_code": "def register_UIHhandler(handler, mainui=False):\n bb.event._ui_handler_seq = bb.event._ui_handler_seq + 1\n _ui_handlers[_ui_handler_seq] = handler\n level, debug_domains = bb.msg.constructLogOptions()\n _ui_logfilters[_ui_handler_seq] = UIEventFilter(level, debug_domains)\n if mainui:\n global _uiready\n _uiready = _ui_handler_seq\n return _ui_handler_seq", "context": "def register_UIHhandler(handler, mainui=False): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_register_UIHhandler", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001410.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": "bb.event.OperationStarted", "focal_method": "fire_ui_handlers", "tests": "import unittest\n\nclass Test_bb_event_OperationStarted_fire_ui_handlers(unittest.TestCase):\n def test_fire_ui_handlers(self):\n \"\"\" Test fire_ui_handlers method \"\"\"\n self._test_ui1.event = Mock(spec_set=EventQueueStub)\n result = bb.event.register_UIHhandler(self._test_ui1, mainui=True)\n self.assertEqual(result, 1)\n self._test_ui2.event = Mock(spec_set=PickleEventQueueStub)\n result = bb.event.register_UIHhandler(self._test_ui2, mainui=True)\n self.assertEqual(result, 2)\n event1 = bb.event.OperationStarted()\n bb.event.fire_ui_handlers(event1, None)\n expected = [call(event1)]\n self.assertEqual(self._test_ui1.event.send.call_args_list, expected)\n expected = [call(pickle.dumps(event1))]\n self.assertEqual(self._test_ui2.event.sendpickle.call_args_list, expected)\n\n def test_ui_handler_log_filter(self):\n \"\"\" Test log filters for UI handlers \"\"\"\n mask = ['*']\n debug_domains = {'BitBake.Foo': logging.WARNING}\n self._test_ui1.event = EventQueueStub()\n result = bb.event.register_UIHhandler(self._test_ui1, mainui=True)\n bb.event.set_UIHmask(result, logging.ERROR, debug_domains, mask)\n self._test_ui2.event = PickleEventQueueStub()\n result = bb.event.register_UIHhandler(self._test_ui2, mainui=True)\n bb.event.set_UIHmask(result, logging.ERROR, debug_domains, mask)\n event1 = bb.event.OperationStarted()\n bb.event.fire_ui_handlers(event1, None)\n event_log_handler = bb.event.LogHandler()\n logger = logging.getLogger('BitBake')\n logger.addHandler(event_log_handler)\n logger1 = logging.getLogger('BitBake.Foo')\n logger1.warning('Test warning LogRecord1')\n logger1.info('Test info LogRecord')\n logger2 = logging.getLogger('BitBake.Bar')\n logger2.error('Test error LogRecord')\n logger2.warning('Test warning LogRecord2')\n logger.removeHandler(event_log_handler)\n expected = ['OperationStarted', 'WARNING: Test warning LogRecord1', 'ERROR: Test error LogRecord']\n self.assertEqual(self._test_ui1.event.event_calls, expected)\n self.assertEqual(self._test_ui2.event.event_calls, expected)\n", "method_code": "def fire_ui_handlers(event, d):\n global _thread_lock\n global _thread_lock_enabled\n if not _uiready:\n ui_queue.append(event)\n return\n if _thread_lock_enabled:\n _thread_lock.acquire()\n errors = []\n for h in _ui_handlers:\n try:\n if not _ui_logfilters[h].filter(event):\n continue\n if hasattr(_ui_handlers[h].event, 'sendpickle'):\n _ui_handlers[h].event.sendpickle(pickle.dumps(event))\n else:\n _ui_handlers[h].event.send(event)\n except:\n errors.append(h)\n for h in errors:\n del _ui_handlers[h]\n if _thread_lock_enabled:\n _thread_lock.release()", "context": "def fire_ui_handlers(event, d): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_fire_ui_handlers", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001411.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": "bb.event.OperationCompleted", "focal_method": "fire_ui_handlers", "tests": "import unittest\n\nclass Test_bb_event_OperationCompleted_fire_ui_handlers(unittest.TestCase):\n def test_ui_handler_mask_filter(self):\n \"\"\" Test filters for UI handlers \"\"\"\n mask = ['bb.event.OperationStarted']\n debug_domains = {}\n self._test_ui1.event = Mock(spec_set=EventQueueStub)\n result = bb.event.register_UIHhandler(self._test_ui1, mainui=True)\n bb.event.set_UIHmask(result, logging.INFO, debug_domains, mask)\n self._test_ui2.event = Mock(spec_set=PickleEventQueueStub)\n result = bb.event.register_UIHhandler(self._test_ui2, mainui=True)\n bb.event.set_UIHmask(result, logging.INFO, debug_domains, mask)\n event1 = bb.event.OperationStarted()\n event2 = bb.event.OperationCompleted(total=1)\n bb.event.fire_ui_handlers(event1, None)\n bb.event.fire_ui_handlers(event2, None)\n expected = [call(event1)]\n self.assertEqual(self._test_ui1.event.send.call_args_list, expected)\n expected = [call(pickle.dumps(event1))]\n self.assertEqual(self._test_ui2.event.sendpickle.call_args_list, expected)\n", "method_code": "def fire_ui_handlers(event, d):\n global _thread_lock\n global _thread_lock_enabled\n if not _uiready:\n ui_queue.append(event)\n return\n if _thread_lock_enabled:\n _thread_lock.acquire()\n errors = []\n for h in _ui_handlers:\n try:\n if not _ui_logfilters[h].filter(event):\n continue\n if hasattr(_ui_handlers[h].event, 'sendpickle'):\n _ui_handlers[h].event.sendpickle(pickle.dumps(event))\n else:\n _ui_handlers[h].event.send(event)\n except:\n errors.append(h)\n for h in errors:\n del _ui_handlers[h]\n if _thread_lock_enabled:\n _thread_lock.release()", "context": "def fire_ui_handlers(event, d): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_ui_handler_mask_filter", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001412.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": "bb.event.ConfigParsed", "focal_method": "fire", "tests": "import unittest\n\nclass Test_bb_event_ConfigParsed_fire(unittest.TestCase):\n def test_fire(self):\n \"\"\" Test fire method used to trigger class and ui event handlers \"\"\"\n mask = ['bb.event.ConfigParsed']\n result = bb.event.register('event_handler1', self._test_process.event_handler1, mask)\n self._test_ui1.event = Mock(spec_set=EventQueueStub)\n result = bb.event.register_UIHhandler(self._test_ui1, mainui=True)\n self.assertEqual(result, 1)\n event1 = bb.event.ConfigParsed()\n bb.event.fire(event1, None)\n expected = [call(event1)]\n self.assertEqual(self._test_process.event_handler1.call_args_list, expected)\n self.assertEqual(self._test_ui1.event.send.call_args_list, expected)\n", "method_code": "def fire(event, d):\n \"\"\"Fire off an Event\"\"\"\n fire_class_handlers(event, d)\n if worker_fire:\n worker_fire(event, d)\n else:\n global _uiready, ui_queue\n if _uiready and ui_queue:\n for queue_event in ui_queue:\n fire_ui_handlers(queue_event, d)\n ui_queue = []\n fire_ui_handlers(event, d)", "context": "def fire(event, d): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_fire", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001413.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": "bb.event.ConfigParsed", "focal_method": "fire_from_worker", "tests": "import unittest\n\nclass Test_bb_event_ConfigParsed_fire_from_worker(unittest.TestCase):\n def test_fire_from_worker(self):\n \"\"\" Test fire_from_worker method \"\"\"\n self._test_ui1.event = Mock(spec_set=EventQueueStub)\n result = bb.event.register_UIHhandler(self._test_ui1, mainui=True)\n self.assertEqual(result, 1)\n event1 = bb.event.ConfigParsed()\n bb.event.fire_from_worker(event1, None)\n expected = [call(event1)]\n self.assertEqual(self._test_ui1.event.send.call_args_list, expected)\n", "method_code": "def fire_from_worker(event, d):\n fire_ui_handlers(event, d)", "context": "def fire_from_worker(event, d): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_fire_from_worker", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001414.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": "bb.event.Event", "focal_method": "fire", "tests": "import unittest\n\nclass Test_bb_event_Event_fire(unittest.TestCase):\n def test_worker_fire(self):\n \"\"\" Test the triggering of bb.event.worker_fire callback \"\"\"\n bb.event.worker_fire = Mock()\n event = bb.event.Event()\n bb.event.fire(event, None)\n expected = [call(event, None)]\n self.assertEqual(bb.event.worker_fire.call_args_list, expected)\n", "method_code": "def fire(event, d):\n \"\"\"Fire off an Event\"\"\"\n fire_class_handlers(event, d)\n if worker_fire:\n worker_fire(event, d)\n else:\n global _uiready, ui_queue\n if _uiready and ui_queue:\n for queue_event in ui_queue:\n fire_ui_handlers(queue_event, d)\n ui_queue = []\n fire_ui_handlers(event, d)", "context": "def fire(event, d): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_worker_fire", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001415.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": "bb.event.OperationCompleted", "focal_method": "print_ui_queue", "tests": "import unittest\n\nclass Test_bb_event_OperationCompleted_print_ui_queue(unittest.TestCase):\n def test_print_ui_queue(self):\n \"\"\" Test print_ui_queue method \"\"\"\n event1 = bb.event.OperationStarted()\n event2 = bb.event.OperationCompleted(total=123)\n bb.event.fire(event1, None)\n bb.event.fire(event2, None)\n event_log_handler = bb.event.LogHandler()\n logger = logging.getLogger('BitBake')\n logger.addHandler(event_log_handler)\n logger.info('Test info LogRecord')\n logger.warning('Test warning LogRecord')\n with self.assertLogs('BitBake', level='INFO') as cm:\n bb.event.print_ui_queue()\n logger.removeHandler(event_log_handler)\n self.assertEqual(cm.output, ['INFO:BitBake:Test info LogRecord', 'WARNING:BitBake:Test warning LogRecord'])\n", "method_code": "def print_ui_queue():\n global ui_queue\n \"If we're exiting before a UI has been spawned, display any queued\\n LogRecords to the console.\"\n logger = logging.getLogger('BitBake')\n if not _uiready:\n from bb.msg import BBLogFormatter\n sys.stdout.flush()\n sys.stderr.flush()\n stdout = logging.StreamHandler(sys.stdout)\n stderr = logging.StreamHandler(sys.stderr)\n formatter = BBLogFormatter('%(levelname)s: %(message)s')\n stdout.setFormatter(formatter)\n stderr.setFormatter(formatter)\n msgprint = False\n msgerrs = False\n for event in ui_queue[:]:\n if isinstance(event, logging.LogRecord) and event.levelno >= logging.WARNING:\n msgerrs = True\n break\n if msgerrs:\n logger.addHandler(stderr)\n else:\n logger.addHandler(stdout)\n for event in ui_queue[:]:\n if isinstance(event, logging.LogRecord):\n if event.levelno > logging.DEBUG:\n logger.handle(event)\n msgprint = True\n if not msgprint:\n for event in ui_queue[:]:\n if isinstance(event, logging.LogRecord):\n logger.handle(event)\n if msgerrs:\n logger.removeHandler(stderr)\n else:\n logger.removeHandler(stdout)\n ui_queue = []", "context": "@atexit.register\ndef print_ui_queue(): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_print_ui_queue", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001416.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": null, "focal_method": "enable_threadlock", "tests": "import unittest\n\nclass Test_enable_threadlock(unittest.TestCase):\n def test_enable_threadlock(self):\n \"\"\" Test enable_threadlock method \"\"\"\n self._set_threadlock_test_mockups()\n bb.event.enable_threadlock()\n self._set_and_run_threadlock_test_workers()\n self.assertEqual(self._threadlock_test_calls, ['w1_ui1', 'w1_ui2', 'w2_ui1', 'w2_ui2'])\n", "method_code": "def enable_threadlock():\n global _thread_lock_enabled\n _thread_lock_enabled = True", "context": "def enable_threadlock(): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_enable_threadlock", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001417.py"} {"focal_file": "bitbake/lib/bb/event.py", "focal_class": null, "focal_method": "disable_threadlock", "tests": "import unittest\n\nclass Test_disable_threadlock(unittest.TestCase):\n def test_disable_threadlock(self):\n \"\"\" Test disable_threadlock method \"\"\"\n self._set_threadlock_test_mockups()\n bb.event.disable_threadlock()\n self._set_and_run_threadlock_test_workers()\n self.assertEqual(self._threadlock_test_calls, ['w1_ui1', 'w2_ui1', 'w1_ui2', 'w2_ui2'])\n", "method_code": "def disable_threadlock():\n global _thread_lock_enabled\n _thread_lock_enabled = False", "context": "def disable_threadlock(): ...\ndef get_class_handlers(): ...\ndef set_class_handlers(h): ...\ndef clean_class_handlers(): ...\ndef enable_threadlock(): ...\ndef disable_threadlock(): ...\ndef execute_handler(name, handler, event, d): ...\ndef fire_class_handlers(event, d): ...\ndef print_ui_queue(): ...\ndef fire_ui_handlers(event, d): ...\ndef fire(event, d): ...\ndef fire_from_worker(event, d): ...\ndef register(name, handler, mask=None, filename=None, lineno=None): ...\ndef remove(name, handler): ...\ndef get_handlers(): ...\ndef set_handlers(handlers): ...\ndef set_eventfilter(func): ...\ndef register_UIHhandler(handler, mainui=False): ...\ndef unregister_UIHhandler(handlerNum, mainui=False): ...\ndef get_uihandler(): ...\ndef set_UIHmask(handlerNum, level, debug_domains, mask): ...\ndef getName(e): ...\n", "repository": "rugged-board/poky", "test_name": "test_disable_threadlock", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001418.py"} {"focal_file": "bitbake/lib/bs4/element.py", "focal_class": null, "focal_method": "decode", "tests": "import unittest\n\nclass Test_decode(unittest.TestCase):\n def test_real_shift_jis_document(self):\n shift_jis_html = b'
\\x82\\xb1\\x82\\xea\\x82\\xcdShift-JIS\\x82\\xc5\\x83R\\x81[\\x83f\\x83B\\x83\\x93\\x83O\\x82\\xb3\\x82\\xea\\x82\\xbd\\x93\\xfa\\x96{\\x8c\\xea\\x82\\xcc\\x83t\\x83@\\x83C\\x83\\x8b\\x82\\xc5\\x82\\xb7\\x81B
'\n unicode_html = shift_jis_html.decode('shift-jis')\n soup = self.soup(unicode_html)\n self.assertEqual(soup.encode('utf-8'), unicode_html.encode('utf-8'))\n self.assertEqual(soup.encode('euc_jp'), unicode_html.encode('euc_jp'))\n\n def test_real_hebrew_document(self):\n hebrew_document = b'Hebrew (ISO 8859-8) in Visual Directionality

Hebrew (ISO 8859-8) in Visual Directionality

\\xed\\xe5\\xec\\xf9'\n soup = self.soup(hebrew_document, from_encoding='iso8859-8')\n self.assertEqual(soup.original_encoding, 'iso8859-8')\n self.assertEqual(soup.encode('utf-8'), hebrew_document.decode('iso8859-8').encode('utf-8'))\n", "method_code": " def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):\n \"\"\"Returns a Unicode representation of this tag and its contents.\n \n :param eventual_encoding: The tag is destined to be\n encoded into this encoding. This method is _not_\n responsible for performing that encoding. This information\n is passed in so that it can be substituted in if the\n document contains a tag that mentions the document's\n encoding.\n \"\"\"\n if not isinstance(formatter, collections.abc.Callable):\n formatter = self._formatter_for_name(formatter)\n attrs = []\n if self.attrs:\n for key, val in sorted(self.attrs.items()):\n if val is None:\n decoded = key\n else:\n if isinstance(val, list) or isinstance(val, tuple):\n val = ' '.join(val)\n elif not isinstance(val, str):\n val = str(val)\n elif isinstance(val, AttributeValueWithCharsetSubstitution) and eventual_encoding is not None:\n val = val.encode(eventual_encoding)\n text = self.format_string(val, formatter)\n decoded = str(key) + '=' + EntitySubstitution.quoted_attribute_value(text)\n attrs.append(decoded)\n close = ''\n closeTag = ''\n prefix = ''\n if self.prefix:\n prefix = self.prefix + ':'\n if self.is_empty_element:\n close = '/'\n else:\n closeTag = '' % (prefix, self.name)\n pretty_print = self._should_pretty_print(indent_level)\n space = ''\n indent_space = ''\n if indent_level is not None:\n indent_space = ' ' * (indent_level - 1)\n if pretty_print:\n space = indent_space\n indent_contents = indent_level + 1\n else:\n indent_contents = None\n contents = self.decode_contents(indent_contents, eventual_encoding, formatter)\n if self.hidden:\n s = contents\n else:\n s = []\n attribute_string = ''\n if attrs:\n attribute_string = ' ' + ' '.join(attrs)\n if indent_level is not None:\n s.append(indent_space)\n s.append('<%s%s%s%s>' % (prefix, self.name, attribute_string, close))\n if pretty_print:\n s.append('\\n')\n s.append(contents)\n if pretty_print and contents and (contents[-1] != '\\n'):\n s.append('\\n')\n if pretty_print and closeTag:\n s.append(space)\n s.append(closeTag)\n if indent_level is not None and closeTag and self.next_sibling:\n s.append('\\n')\n s = ''.join(s)\n return s\n ", "context": "class Tag(PageElement):\n def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None): ...\n def __copy__(self): ...\n def is_empty_element(self): ...\n def string(self): ...\n def string(self, string): ...\n def _all_strings(self, strip=False, types=(NavigableString, CData)): ...\n def stripped_strings(self): ...\n def get_text(self, separator='', strip=False, types=(NavigableString, CData)): ...\n def decompose(self): ...\n def clear(self, decompose=False): ...\n def index(self, element): ...\n def get(self, key, default=None): ...\n def has_attr(self, key): ...\n def __hash__(self): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __contains__(self, x): ...\n def __bool__(self): ...\n def __setitem__(self, key, value): ...\n def __delitem__(self, key): ...\n def __call__(self, *args, **kwargs): ...\n def __getattr__(self, tag): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __repr__(self, encoding='unicode-escape'): ...\n def __unicode__(self): ...\n def __str__(self): ...\n def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, indent_level=None, formatter='minimal', errors='xmlcharrefreplace'): ...\n def _should_pretty_print(self, indent_level): ...\n def prettify(self, encoding=None, formatter='minimal'): ...\n def decode_contents(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def encode_contents(self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'): ...\n def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): ...\n def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): ...\n def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): ...\n def children(self): ...\n def descendants(self): ...\n def select_one(self, selector): ...\n def select(self, selector, _candidate_generator=None, limit=None): ...\n def childGenerator(self): ...\n def recursiveChildGenerator(self): ...\n def has_key(self, key): ...\n\n self.name = name\n self.namespace = namespace\n self.prefix = prefix\n self.attrs = attrs\n self.contents = []\n self.hidden = False\n\n parserClass = _alias('parser_class')\n isSelfClosing = is_empty_element\n strings = property(_all_strings)\n getText = get_text\n text = property(get_text)\n findChild = find\n findAll = find_all\n findChildren = find_all\n _selector_combinators = ['>', '+', '~']\n _select_debug = False\n", "repository": "rugged-board/poky", "test_name": "test_real_shift_jis_document", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001419.py"} {"focal_file": "scripts/pybootchartgui/pybootchartgui/process_tree.py", "focal_class": null, "focal_method": "merge_logger", "tests": "import unittest\n\nclass Test_merge_logger(unittest.TestCase):\n def testMergeLogger(self):\n self.processtree.merge_logger(self.processtree.process_tree, 'bootchartd', None, False)\n process_tree = self.processtree.process_tree\n self.checkAgainstJavaExtract(self.mk_fname('extract.processtree.2.log'), process_tree)\n", "method_code": " def merge_logger(self, process_subtree, logger_proc, monitored_app, app_tree):\n \"\"\"Merges the logger's process subtree. The logger will typically\n spawn lots of sleep and cat processes, thus polluting the\n process tree.\n \n \"\"\"\n num_removed = 0\n for p in process_subtree:\n is_app_tree = app_tree\n if logger_proc == p.cmd and (not app_tree):\n is_app_tree = True\n num_removed += self.merge_logger(p.child_list, logger_proc, monitored_app, is_app_tree)\n continue\n if app_tree and monitored_app != None and (monitored_app == p.cmd):\n is_app_tree = False\n if is_app_tree:\n for child in p.child_list:\n self.merge_processes(p, child)\n num_removed += 1\n p.child_list = []\n else:\n num_removed += self.merge_logger(p.child_list, logger_proc, monitored_app, is_app_tree)\n return num_removed\n ", "context": "class ProcessTree():\n def merge_logger(self, process_subtree, logger_proc, monitored_app, app_tree): ...\n def __init__(self, writer, kernel, psstats, sample_period, monitoredApp, prune, idle, taskstats, accurate_parentage, for_testing=False): ...\n def build(self): ...\n def sort(self, process_subtree): ...\n def num_nodes(self, process_list): ...\n def get_start_time(self, process_subtree): ...\n def get_end_time(self, process_subtree): ...\n def get_max_pid(self, process_subtree): ...\n def update_ppids_for_daemons(self, process_list): ...\n def prune(self, process_subtree, parent): ...\n def merge_exploders(self, process_subtree, processes): ...\n def merge_siblings(self, process_subtree): ...\n def merge_runs(self, process_subtree): ...\n def merge_processes(self, p1, p2): ...\n\n self.writer = writer\n self.process_tree = []\n self.taskstats = taskstats\n self.process_list = sorted(process_list, key=lambda p: p.pid)\n self.sample_period = sample_period\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.idle = idle\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.num_proc = self.num_nodes(self.process_tree)\n\n LOGGER_PROC = 'bootchart-colle'\n EXPLODER_PROCESSES = set(['hwup'])\n", "repository": "rugged-board/poky", "test_name": "testMergeLogger", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001420.py"} {"focal_file": "scripts/pybootchartgui/pybootchartgui/process_tree.py", "focal_class": null, "focal_method": "merge_exploders", "tests": "import unittest\n\nclass Test_merge_exploders(unittest.TestCase):\n def testMergeExploders(self):\n self.processtree.merge_logger(self.processtree.process_tree, 'bootchartd', None, False)\n self.processtree.prune(self.processtree.process_tree, None)\n self.processtree.merge_exploders(self.processtree.process_tree, set(['hwup']))\n process_tree = self.processtree.process_tree\n self.checkAgainstJavaExtract(self.mk_fname('extract.processtree.3c.log'), process_tree)\n", "method_code": " def merge_exploders(self, process_subtree, processes):\n \"\"\"Merges specific process subtrees (used for processes which usually\n spawn huge meaningless process trees).\n \n \"\"\"\n num_removed = 0\n for p in process_subtree:\n if processes in processes and len(p.child_list) > 0:\n subtreemap = self.getProcessMap(p.child_list)\n for child in subtreemap.values():\n self.merge_processes(p, child)\n num_removed += len(subtreemap)\n p.child_list = []\n p.cmd += ' (+)'\n else:\n num_removed += self.merge_exploders(p.child_list, processes)\n return num_removed\n ", "context": "class ProcessTree():\n def merge_exploders(self, process_subtree, processes): ...\n def __init__(self, writer, kernel, psstats, sample_period, monitoredApp, prune, idle, taskstats, accurate_parentage, for_testing=False): ...\n def build(self): ...\n def sort(self, process_subtree): ...\n def num_nodes(self, process_list): ...\n def get_start_time(self, process_subtree): ...\n def get_end_time(self, process_subtree): ...\n def get_max_pid(self, process_subtree): ...\n def update_ppids_for_daemons(self, process_list): ...\n def prune(self, process_subtree, parent): ...\n def merge_logger(self, process_subtree, logger_proc, monitored_app, app_tree): ...\n def merge_siblings(self, process_subtree): ...\n def merge_runs(self, process_subtree): ...\n def merge_processes(self, p1, p2): ...\n\n self.writer = writer\n self.process_tree = []\n self.taskstats = taskstats\n self.process_list = sorted(process_list, key=lambda p: p.pid)\n self.sample_period = sample_period\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.idle = idle\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.num_proc = self.num_nodes(self.process_tree)\n\n LOGGER_PROC = 'bootchart-colle'\n EXPLODER_PROCESSES = set(['hwup'])\n", "repository": "rugged-board/poky", "test_name": "testMergeExploders", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001421.py"} {"focal_file": "scripts/pybootchartgui/pybootchartgui/process_tree.py", "focal_class": null, "focal_method": "merge_siblings", "tests": "import unittest\n\nclass Test_merge_siblings(unittest.TestCase):\n def testMergeSiblings(self):\n self.processtree.merge_logger(self.processtree.process_tree, 'bootchartd', None, False)\n self.processtree.prune(self.processtree.process_tree, None)\n self.processtree.merge_exploders(self.processtree.process_tree, set(['hwup']))\n self.processtree.merge_siblings(self.processtree.process_tree)\n process_tree = self.processtree.process_tree\n self.checkAgainstJavaExtract(self.mk_fname('extract.processtree.3d.log'), process_tree)\n", "method_code": " def merge_siblings(self, process_subtree):\n \"\"\"Merges thread processes. Sibling processes with the same command\n line are merged together.\n \n \"\"\"\n num_removed = 0\n idx = 0\n while idx < len(process_subtree) - 1:\n p = process_subtree[idx]\n nextp = process_subtree[idx + 1]\n if nextp.cmd == p.cmd:\n process_subtree.pop(idx + 1)\n idx -= 1\n num_removed += 1\n p.child_list.extend(nextp.child_list)\n self.merge_processes(p, nextp)\n num_removed += self.merge_siblings(p.child_list)\n idx += 1\n if len(process_subtree) > 0:\n p = process_subtree[-1]\n num_removed += self.merge_siblings(p.child_list)\n return num_removed\n ", "context": "class ProcessTree():\n def merge_siblings(self, process_subtree): ...\n def __init__(self, writer, kernel, psstats, sample_period, monitoredApp, prune, idle, taskstats, accurate_parentage, for_testing=False): ...\n def build(self): ...\n def sort(self, process_subtree): ...\n def num_nodes(self, process_list): ...\n def get_start_time(self, process_subtree): ...\n def get_end_time(self, process_subtree): ...\n def get_max_pid(self, process_subtree): ...\n def update_ppids_for_daemons(self, process_list): ...\n def prune(self, process_subtree, parent): ...\n def merge_logger(self, process_subtree, logger_proc, monitored_app, app_tree): ...\n def merge_exploders(self, process_subtree, processes): ...\n def merge_runs(self, process_subtree): ...\n def merge_processes(self, p1, p2): ...\n\n self.writer = writer\n self.process_tree = []\n self.taskstats = taskstats\n self.process_list = sorted(process_list, key=lambda p: p.pid)\n self.sample_period = sample_period\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.idle = idle\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.num_proc = self.num_nodes(self.process_tree)\n\n LOGGER_PROC = 'bootchart-colle'\n EXPLODER_PROCESSES = set(['hwup'])\n", "repository": "rugged-board/poky", "test_name": "testMergeSiblings", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001422.py"} {"focal_file": "pyzwaver/security.py", "focal_class": null, "focal_method": "str_inc", "tests": "import unittest\n\nclass Test_str_inc(unittest.TestCase):\n def test_str_inc(self):\n b = b'\\x00' * 2\n for i in range(256 ** len(b) + 1):\n self.assertEqual(i % 256 ** len(b), int.from_bytes(b, 'big'))\n b = security.str_inc(b)\n", "method_code": "def str_inc(b):\n lst = [int(x) for x in b]\n for i in reversed(range(0, len(b))):\n lst[i] = (lst[i] + 1) % 256\n if lst[i] != 0:\n break\n return bytes(lst)", "context": "def str_inc(b): ...\ndef CKDF_GenerateSharedSecret(other_public_key: bytes): ...\ndef CMAC(key: bytes, data: bytes): ...\ndef CKDF_TempExtract(shared_secret: bytes, this_public_key: bytes, other_public_key: bytes): ...\ndef Constant15(a, b): ...\ndef CKDF_TempExpand(prk: bytes): ...\ndef CKFD_SharedKey(other_public_key: bytes): ...\ndef CKDF_MeiExtract(sender_ei: bytes, receiver_ei: bytes): ...\ndef CKDF_MeiExpand(nonce_prk: bytes): ...\ndef str_xor(a, b): ...\ndef str_pad(b, length, pad_byte=b'\\x00'): ...\ndef str_inc(b): ...\ndef str_zero(length): ...\ndef _CTR_DRBG_AES128_update(data, key, v): ...\ndef Encrypt(key_ccm, nonce, data, aad): ...\ndef Decrypt(key_ccm, nonce, ct, aad): ...\n", "repository": "robertmuth/PyZwaver", "test_name": "test_str_inc", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001423.py"} {"focal_file": "pyzwaver/security.py", "focal_class": "pyzwaver.security.CTR_DRBG_AES128", "focal_method": "generate", "tests": "import unittest\n\nclass Test_pyzwaver_security_CTR_DRBG_AES128_generate(unittest.TestCase):\n def test_generation_simple(self):\n EntropyInput = make_bytes('48e8271c4b554d9da3f88c820d078f6a3f66acf007cc98840e03e26c62527f91')\n ReturnedBits = make_bytes('b9a956a6e3d10310e57e287c284c6867ed9e8084a62b25c49218fa3aede7c6eaec1622696640f6b4ad5379c6fb8f9b5d7202ad89105d03173487e29da9739390')\n ctr_drbg = security.CTR_DRBG_AES128(EntropyInput)\n out = ctr_drbg.generate(64)\n out = ctr_drbg.generate(64)\n self.assertEqual(out, ReturnedBits)\n", "method_code": " def generate(self, count, data=None):\n out = b''\n v = self._v\n key = self._key\n if data is not None:\n key, v = _CTR_DRBG_AES128_update(data, key, v)\n cipher = Cipher(algorithms.AES(key), modes.CBC(str_zero(16)), backend=default_backend())\n while len(out) < count:\n encryptor = cipher.encryptor()\n v = str_inc(v)\n out += encryptor.update(v) + encryptor.finalize()\n if data is None:\n data = str_zero(32)\n self._key, self._v = _CTR_DRBG_AES128_update(data, key, v)\n return out[:count]\n ", "context": "class CTR_DRBG_AES128(object):\n def generate(self, count, data=None): ...\n def __init__(self, entropy: bytes, personalization_string: bytes=str_zero(32)): ...\n\n self._key, self._v = _CTR_DRBG_AES128_update(str_xor(entropy, personalization_string), str_zero(16), str_zero(16))\n", "repository": "robertmuth/PyZwaver", "test_name": "test_generation_simple", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001424.py"} {"focal_file": "sketchduino/__init__.py", "focal_class": null, "focal_method": "create_directory_tree", "tests": "import unittest\n\nclass Test_create_directory_tree(unittest.TestCase):\n def test_create_directory_tree(self):\n nodes = [os.path.join('root', 'node1'), os.path.join('root', 'node2'), os.path.join('root', 'node3')]\n for node in nodes:\n create_directory_tree(node)\n for node in nodes:\n self.assertTrue(os.path.exists(node))\n", "method_code": "def create_directory_tree(directory):\n if os.path.isdir(directory) is False:\n parent = os.path.dirname(directory)\n if parent not in ('/', '.', '..', ''):\n create_directory_tree(parent)\n os.mkdir(directory)\n return '+'\n else:\n return 'S'", "context": "def create_directory_tree(directory): ...\ndef sdk_refresh(params): ...\ndef search(patterns, directory, notfound=None): ...\ndef search_for_pattern(pattern, directories, notfound): ...\ndef find_avr_toolchain(params): ...\ndef expand_project_path(params): ...\ndef not_implemented(**kargs): ...\ndef command_not_found(**kargs): ...\ndef create_directory_tree(directory): ...\ndef scan_for_sources(path, basepath=None): ...\ndef src_to_obj(src): ...\ndef src_to_asm(src): ...\ndef sources_to_objects(sources, prefix=''): ...\ndef sources_to_asm(sources, prefix=''): ...\ndef asm_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef obj_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef core_ruler(sources, prefix, obj_dir, library): ...\ndef gen_pgr_extra(serial=None, baudrate=None, **params): ...\ndef detect_libraries(lib_dir, **kwargs): ...\ndef linker_ruler_for(objs, out=''): ...\ndef lib_ruler_for(name, conf): ...\ndef create_or_update_makefile(sdk_source_dir, **params): ...\ndef create_main(**params): ...\ndef create_or_update_command(command=None, **kargs): ...\ndef load_sketch_conf(project_home): ...\ndef apply_if(a, b): ...\ndef rebuild_command(project_home, **params): ...\ndef build_command(project_home, **params): ...\ndef clean_command(project_home, **params): ...\ndef show_command(**params): ...\ndef variant_list(sdk_variant_dir, variant, **params): ...\ndef version_cmd(*args, **kwargs): ...\ndef main(): ...\n", "repository": "rodrigopmatias/sketchduino", "test_name": "test_create_directory_tree", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001425.py"} {"focal_file": "sketchduino/__init__.py", "focal_class": null, "focal_method": "src_to_obj", "tests": "import unittest\n\nclass Test_src_to_obj(unittest.TestCase):\n def test_src_to_obj(self):\n assert src_to_obj('main.c') == 'main.o'\n assert src_to_obj('main.cc') == 'main.o'\n assert src_to_obj('main.cpp') == 'main.o'\n assert src_to_obj('main.cxx') == 'main.o'\n", "method_code": "def src_to_obj(src):\n return re.sub('\\\\/', '-', re.sub('\\\\.(c|cc|cpp|hpp|cxx)$', '.o', src))", "context": "def src_to_obj(src): ...\ndef sdk_refresh(params): ...\ndef search(patterns, directory, notfound=None): ...\ndef search_for_pattern(pattern, directories, notfound): ...\ndef find_avr_toolchain(params): ...\ndef expand_project_path(params): ...\ndef not_implemented(**kargs): ...\ndef command_not_found(**kargs): ...\ndef create_directory_tree(directory): ...\ndef scan_for_sources(path, basepath=None): ...\ndef src_to_obj(src): ...\ndef src_to_asm(src): ...\ndef sources_to_objects(sources, prefix=''): ...\ndef sources_to_asm(sources, prefix=''): ...\ndef asm_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef obj_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef core_ruler(sources, prefix, obj_dir, library): ...\ndef gen_pgr_extra(serial=None, baudrate=None, **params): ...\ndef detect_libraries(lib_dir, **kwargs): ...\ndef linker_ruler_for(objs, out=''): ...\ndef lib_ruler_for(name, conf): ...\ndef create_or_update_makefile(sdk_source_dir, **params): ...\ndef create_main(**params): ...\ndef create_or_update_command(command=None, **kargs): ...\ndef load_sketch_conf(project_home): ...\ndef apply_if(a, b): ...\ndef rebuild_command(project_home, **params): ...\ndef build_command(project_home, **params): ...\ndef clean_command(project_home, **params): ...\ndef show_command(**params): ...\ndef variant_list(sdk_variant_dir, variant, **params): ...\ndef version_cmd(*args, **kwargs): ...\ndef main(): ...\n", "repository": "rodrigopmatias/sketchduino", "test_name": "test_src_to_obj", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001426.py"} {"focal_file": "sketchduino/__init__.py", "focal_class": null, "focal_method": "src_to_asm", "tests": "import unittest\n\nclass Test_src_to_asm(unittest.TestCase):\n def test_src_to_asm(self):\n assert src_to_asm('main.c') == 'main.s'\n assert src_to_asm('main.cc') == 'main.s'\n assert src_to_asm('main.cpp') == 'main.s'\n assert src_to_asm('main.cxx') == 'main.s'\n", "method_code": "def src_to_asm(src):\n return re.sub('\\\\/', '-', re.sub('\\\\.(c|cc|cpp|hpp|cxx)$', '.s', src))", "context": "def src_to_asm(src): ...\ndef sdk_refresh(params): ...\ndef search(patterns, directory, notfound=None): ...\ndef search_for_pattern(pattern, directories, notfound): ...\ndef find_avr_toolchain(params): ...\ndef expand_project_path(params): ...\ndef not_implemented(**kargs): ...\ndef command_not_found(**kargs): ...\ndef create_directory_tree(directory): ...\ndef scan_for_sources(path, basepath=None): ...\ndef src_to_obj(src): ...\ndef src_to_asm(src): ...\ndef sources_to_objects(sources, prefix=''): ...\ndef sources_to_asm(sources, prefix=''): ...\ndef asm_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef obj_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef core_ruler(sources, prefix, obj_dir, library): ...\ndef gen_pgr_extra(serial=None, baudrate=None, **params): ...\ndef detect_libraries(lib_dir, **kwargs): ...\ndef linker_ruler_for(objs, out=''): ...\ndef lib_ruler_for(name, conf): ...\ndef create_or_update_makefile(sdk_source_dir, **params): ...\ndef create_main(**params): ...\ndef create_or_update_command(command=None, **kargs): ...\ndef load_sketch_conf(project_home): ...\ndef apply_if(a, b): ...\ndef rebuild_command(project_home, **params): ...\ndef build_command(project_home, **params): ...\ndef clean_command(project_home, **params): ...\ndef show_command(**params): ...\ndef variant_list(sdk_variant_dir, variant, **params): ...\ndef version_cmd(*args, **kwargs): ...\ndef main(): ...\n", "repository": "rodrigopmatias/sketchduino", "test_name": "test_src_to_asm", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001427.py"} {"focal_file": "sketchduino/__init__.py", "focal_class": null, "focal_method": "find_avr_toolchain", "tests": "import unittest\n\nclass Test_find_avr_toolchain(unittest.TestCase):\n def test_find_avr_toolchain(self):\n rst = find_avr_toolchain(self.conf)\n self.assertEqual(rst.get('cc', None), os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'bin', 'avr-gcc']))\n self.assertEqual(rst.get('cxx', None), os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'bin', 'avr-g++']))\n self.assertEqual(rst.get('ld', None), os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'bin', 'avr-ld']))\n self.assertEqual(rst.get('objcopy', None), os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'bin', 'avr-objcopy']))\n self.assertEqual(rst.get('ar', None), os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'bin', 'avr-ar']))\n self.assertEqual(rst.get('avr_include', None), os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'include']))\n self.assertEqual(rst.get('avr_lib', None), os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'lib']))\n self.assertTrue(rst.get('avrdude', None) == os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'avrdude64']) or rst.get('avrdude', None) == os.path.sep.join([self.conf.get('sdk_home'), 'hardware', 'tools', 'avr', 'avrdude']))\n", "method_code": "def find_avr_toolchain(params):\n if params.get('avr_home') is not None or params.get('sdk_home') is not None:\n if params.get('avr_home', None) is None:\n params.update(avr_home=os.path.sep.join([params.get('sdk_home'), 'hardware', 'tools', 'avr']))\n avr_home = params.get('avr_home')\n avr_bindir = os.path.join(avr_home, 'bin')\n avr_includedir = os.path.join(avr_home, 'include')\n avr_libdir = os.path.join(avr_home, 'lib')\n params.update(cxx=search(('^avr\\\\-g\\\\+\\\\+$', '^g\\\\+\\\\+$'), [avr_bindir, '/usr/bin'], 'not found'), cc=search(('^avr\\\\-gcc$', '^gcc$'), [avr_bindir, '/usr/bin'], 'not found'), ld=search(('^avr\\\\-ld$', '^ld$'), [avr_bindir, '/usr/bin'], 'not found'), objcopy=search(('^avr\\\\-objcopy$', '^objcopy$'), [avr_bindir, '/usr/bin'], 'not found'), size=search(('^avr\\\\-size$', '^size$'), [avr_bindir, '/usr/bin'], 'not found'), avr_include=avr_includedir, avr_lib=avr_libdir, ar=search(('^avr\\\\-ar$', '^ar$'), [avr_bindir, '/usr/bin'], 'not found'), asm=search(('^avr\\\\-as$', '^as$'), [avr_bindir, '/usr/bin'], 'not found'), avrdude=search('^avrdude(|64)$', [avr_home, '/usr/bin'], 'not found'))\n return params", "context": "def find_avr_toolchain(params): ...\ndef sdk_refresh(params): ...\ndef search(patterns, directory, notfound=None): ...\ndef search_for_pattern(pattern, directories, notfound): ...\ndef find_avr_toolchain(params): ...\ndef expand_project_path(params): ...\ndef not_implemented(**kargs): ...\ndef command_not_found(**kargs): ...\ndef create_directory_tree(directory): ...\ndef scan_for_sources(path, basepath=None): ...\ndef src_to_obj(src): ...\ndef src_to_asm(src): ...\ndef sources_to_objects(sources, prefix=''): ...\ndef sources_to_asm(sources, prefix=''): ...\ndef asm_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef obj_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef core_ruler(sources, prefix, obj_dir, library): ...\ndef gen_pgr_extra(serial=None, baudrate=None, **params): ...\ndef detect_libraries(lib_dir, **kwargs): ...\ndef linker_ruler_for(objs, out=''): ...\ndef lib_ruler_for(name, conf): ...\ndef create_or_update_makefile(sdk_source_dir, **params): ...\ndef create_main(**params): ...\ndef create_or_update_command(command=None, **kargs): ...\ndef load_sketch_conf(project_home): ...\ndef apply_if(a, b): ...\ndef rebuild_command(project_home, **params): ...\ndef build_command(project_home, **params): ...\ndef clean_command(project_home, **params): ...\ndef show_command(**params): ...\ndef variant_list(sdk_variant_dir, variant, **params): ...\ndef version_cmd(*args, **kwargs): ...\ndef main(): ...\n", "repository": "rodrigopmatias/sketchduino", "test_name": "test_find_avr_toolchain", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001428.py"} {"focal_file": "sketchduino/__init__.py", "focal_class": null, "focal_method": "search", "tests": "import unittest\n\nclass Test_search(unittest.TestCase):\n def test_search(self):\n found_re = re.compile('^(avr\\\\-g\\\\+\\\\+|g\\\\+\\\\+)$')\n notfound_re = re.compile('^notfound$')\n conf = find_avr_toolchain(self.conf)\n avr_bindir = os.path.join(conf.get('avr_home'), 'bin')\n rst = (search(found_re, avr_bindir), search(notfound_re, avr_bindir))\n self.assertEqual(rst[0], os.path.join(avr_bindir, 'avr-g++'))\n self.assertEqual(rst[1], None)\n", "method_code": "def search(patterns, directory, notfound=None):\n directories = tuple([directory]) if not isinstance(directory, (tuple, list)) else directory\n patterns = tuple([patterns]) if not isinstance(patterns, (tuple, list)) else patterns\n rst = notfound\n for pattern in patterns:\n compiled = re.compile(pattern)\n rst = search_for_pattern(compiled, directories, notfound)\n if rst != notfound:\n break\n return rst", "context": "def search(patterns, directory, notfound=None): ...\ndef sdk_refresh(params): ...\ndef search(patterns, directory, notfound=None): ...\ndef search_for_pattern(pattern, directories, notfound): ...\ndef find_avr_toolchain(params): ...\ndef expand_project_path(params): ...\ndef not_implemented(**kargs): ...\ndef command_not_found(**kargs): ...\ndef create_directory_tree(directory): ...\ndef scan_for_sources(path, basepath=None): ...\ndef src_to_obj(src): ...\ndef src_to_asm(src): ...\ndef sources_to_objects(sources, prefix=''): ...\ndef sources_to_asm(sources, prefix=''): ...\ndef asm_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef obj_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef core_ruler(sources, prefix, obj_dir, library): ...\ndef gen_pgr_extra(serial=None, baudrate=None, **params): ...\ndef detect_libraries(lib_dir, **kwargs): ...\ndef linker_ruler_for(objs, out=''): ...\ndef lib_ruler_for(name, conf): ...\ndef create_or_update_makefile(sdk_source_dir, **params): ...\ndef create_main(**params): ...\ndef create_or_update_command(command=None, **kargs): ...\ndef load_sketch_conf(project_home): ...\ndef apply_if(a, b): ...\ndef rebuild_command(project_home, **params): ...\ndef build_command(project_home, **params): ...\ndef clean_command(project_home, **params): ...\ndef show_command(**params): ...\ndef variant_list(sdk_variant_dir, variant, **params): ...\ndef version_cmd(*args, **kwargs): ...\ndef main(): ...\n", "repository": "rodrigopmatias/sketchduino", "test_name": "test_search", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001429.py"} {"focal_file": "sketchduino/__init__.py", "focal_class": null, "focal_method": "sdk_refresh", "tests": "import unittest\n\nclass Test_sdk_refresh(unittest.TestCase):\n def test_sdk_refresh(self):\n rst = sdk_refresh(self.conf)\n sdk_home = self.conf.get('sdk_home')\n self.assertEqual(rst.get('sdk_variant_dir', None), os.path.sep.join([sdk_home, 'hardware', 'arduino', 'variants']))\n self.assertEqual(rst.get('sdk_source_dir', None), os.path.sep.join([sdk_home, 'hardware', 'arduino', 'cores', 'arduino']))\n self.assertEqual(rst.get('sdk_libary_dir', None), os.path.sep.join([sdk_home, 'libraries']))\n", "method_code": "def sdk_refresh(params):\n sdk_home = params.get('sdk_home', None)\n params.update(sdk_variant_dir=os.path.sep.join([sdk_home, 'hardware', 'arduino', 'variants']) if sdk_home else '', sdk_source_dir=os.path.sep.join([sdk_home, 'hardware', 'arduino', 'cores', 'arduino']) if sdk_home else '', sdk_libary_dir=os.path.sep.join([sdk_home, 'libraries']) if sdk_home else '')\n if sdk_home is not None:\n sdk_version = '000'\n with open(os.path.sep.join([sdk_home, 'lib', 'version.txt'])) as fd:\n sdk_version = fd.read().replace('.', '')\n params.update(sdk_version=sdk_version)\n return params", "context": "def sdk_refresh(params): ...\ndef sdk_refresh(params): ...\ndef search(patterns, directory, notfound=None): ...\ndef search_for_pattern(pattern, directories, notfound): ...\ndef find_avr_toolchain(params): ...\ndef expand_project_path(params): ...\ndef not_implemented(**kargs): ...\ndef command_not_found(**kargs): ...\ndef create_directory_tree(directory): ...\ndef scan_for_sources(path, basepath=None): ...\ndef src_to_obj(src): ...\ndef src_to_asm(src): ...\ndef sources_to_objects(sources, prefix=''): ...\ndef sources_to_asm(sources, prefix=''): ...\ndef asm_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef obj_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef core_ruler(sources, prefix, obj_dir, library): ...\ndef gen_pgr_extra(serial=None, baudrate=None, **params): ...\ndef detect_libraries(lib_dir, **kwargs): ...\ndef linker_ruler_for(objs, out=''): ...\ndef lib_ruler_for(name, conf): ...\ndef create_or_update_makefile(sdk_source_dir, **params): ...\ndef create_main(**params): ...\ndef create_or_update_command(command=None, **kargs): ...\ndef load_sketch_conf(project_home): ...\ndef apply_if(a, b): ...\ndef rebuild_command(project_home, **params): ...\ndef build_command(project_home, **params): ...\ndef clean_command(project_home, **params): ...\ndef show_command(**params): ...\ndef variant_list(sdk_variant_dir, variant, **params): ...\ndef version_cmd(*args, **kwargs): ...\ndef main(): ...\n", "repository": "rodrigopmatias/sketchduino", "test_name": "test_sdk_refresh", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001430.py"} {"focal_file": "sketchduino/__init__.py", "focal_class": null, "focal_method": "expand_project_path", "tests": "import unittest\n\nclass Test_expand_project_path(unittest.TestCase):\n def test_expand_project(self):\n rst = expand_project_path(self.conf)\n self.assertEqual(rst.get('source_dir', None), os.path.join(self.conf.get('project_home'), 'src'))\n self.assertEqual(rst.get('lib_dir', None), os.path.join(self.conf.get('project_home'), 'lib'))\n self.assertEqual(rst.get('bin_dir', None), os.path.join(self.conf.get('project_home'), 'binary'))\n self.assertEqual(rst.get('include_dir', None), os.path.join(self.conf.get('project_home'), 'include'))\n", "method_code": "def expand_project_path(params):\n params.update(project_home=os.path.abspath(params.get('project_home')))\n project_home = params.get('project_home')\n params.update(source_dir=os.path.join(project_home, 'src'), lib_dir=os.path.join(project_home, 'lib'), bin_dir=os.path.join(project_home, 'binary'), include_dir=os.path.join(project_home, 'include'))\n return params", "context": "def expand_project_path(params): ...\ndef sdk_refresh(params): ...\ndef search(patterns, directory, notfound=None): ...\ndef search_for_pattern(pattern, directories, notfound): ...\ndef find_avr_toolchain(params): ...\ndef expand_project_path(params): ...\ndef not_implemented(**kargs): ...\ndef command_not_found(**kargs): ...\ndef create_directory_tree(directory): ...\ndef scan_for_sources(path, basepath=None): ...\ndef src_to_obj(src): ...\ndef src_to_asm(src): ...\ndef sources_to_objects(sources, prefix=''): ...\ndef sources_to_asm(sources, prefix=''): ...\ndef asm_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef obj_ruler_for(sources, source_dir='', obj_dir='', prefix=''): ...\ndef core_ruler(sources, prefix, obj_dir, library): ...\ndef gen_pgr_extra(serial=None, baudrate=None, **params): ...\ndef detect_libraries(lib_dir, **kwargs): ...\ndef linker_ruler_for(objs, out=''): ...\ndef lib_ruler_for(name, conf): ...\ndef create_or_update_makefile(sdk_source_dir, **params): ...\ndef create_main(**params): ...\ndef create_or_update_command(command=None, **kargs): ...\ndef load_sketch_conf(project_home): ...\ndef apply_if(a, b): ...\ndef rebuild_command(project_home, **params): ...\ndef build_command(project_home, **params): ...\ndef clean_command(project_home, **params): ...\ndef show_command(**params): ...\ndef variant_list(sdk_variant_dir, variant, **params): ...\ndef version_cmd(*args, **kwargs): ...\ndef main(): ...\n", "repository": "rodrigopmatias/sketchduino", "test_name": "test_expand_project", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001431.py"} {"focal_file": "Python Crash Course/Chapter 11 Testing your code/name_function.py", "focal_class": null, "focal_method": "get_formatted_name", "tests": "import unittest\n\nclass Test_get_formatted_name(unittest.TestCase):\n def test_first_last_name(self):\n \"\"\" Do names like Janis Joplin work \"\"\"\n formatted_name = get_formatted_name('Janis', 'Joplin')\n self.assertEqual(formatted_name, 'Janis Joplin')\n\n def test_first_last_middle_name(self):\n formatted_name = get_formatted_name('wolfgang', 'wimmer', 'bob')\n self.assertEqual(formatted_name, 'Wolfgang Bob Wimmer')\n", "method_code": "def get_formatted_name(first, last, middle=''):\n \"\"\" Generate a neatly formatted full name\"\"\"\n if middle:\n full_name = first + ' ' + middle + ' ' + last\n else:\n full_name = first + ' ' + last\n return full_name.title()", "context": "def get_formatted_name(first, last, middle=''): ...\ndef get_formatted_name(first, last, middle=''): ...\n", "repository": "ljbradbury/python3", "test_name": "test_first_last_name", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001432.py"} {"focal_file": "Python Crash Course/Chapter 11 Testing your code/survey.py", "focal_class": null, "focal_method": "store_response", "tests": "import unittest\n\nclass Test_store_response(unittest.TestCase):\n def test_store_single_response(self):\n \"\"\" Test that a single response is stored correctly \"\"\"\n question = 'What language did you first learn to speak?'\n self.my_survey.store_response(self.responses[0])\n self.assertIn(self.responses[0], self.my_survey.responses)\n\n def test_store_three_responses(self):\n \"\"\" Test that three responses are stored correctly \"\"\"\n for response in self.responses:\n self.my_survey.store_response(response)\n for response in self.responses:\n self.assertIn(response, self.my_survey.responses)\n", "method_code": " def store_response(self, new_response):\n self.responses.append(new_response)\n ' Store a single response to the survey '\n ", "context": "class AnonymousSurvey():\n def store_response(self, new_response): ...\n def __init__(self, question): ...\n def show_question(self): ...\n def show_results(self): ...\n\n self.question = question\n self.responses = []\n", "repository": "ljbradbury/python3", "test_name": "test_store_single_response", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001433.py"} {"focal_file": "bravo/config.py", "focal_class": null, "focal_method": "getlist", "tests": "import unittest\n\nclass Test_getlist(unittest.TestCase):\n def test_getlist(self):\n self.bcp.set('unittest', 'l', 'a,b,c,d')\n self.assertEqual(self.bcp.getlist('unittest', 'l'), ['a', 'b', 'c', 'd'])\n", "method_code": " def getlist(self, section, option, separator=','):\n \"\"\"\n Coerce an option to a list, and retrieve it.\n \"\"\"\n s = self.get(section, option).strip()\n if s:\n return [i.strip() for i in s.split(separator)]\n else:\n return []\n ", "context": "class BravoConfigParser(SafeConfigParser):\n def getlist(self, section, option, separator=','): ...\n def getdefault(self, section, option, default): ...\n def getbooleandefault(self, section, option, default): ...\n def getintdefault(self, section, option, default): ...\n def getlistdefault(self, section, option, default): ...\n", "repository": "bravoserver/bravo", "test_name": "test_getlist", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001434.py"} {"focal_file": "bravo/config.py", "focal_class": null, "focal_method": "getdefault", "tests": "import unittest\n\nclass Test_getdefault(unittest.TestCase):\n def test_getdefault(self):\n self.assertEqual(self.bcp.getdefault('unittest', 'fake', ''), '')\n", "method_code": " def getdefault(self, section, option, default):\n \"\"\"\n Retrieve an option, or a default value.\n \"\"\"\n try:\n return self.get(section, option)\n except (NoSectionError, NoOptionError):\n return default\n ", "context": "class BravoConfigParser(SafeConfigParser):\n def getdefault(self, section, option, default): ...\n def getlist(self, section, option, separator=','): ...\n def getbooleandefault(self, section, option, default): ...\n def getintdefault(self, section, option, default): ...\n def getlistdefault(self, section, option, default): ...\n", "repository": "bravoserver/bravo", "test_name": "test_getdefault", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001435.py"} {"focal_file": "bravo/config.py", "focal_class": null, "focal_method": "getbooleandefault", "tests": "import unittest\n\nclass Test_getbooleandefault(unittest.TestCase):\n def test_getbooleandefault(self):\n self.assertEqual(self.bcp.getbooleandefault('unittest', 'fake', True), True)\n", "method_code": " def getbooleandefault(self, section, option, default):\n \"\"\"\n Retrieve an option, or a default value.\n \"\"\"\n try:\n return self.getboolean(section, option)\n except (NoSectionError, NoOptionError):\n return default\n ", "context": "class BravoConfigParser(SafeConfigParser):\n def getbooleandefault(self, section, option, default): ...\n def getlist(self, section, option, separator=','): ...\n def getdefault(self, section, option, default): ...\n def getintdefault(self, section, option, default): ...\n def getlistdefault(self, section, option, default): ...\n", "repository": "bravoserver/bravo", "test_name": "test_getbooleandefault", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001436.py"} {"focal_file": "bravo/config.py", "focal_class": null, "focal_method": "getintdefault", "tests": "import unittest\n\nclass Test_getintdefault(unittest.TestCase):\n def test_getintdefault(self):\n self.assertEqual(self.bcp.getintdefault('unittest', 'fake', 42), 42)\n", "method_code": " def getintdefault(self, section, option, default):\n \"\"\"\n Retrieve an option, or a default value.\n \"\"\"\n try:\n return self.getint(section, option)\n except (NoSectionError, NoOptionError):\n return default\n ", "context": "class BravoConfigParser(SafeConfigParser):\n def getintdefault(self, section, option, default): ...\n def getlist(self, section, option, separator=','): ...\n def getdefault(self, section, option, default): ...\n def getbooleandefault(self, section, option, default): ...\n def getlistdefault(self, section, option, default): ...\n", "repository": "bravoserver/bravo", "test_name": "test_getintdefault", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001437.py"} {"focal_file": "bravo/config.py", "focal_class": null, "focal_method": "getlistdefault", "tests": "import unittest\n\nclass Test_getlistdefault(unittest.TestCase):\n def test_getlistdefault(self):\n self.assertEqual(self.bcp.getlistdefault('unittest', 'fake', []), [])\n", "method_code": " def getlistdefault(self, section, option, default):\n \"\"\"\n Retrieve an option, or a default value.\n \"\"\"\n try:\n return self.getlist(section, option)\n except (NoSectionError, NoOptionError):\n return default\n ", "context": "class BravoConfigParser(SafeConfigParser):\n def getlistdefault(self, section, option, default): ...\n def getlist(self, section, option, separator=','): ...\n def getdefault(self, section, option, default): ...\n def getbooleandefault(self, section, option, default): ...\n def getintdefault(self, section, option, default): ...\n", "repository": "bravoserver/bravo", "test_name": "test_getlistdefault", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001438.py"} {"focal_file": "bravo/entity.py", "focal_class": null, "focal_method": "save_to_packet", "tests": "import unittest\n\nclass Test_save_to_packet(unittest.TestCase):\n def test_save_to_packet(self):\n self.m.save_to_packet()\n", "method_code": " def save_to_packet(self):\n \"\"\"\n Create a \"player\" packet representing this entity.\n \"\"\"\n yaw, pitch = self.location.ori.to_fracs()\n x, y, z = self.location.pos\n item = self.inventory.holdables[self.equipped]\n if item is None:\n item = 0\n else:\n item = item[0]\n packet = make_packet('player', eid=self.eid, username=self.username, x=x, y=y, z=z, yaw=yaw, pitch=pitch, item=item, metadata={0: ('byte', 0), 1: ('short', 300), 8: ('int', 0)})\n return packet\n ", "context": "class Player(Entity):\n def save_to_packet(self): ...\n def __init__(self, username='', **kwargs): ...\n def __repr__(self): ...\n def save_equipment_to_packet(self): ...\n\n self.username = username\n self.inventory = Inventory()\n self.equipped = 0\n\n name = 'Player'\n __str__ = __repr__\n", "repository": "bravoserver/bravo", "test_name": "test_save_to_packet", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001439.py"} {"focal_file": "bravo/entity.py", "focal_class": null, "focal_method": "save_location_to_packet", "tests": "import unittest\n\nclass Test_save_location_to_packet(unittest.TestCase):\n def test_save_location_to_packet(self):\n self.m.save_location_to_packet()\n", "method_code": " def save_location_to_packet(self):\n x, y, z = self.location.pos\n yaw, pitch = self.location.ori.to_fracs()\n return make_packet('teleport', eid=self.eid, x=x, y=y, z=z, yaw=yaw, pitch=pitch)\n ", "context": "class Mob(Entity):\n def save_location_to_packet(self): ...\n def __init__(self, **kwargs): ...\n def update_metadata(self): ...\n def run(self): ...\n def save_to_packet(self): ...\n def update(self): ...\n\n self.loop = None\n self.manager = None\n\n name = 'Mob'\n metadata = {0: ('byte', 0)}\n", "repository": "bravoserver/bravo", "test_name": "test_save_location_to_packet", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001440.py"} {"focal_file": "bravo/utilities/bits.py", "focal_class": null, "focal_method": "unpack_nibbles", "tests": "import unittest\n\nclass Test_unpack_nibbles(unittest.TestCase):\n def test_unpack_nibbles_single(self):\n self.assertEqual(unpack_nibbles('a'), array('B', [1, 6]))\n\n def test_unpack_nibbles_multiple(self):\n self.assertEqual(unpack_nibbles('nibbles'), array('B', [14, 6, 9, 6, 2, 6, 2, 6, 12, 6, 5, 6, 3, 7]))\n", "method_code": "def unpack_nibbles(l):\n \"\"\"\n Unpack bytes into pairs of nibbles.\n\n Nibbles are half-byte quantities. The nibbles unpacked by this function\n are returned as unsigned numeric values.\n\n >>> unpack_nibbles(\"a\")\n [6, 1]\n >>> unpack_nibbles(\"nibbles\")\n [6, 14, 6, 9, 6, 2, 6, 2, 6, 12, 6, 5, 7, 3]\n\n :param list l: bytes\n\n :returns: list of nibbles\n \"\"\"\n data = array('B')\n for d in l:\n i = ord(d)\n data.append(i & 15)\n data.append(i >> 4)\n return data", "context": "def unpack_nibbles(l): ...\ndef grouper(n, iterable, fillvalue=None): ...\ndef unpack_nibbles(l): ...\ndef pack_nibbles(a): ...\n", "repository": "bravoserver/bravo", "test_name": "test_unpack_nibbles_single", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001441.py"} {"focal_file": "bravo/utilities/bits.py", "focal_class": null, "focal_method": "pack_nibbles", "tests": "import unittest\n\nclass Test_pack_nibbles(unittest.TestCase):\n def test_pack_nibbles_single(self):\n self.assertEqual(pack_nibbles(array('B', [1, 6])), 'a')\n\n def test_pack_nibbles_multiple(self):\n self.assertEqual(pack_nibbles(array('B', [14, 6, 9, 6, 2, 6, 3, 7])), 'nibs')\n\n def test_unpack_nibbles_overflow(self):\n \"\"\"\n No spurious OverflowErrors should occur when packing nibbles.\n\n This test will raise if there's a regression.\n \"\"\"\n self.assertEqual(pack_nibbles(array('B', [255, 255])), 'ÿ')\n", "method_code": "def pack_nibbles(a):\n \"\"\"\n Pack pairs of nibbles into bytes.\n\n Bytes are returned as characters.\n\n :param `array` a: nibbles to pack\n\n :returns: packed nibbles as a string of bytes\n \"\"\"\n packed = array('B', ((y & 15) << 4 | x & 15 for x, y in grouper(2, a)))\n return packed.tostring()", "context": "def pack_nibbles(a): ...\ndef grouper(n, iterable, fillvalue=None): ...\ndef unpack_nibbles(l): ...\ndef pack_nibbles(a): ...\n", "repository": "bravoserver/bravo", "test_name": "test_pack_nibbles_single", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001442.py"} {"focal_file": "bravo/geometry/section.py", "focal_class": null, "focal_method": "set_block", "tests": "import unittest\n\nclass Test_set_block(unittest.TestCase):\n def test_set_block(self):\n \"\"\"\n ``set_block`` correctly alters the internal array.\n \"\"\"\n self.s.set_block((0, 0, 0), 1)\n self.assertEqual(self.s.blocks[0], 1)\n\n def test_set_block_xyz_xzy(self):\n \"\"\"\n ``set_block`` swizzles into the internal array correctly.\n \"\"\"\n self.s.set_block((1, 0, 0), 1)\n self.s.set_block((0, 1, 0), 2)\n self.s.set_block((0, 0, 1), 3)\n self.assertEqual(self.s.blocks[1], 1)\n self.assertEqual(self.s.blocks[256], 2)\n self.assertEqual(self.s.blocks[16], 3)\n", "method_code": " def set_block(self, coords, block):\n self.blocks[si(*coords)] = block\n ", "context": "class Section(object):\n def set_block(self, coords, block): ...\n def __init__(self): ...\n def get_block(self, coords): ...\n def get_metadata(self, coords): ...\n def set_metadata(self, coords, metadata): ...\n def get_skylight(self, coords): ...\n def set_skylight(self, coords, value): ...\n\n self.blocks = array('B', [0] * (16 * 16 * 16))\n self.metadata = array('B', [0] * (16 * 16 * 16))\n self.skylight = array('B', [15] * (16 * 16 * 16))\n", "repository": "bravoserver/bravo", "test_name": "test_set_block", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001443.py"} {"focal_file": "bravo/policy/dig.py", "focal_class": null, "focal_method": "is_effective_against", "tests": "import unittest\n\nclass Test_is_effective_against(unittest.TestCase):\n def test_wooden_pickaxe_is_effective_against_diamond(self):\n self.assertTrue(is_effective_against(blocks['diamond-block'].slot, Slot(items['wooden-pickaxe'].slot, 100, 1)))\n", "method_code": "def is_effective_against(block, slot):\n if not slot or slot.primary not in items:\n return False\n item = items[slot.primary]\n if item.name.endswith('-shovel'):\n return block in (blocks['clay'].slot, blocks['dirt'].slot, blocks['grass'].slot, blocks['gravel'].slot, blocks['sand'].slot, blocks['snow'].slot, blocks['snow-block'].slot)\n elif item.name.endswith('-axe'):\n return block in (blocks['bookshelf'].slot, blocks['log'].slot, blocks['wood'].slot)\n elif item.name.endswith('-pickaxe'):\n return block in (blocks['brimstone'].slot, blocks['coal-ore'].slot, blocks['cobblestone'].slot, blocks['diamond-block'].slot, blocks['diamond-ore'].slot, blocks['double-stone-slab'].slot, blocks['gold'].slot, blocks['gold-ore'].slot, blocks['ice'].slot, blocks['iron'].slot, blocks['iron-ore'].slot, blocks['lapis-lazuli-block'].slot, blocks['lapis-lazuli-ore'].slot, blocks['mossy-cobblestone'].slot, blocks['sandstone'].slot, blocks['single-stone-slab'].slot, blocks['stone'].slot)\n return False", "context": "def is_effective_against(block, slot): ...\ndef effect_multiplier(slot): ...\ndef is_effective_against(block, slot): ...\n", "repository": "bravoserver/bravo", "test_name": "test_wooden_pickaxe_is_effective_against_diamond", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001444.py"} {"focal_file": "bravo/utilities/chat.py", "focal_class": null, "focal_method": "complete", "tests": "import unittest\n\nclass Test_complete(unittest.TestCase):\n def test_complete_single(self):\n i = u'comp'\n o = [u'completion']\n e = u'completion '\n self.assertEqual(complete(i, o), e)\n\n def test_complete_multiple(self):\n i = u'comp'\n o = [u'completion', u'computer']\n e = u'completion \\x00computer '\n self.assertEqual(complete(i, o), e)\n\n def test_complete_none(self):\n i = u'comp'\n o = []\n e = u''\n self.assertEqual(complete(i, o), e)\n", "method_code": "def complete(sentence, possibilities):\n \"\"\"\n Perform completion on a string using a list of possible strings.\n\n Returns a single string containing all possibilities.\n \"\"\"\n words = sentence.split()\n tail = words[-1].lower()\n tails = [s + u' ' for s in possibilities if s.lower().startswith(tail)]\n return u'\\x00'.join(tails)", "context": "def complete(sentence, possibilities): ...\ndef chat_name(s): ...\ndef fancy_console_name(s): ...\ndef sanitize_chat(s): ...\ndef username_alternatives(n): ...\ndef complete(sentence, possibilities): ...\n", "repository": "bravoserver/bravo", "test_name": "test_complete_single", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001445.py"} {"focal_file": "bravo/utilities/coords.py", "focal_class": null, "focal_method": "iterneighbors", "tests": "import unittest\n\nclass Test_iterneighbors(unittest.TestCase):\n def test_no_neighbors(self):\n x, y, z = (0, -2, 0)\n self.assertEqual(list(iterneighbors(x, y, z)), [])\n", "method_code": "def iterneighbors(x, y, z):\n \"\"\"\n Yield an iterable of neighboring block coordinates.\n\n The first item in the iterable is the original coordinates.\n\n Coordinates with invalid Y values are discarded automatically.\n \"\"\"\n for dx, dy, dz in ((0, 0, 0), (0, 0, 1), (0, 0, -1), (0, 1, 0), (0, -1, 0), (1, 0, 0), (-1, 0, 0)):\n if 0 <= y + dy < CHUNK_HEIGHT:\n yield (x + dx, y + dy, z + dz)", "context": "def iterneighbors(x, y, z): ...\ndef polar_round_vector(vector): ...\ndef split_coords(x, z): ...\ndef taxicab2(x1, y1, x2, y2): ...\ndef taxicab3(x1, y1, z1, x2, y2, z2): ...\ndef adjust_coords_for_face(coords, face): ...\ndef iterchunk(): ...\ndef iterneighbors(x, y, z): ...\ndef itercube(x, y, z, r): ...\n", "repository": "bravoserver/bravo", "test_name": "test_no_neighbors", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001446.py"} {"focal_file": "bravo/utilities/coords.py", "focal_class": null, "focal_method": "itercube", "tests": "import unittest\n\nclass Test_itercube(unittest.TestCase):\n def test_no_cube(self):\n x, y, z, r = (0, -2, 0, 1)\n self.assertEqual(list(itercube(x, y, z, r)), [])\n", "method_code": "def itercube(x, y, z, r):\n \"\"\"\n Yield an iterable of coordinates in a cube around a given block.\n\n Coordinates with invalid Y values are discarded automatically.\n \"\"\"\n bx = x - r\n tx = x + r + 1\n by = max(y - r, 0)\n ty = min(y + r + 1, CHUNK_HEIGHT)\n bz = z - r\n tz = z + r + 1\n return product(xrange(bx, tx), xrange(by, ty), xrange(bz, tz))", "context": "def itercube(x, y, z, r): ...\ndef polar_round_vector(vector): ...\ndef split_coords(x, z): ...\ndef taxicab2(x1, y1, x2, y2): ...\ndef taxicab3(x1, y1, z1, x2, y2, z2): ...\ndef adjust_coords_for_face(coords, face): ...\ndef iterchunk(): ...\ndef iterneighbors(x, y, z): ...\ndef itercube(x, y, z, r): ...\n", "repository": "bravoserver/bravo", "test_name": "test_no_cube", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001447.py"} {"focal_file": "bravo/utilities/paths.py", "focal_class": null, "focal_method": "names_for_chunk", "tests": "import unittest\n\nclass Test_names_for_chunk(unittest.TestCase):\n def test_names_for_chunk(self):\n self.assertEqual(names_for_chunk(-13, 44), ('1f', '18', 'c.-d.18.dat'))\n self.assertEqual(names_for_chunk(-259, 266), ('1p', 'a', 'c.-77.7e.dat'))\n", "method_code": "def names_for_chunk(x, z):\n \"\"\"\n Calculate the folder and file names for given chunk coordinates.\n \"\"\"\n first = base36(x & 63)\n second = base36(z & 63)\n third = 'c.%s.%s.dat' % (base36(x), base36(z))\n return (first, second, third)", "context": "def names_for_chunk(x, z): ...\ndef base36(i): ...\ndef names_for_chunk(x, z): ...\ndef name_for_region(x, z): ...\ndef name_for_anvil(x, z): ...\n", "repository": "bravoserver/bravo", "test_name": "test_names_for_chunk", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001448.py"} {"focal_file": "bravo/utilities/paths.py", "focal_class": null, "focal_method": "base36", "tests": "import unittest\n\nclass Test_base36(unittest.TestCase):\n def test_base36(self):\n self.assertEqual(base36(0), '0')\n self.assertEqual(base36(-47), '-1b')\n self.assertEqual(base36(137), '3t')\n self.assertEqual(base36(24567), 'iyf')\n", "method_code": "def base36(i):\n \"\"\"\n Return the string representation of i in base 36, using lowercase letters.\n\n This isn't optimal, but it covers all of the Notchy corner cases.\n \"\"\"\n letters = '0123456789abcdefghijklmnopqrstuvwxyz'\n if i < 0:\n i = -i\n signed = True\n elif i == 0:\n return '0'\n else:\n signed = False\n s = ''\n while i:\n i, digit = divmod(i, 36)\n s = letters[digit] + s\n if signed:\n s = '-' + s\n return s", "context": "def base36(i): ...\ndef base36(i): ...\ndef names_for_chunk(x, z): ...\ndef name_for_region(x, z): ...\ndef name_for_anvil(x, z): ...\n", "repository": "bravoserver/bravo", "test_name": "test_base36", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001449.py"} {"focal_file": "bravo/utilities/paths.py", "focal_class": null, "focal_method": "name_for_region", "tests": "import unittest\n\nclass Test_name_for_region(unittest.TestCase):\n def test_name_for_region(self):\n \"\"\"\n From RegionFile.java's comments.\n \"\"\"\n self.assertEqual(name_for_region(30, -3), 'r.0.-1.mcr')\n self.assertEqual(name_for_region(70, -30), 'r.2.-1.mcr')\n", "method_code": "def name_for_region(x, z):\n \"\"\"\n Figure out the name for a region file, given chunk coordinates.\n \"\"\"\n return 'r.%s.%s.mcr' % (x // 32, z // 32)", "context": "def name_for_region(x, z): ...\ndef base36(i): ...\ndef names_for_chunk(x, z): ...\ndef name_for_region(x, z): ...\ndef name_for_anvil(x, z): ...\n", "repository": "bravoserver/bravo", "test_name": "test_name_for_region", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001450.py"} {"focal_file": "bravo/utilities/paths.py", "focal_class": null, "focal_method": "name_for_anvil", "tests": "import unittest\n\nclass Test_name_for_anvil(unittest.TestCase):\n def test_name_for_anvil(self):\n \"\"\"\n Equivalent tests for the Anvil version.\n \"\"\"\n self.assertEqual(name_for_anvil(30, -3), 'r.0.-1.mca')\n self.assertEqual(name_for_anvil(70, -30), 'r.2.-1.mca')\n", "method_code": "def name_for_anvil(x, z):\n \"\"\"\n Figure out the name for an Anvil region file, given chunk coordinates.\n \"\"\"\n return 'r.%s.%s.mca' % (x // 32, z // 32)", "context": "def name_for_anvil(x, z): ...\ndef base36(i): ...\ndef names_for_chunk(x, z): ...\ndef name_for_region(x, z): ...\ndef name_for_anvil(x, z): ...\n", "repository": "bravoserver/bravo", "test_name": "test_name_for_anvil", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001451.py"} {"focal_file": "bravo/utilities/redstone.py", "focal_class": null, "focal_method": "truthify_block", "tests": "import unittest\n\nclass Test_truthify_block(unittest.TestCase):\n def test_truthify_lever(self):\n \"\"\"\n Ditto for truthification.\n \"\"\"\n self.assertEqual(truthify_block(True, blocks['lever'].slot, 3), (blocks['lever'].slot, 11))\n", "method_code": "def truthify_block(truth, block, metadata):\n \"\"\"\n Alter a block based on whether it should be true or false (on or off).\n\n This function returns a tuple of the block and metadata, possibly\n partially or fully unaltered.\n \"\"\"\n if block in (blocks['redstone-torch'].slot, blocks['redstone-torch-off'].slot):\n if truth:\n return (blocks['redstone-torch'].slot, metadata)\n else:\n return (blocks['redstone-torch-off'].slot, metadata)\n elif block == blocks['redstone-wire'].slot:\n if truth:\n return (block, metadata if metadata else 15)\n else:\n return (block, 0)\n elif block == blocks['lever'].slot:\n if truth:\n return (block, metadata | 8)\n else:\n return (block, metadata & ~8)\n return (block, metadata)", "context": "def truthify_block(truth, block, metadata): ...\ndef truthify_block(truth, block, metadata): ...\ndef bbool(block, metadata): ...\n", "repository": "bravoserver/bravo", "test_name": "test_truthify_lever", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001452.py"} {"focal_file": "bravo/utilities/redstone.py", "focal_class": "PlainBlock", "focal_method": "iter_outputs", "tests": "import unittest\n\nclass Test_PlainBlock_iter_outputs(unittest.TestCase):\n def test_sand_iter_outputs(self):\n \"\"\"\n Sand has several outputs.\n \"\"\"\n sand = PlainBlock((0, 0, 0), blocks['sand'].slot, 0)\n self.assertTrue((0, 1, 0) in sand.iter_outputs())\n", "method_code": " def iter_outputs(self):\n \"\"\"\n Iterate over possible output coordinates.\n \"\"\"\n x, y, z = self.coords\n for dx, dy, dz in ((-1, 0, 0), (1, 0, 0), (0, 0, -1), (0, 0, 1), (0, -1, 0), (0, 1, 0)):\n yield (x + dx, y + dy, z + dz)\n ", "context": "class Circuit(object):\n def iter_outputs(self): ...\n def __new__(cls, coordinates, block, metadata): ...\n def __str__(self): ...\n def iter_inputs(self): ...\n def connect(self, asic): ...\n def disconnect(self, asic): ...\n def update(self): ...\n def from_block(self, block, metadata): ...\n def to_block(self, block, metadata): ...\n\n asic = None\n __repr__ = __str__\n", "repository": "bravoserver/bravo", "test_name": "test_sand_iter_outputs", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001453.py"} {"focal_file": "bravo/utilities/redstone.py", "focal_class": "Torch", "focal_method": "iter_inputs", "tests": "import unittest\n\nclass Test_Torch_iter_inputs(unittest.TestCase):\n def test_torch_plus_y_iter_inputs(self):\n \"\"\"\n A torch with +y orientation sits on top of a block.\n \"\"\"\n torch = Torch((0, 1, 0), blocks['redstone-torch'].slot, blocks['redstone-torch'].orientation('+y'))\n self.assertTrue((0, 0, 0) in torch.iter_inputs())\n", "method_code": " def iter_inputs(self):\n \"\"\"\n Iterate over possible input coordinates.\n \"\"\"\n x, y, z = self.coords\n for dx, dy, dz in ((-1, 0, 0), (1, 0, 0), (0, 0, -1), (0, 0, 1), (0, -1, 0), (0, 1, 0)):\n yield (x + dx, y + dy, z + dz)\n ", "context": "class Circuit(object):\n def iter_inputs(self): ...\n def __new__(cls, coordinates, block, metadata): ...\n def __str__(self): ...\n def iter_outputs(self): ...\n def connect(self, asic): ...\n def disconnect(self, asic): ...\n def update(self): ...\n def from_block(self, block, metadata): ...\n def to_block(self, block, metadata): ...\n\n asic = None\n __repr__ = __str__\n", "repository": "bravoserver/bravo", "test_name": "test_torch_plus_y_iter_inputs", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001454.py"} {"focal_file": "bravo/utilities/redstone.py", "focal_class": "Torch", "focal_method": "iter_outputs", "tests": "import unittest\n\nclass Test_Torch_iter_outputs(unittest.TestCase):\n def test_torch_plus_z_input_output(self):\n \"\"\"\n A torch with +z orientation accepts input from one block, and sends\n output to three blocks around it.\n \"\"\"\n torch = Torch((0, 0, 0), blocks['redstone-torch'].slot, blocks['redstone-torch'].orientation('+z'))\n self.assertTrue((0, 0, -1) in torch.iter_inputs())\n self.assertTrue((0, 0, 1) in torch.iter_outputs())\n self.assertTrue((1, 0, 0) in torch.iter_outputs())\n self.assertTrue((-1, 0, 0) in torch.iter_outputs())\n", "method_code": " def iter_outputs(self):\n \"\"\"\n Iterate over possible output coordinates.\n \"\"\"\n x, y, z = self.coords\n for dx, dy, dz in ((-1, 0, 0), (1, 0, 0), (0, 0, -1), (0, 0, 1), (0, -1, 0), (0, 1, 0)):\n yield (x + dx, y + dy, z + dz)\n ", "context": "class Circuit(object):\n def iter_outputs(self): ...\n def __new__(cls, coordinates, block, metadata): ...\n def __str__(self): ...\n def iter_inputs(self): ...\n def connect(self, asic): ...\n def disconnect(self, asic): ...\n def update(self): ...\n def from_block(self, block, metadata): ...\n def to_block(self, block, metadata): ...\n\n asic = None\n __repr__ = __str__\n", "repository": "bravoserver/bravo", "test_name": "test_torch_plus_z_input_output", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001455.py"} {"focal_file": "bravo/utilities/redstone.py", "focal_class": "Torch", "focal_method": "to_block", "tests": "import unittest\n\nclass Test_Torch_to_block(unittest.TestCase):\n def test_torch_block_change(self):\n \"\"\"\n Torches change block type depending on their status. They don't change\n metadata, though.\n \"\"\"\n metadata = blocks['redstone-torch'].orientation('-x')\n torch = Torch((0, 0, 0), blocks['redstone-torch'].slot, metadata)\n torch.status = False\n self.assertEqual(torch.to_block(blocks['redstone-torch'].slot, metadata), (blocks['redstone-torch-off'].slot, metadata))\n", "method_code": " def to_block(self, block, metadata):\n return truthify_block(self.status, block, metadata)\n ", "context": "class Circuit(object):\n def to_block(self, block, metadata): ...\n def __new__(cls, coordinates, block, metadata): ...\n def __str__(self): ...\n def iter_inputs(self): ...\n def iter_outputs(self): ...\n def connect(self, asic): ...\n def disconnect(self, asic): ...\n def update(self): ...\n def from_block(self, block, metadata): ...\n\n asic = None\n __repr__ = __str__\n", "repository": "bravoserver/bravo", "test_name": "test_torch_block_change", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001456.py"} {"focal_file": "bravo/utilities/redstone.py", "focal_class": "Wire", "focal_method": "find_wires", "tests": "import unittest\n\nclass Test_Wire_find_wires(unittest.TestCase):\n def test_find_wires_single(self):\n wires = set([Wire((0, 0, 0), blocks['redstone-wire'].slot, 0)])\n for wire in wires:\n wire.connect(self.asic)\n self.assertEqual(wires, self.asic.find_wires(0, 0, 0)[1])\n\n def test_find_wires_plural(self):\n wires = set([Wire((0, 0, 0), blocks['redstone-wire'].slot, 0), Wire((1, 0, 0), blocks['redstone-wire'].slot, 0)])\n for wire in wires:\n wire.connect(self.asic)\n self.assertEqual(wires, self.asic.find_wires(0, 0, 0)[1])\n\n def test_find_wires_many(self):\n wires = set([Wire((0, 0, 0), blocks['redstone-wire'].slot, 0), Wire((1, 0, 0), blocks['redstone-wire'].slot, 0), Wire((2, 0, 0), blocks['redstone-wire'].slot, 0), Wire((2, 0, 1), blocks['redstone-wire'].slot, 0)])\n for wire in wires:\n wire.connect(self.asic)\n self.assertEqual(wires, self.asic.find_wires(0, 0, 0)[1])\n\n def test_find_wires_cross(self):\n \"\"\"\n Finding wires works when the starting point is inside a cluster of\n wires.\n \"\"\"\n wires = set([Wire((0, 0, 0), blocks['redstone-wire'].slot, 0), Wire((1, 0, 0), blocks['redstone-wire'].slot, 0), Wire((-1, 0, 0), blocks['redstone-wire'].slot, 0), Wire((0, 0, 1), blocks['redstone-wire'].slot, 0), Wire((0, 0, -1), blocks['redstone-wire'].slot, 0)])\n for wire in wires:\n wire.connect(self.asic)\n self.assertEqual(wires, self.asic.find_wires(0, 0, 0)[1])\n", "method_code": " def find_wires(self, x, y, z):\n \"\"\"\n Collate a group of neighboring wires, starting at a certain point.\n \n This function does a simple breadth-first search to find wires.\n \n The returned data is a tuple of an iterable of wires in the group with\n inputs, and an iterable of all wires in the group.\n \"\"\"\n if (x, y, z) not in self.circuits:\n raise RedstoneError('Unmanaged coords!')\n root = self.circuits[x, y, z]\n if root.name != 'wire':\n raise RedstoneError('Non-wire in find_wires')\n d = deque([root])\n wires = set()\n heads = []\n tails = []\n while d:\n w = d.pop()\n for neighbor in self._get_wire_neighbors(w):\n if neighbor not in wires:\n d.appendleft(neighbor)\n wires.add(w)\n if w.inputs:\n heads.append(w)\n if w.outputs:\n tails.append(w)\n return (heads, wires, tails)\n ", "context": "class Asic(object):\n def find_wires(self, x, y, z): ...\n def __init__(self): ...\n def _get_wire_neighbors(self, wire): ...\n def update_wires(self, x, y, z): ...\n\n self.circuits = {}\n self._wire_cache = {}\n\n level_marker = object()\n", "repository": "bravoserver/bravo", "test_name": "test_find_wires_single", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001457.py"} {"focal_file": "bravo/utilities/redstone.py", "focal_class": "Torch", "focal_method": "find_wires", "tests": "import unittest\n\nclass Test_Torch_find_wires(unittest.TestCase):\n def test_find_wires_inputs_many(self):\n inputs = set([Wire((0, 0, 0), blocks['redstone-wire'].slot, 0), Wire((2, 0, 1), blocks['redstone-wire'].slot, 0)])\n wires = set([Wire((1, 0, 0), blocks['redstone-wire'].slot, 0), Wire((2, 0, 0), blocks['redstone-wire'].slot, 0)])\n wires.update(inputs)\n torches = set([Torch((0, 0, 1), blocks['redstone-torch'].slot, blocks['redstone-torch'].orientation('-z')), Torch((3, 0, 1), blocks['redstone-torch'].slot, blocks['redstone-torch'].orientation('-x'))])\n for wire in wires:\n wire.connect(self.asic)\n for torch in torches:\n torch.connect(self.asic)\n self.assertEqual(inputs, set(self.asic.find_wires(0, 0, 0)[0]))\n", "method_code": " def find_wires(self, x, y, z):\n \"\"\"\n Collate a group of neighboring wires, starting at a certain point.\n \n This function does a simple breadth-first search to find wires.\n \n The returned data is a tuple of an iterable of wires in the group with\n inputs, and an iterable of all wires in the group.\n \"\"\"\n if (x, y, z) not in self.circuits:\n raise RedstoneError('Unmanaged coords!')\n root = self.circuits[x, y, z]\n if root.name != 'wire':\n raise RedstoneError('Non-wire in find_wires')\n d = deque([root])\n wires = set()\n heads = []\n tails = []\n while d:\n w = d.pop()\n for neighbor in self._get_wire_neighbors(w):\n if neighbor not in wires:\n d.appendleft(neighbor)\n wires.add(w)\n if w.inputs:\n heads.append(w)\n if w.outputs:\n tails.append(w)\n return (heads, wires, tails)\n ", "context": "class Asic(object):\n def find_wires(self, x, y, z): ...\n def __init__(self): ...\n def _get_wire_neighbors(self, wire): ...\n def update_wires(self, x, y, z): ...\n\n self.circuits = {}\n self._wire_cache = {}\n\n level_marker = object()\n", "repository": "bravoserver/bravo", "test_name": "test_find_wires_inputs_many", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001458.py"} {"focal_file": "bravo/utilities/redstone.py", "focal_class": "Torch", "focal_method": "update_wires", "tests": "import unittest\n\nclass Test_Torch_update_wires(unittest.TestCase):\n def test_update_wires_single(self):\n torch = Torch((0, 0, 0), blocks['redstone-torch-off'].slot, blocks['redstone-torch'].orientation('-x'))\n wire = Wire((1, 0, 0), blocks['redstone-wire'].slot, 0)\n plain = PlainBlock((2, 0, 0), blocks['sand'].slot, 0)\n torch.connect(self.asic)\n wire.connect(self.asic)\n plain.connect(self.asic)\n wires, outputs = self.asic.update_wires(1, 0, 0)\n self.assertTrue(wire in wires)\n self.assertTrue(plain in outputs)\n self.assertFalse(wire.status)\n self.assertEqual(wire.metadata, 0)\n\n def test_update_wires_single_powered(self):\n torch = Torch((0, 0, 0), blocks['redstone-torch'].slot, blocks['redstone-torch'].orientation('-x'))\n wire = Wire((1, 0, 0), blocks['redstone-wire'].slot, 0)\n plain = PlainBlock((2, 0, 0), blocks['sand'].slot, 0)\n torch.connect(self.asic)\n wire.connect(self.asic)\n plain.connect(self.asic)\n torch.status = True\n wires, outputs = self.asic.update_wires(1, 0, 0)\n self.assertTrue(wire in wires)\n self.assertTrue(plain in outputs)\n self.assertTrue(wire.status)\n self.assertEqual(wire.metadata, 15)\n\n def test_update_wires_multiple(self):\n torch = Torch((0, 0, 0), blocks['redstone-torch-off'].slot, blocks['redstone-torch'].orientation('-x'))\n wire = Wire((1, 0, 0), blocks['redstone-wire'].slot, 0)\n wire2 = Wire((1, 0, 1), blocks['redstone-wire'].slot, 0)\n plain = PlainBlock((2, 0, 0), blocks['sand'].slot, 0)\n torch.connect(self.asic)\n wire.connect(self.asic)\n wire2.connect(self.asic)\n plain.connect(self.asic)\n wires, outputs = self.asic.update_wires(1, 0, 0)\n self.assertTrue(wire in wires)\n self.assertTrue(wire2 in wires)\n self.assertTrue(plain in outputs)\n self.assertFalse(wire.status)\n self.assertEqual(wire.metadata, 0)\n self.assertFalse(wire2.status)\n self.assertEqual(wire2.metadata, 0)\n", "method_code": " def update_wires(self, x, y, z):\n \"\"\"\n Find all the wires in a group and update them all, by force if\n necessary.\n \n Returns a list of outputs belonging to this wire group, for\n convenience.\n \"\"\"\n heads, wires, tails = self.find_wires(x, y, z)\n outputs = set()\n for wire in tails:\n outputs.update(wire.outputs)\n retval = (wires.copy(), outputs)\n for head in heads:\n Circuit.update(head)\n starters = [head for head in heads if head.status]\n visited = set(starters)\n for level in xrange(15, 0, -1):\n if not visited:\n break\n to_visit = set()\n for wire in visited:\n wire.status = True\n wire.metadata = level\n for neighbor in self._get_wire_neighbors(wire):\n if neighbor in wires:\n to_visit.add(neighbor)\n wires -= visited\n visited = to_visit\n for wire in wires:\n wire.status = False\n wire.metadata = 0\n return retval\n ", "context": "class Asic(object):\n def update_wires(self, x, y, z): ...\n def __init__(self): ...\n def _get_wire_neighbors(self, wire): ...\n def find_wires(self, x, y, z): ...\n\n self.circuits = {}\n self._wire_cache = {}\n\n level_marker = object()\n", "repository": "bravoserver/bravo", "test_name": "test_update_wires_single", "smells": [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001459.py"} {"focal_file": "enum34-0.9.23/build/lib/enum/__init__.py", "focal_class": null, "focal_method": "_is_descriptor", "tests": "import unittest\n\nclass Test_is_descriptor(unittest.TestCase):\n def test_is_descriptor(self):\n\n class foo:\n pass\n for attr in ('__get__', '__set__', '__delete__'):\n obj = foo()\n self.assertFalse(enum._is_descriptor(obj))\n setattr(obj, attr, 1)\n self.assertTrue(enum._is_descriptor(obj))\n\n def test_is_descriptor(self):\n\n class foo:\n pass\n for attr in ('__get__', '__set__', '__delete__'):\n obj = foo()\n self.assertFalse(enum._is_descriptor(obj))\n setattr(obj, attr, 1)\n self.assertTrue(enum._is_descriptor(obj))\n", "method_code": "def _is_descriptor(obj):\n \"\"\"Returns True if obj is a descriptor, False otherwise.\"\"\"\n return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')", "context": "def _is_descriptor(obj): ...\ndef _is_descriptor(obj): ...\ndef _is_dunder(name): ...\ndef _is_sunder(name): ...\ndef _make_class_unpicklable(cls): ...\ndef __new__(cls, value): ...\ndef __repr__(self): ...\ndef __str__(self): ...\ndef __dir__(self): ...\ndef __format__(self, format_spec): ...\ndef __eq__(self, other): ...\ndef __ne__(self, other): ...\ndef __getnewargs__(self): ...\ndef __hash__(self): ...\ndef __reduce_ex__(self, proto): ...\ndef name(self): ...\ndef value(self): ...\ndef unique(enumeration): ...\n", "repository": "str8Astud3nt/SuperConductor", "test_name": "test_is_descriptor", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001460.py"} {"focal_file": "enum34-0.9.23/build/lib/enum/__init__.py", "focal_class": null, "focal_method": "_is_sunder", "tests": "import unittest\n\nclass Test_is_sunder(unittest.TestCase):\n def test_is_sunder(self):\n for s in ('_a_', '_aa_'):\n self.assertTrue(enum._is_sunder(s))\n for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_', '__', '___', '____', '_____'):\n self.assertFalse(enum._is_sunder(s))\n\n def test_is_sunder(self):\n for s in ('_a_', '_aa_'):\n self.assertTrue(enum._is_sunder(s))\n for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_', '__', '___', '____', '_____'):\n self.assertFalse(enum._is_sunder(s))\n", "method_code": "def _is_sunder(name):\n \"\"\"Returns True if a _sunder_ name, False otherwise.\"\"\"\n return name[0] == name[-1] == '_' and name[1:2] != '_' and (name[-2:-1] != '_') and (len(name) > 2)", "context": "def _is_sunder(name): ...\ndef _is_descriptor(obj): ...\ndef _is_dunder(name): ...\ndef _is_sunder(name): ...\ndef _make_class_unpicklable(cls): ...\ndef __new__(cls, value): ...\ndef __repr__(self): ...\ndef __str__(self): ...\ndef __dir__(self): ...\ndef __format__(self, format_spec): ...\ndef __eq__(self, other): ...\ndef __ne__(self, other): ...\ndef __getnewargs__(self): ...\ndef __hash__(self): ...\ndef __reduce_ex__(self, proto): ...\ndef name(self): ...\ndef value(self): ...\ndef unique(enumeration): ...\n", "repository": "str8Astud3nt/SuperConductor", "test_name": "test_is_sunder", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001461.py"} {"focal_file": "enum34-0.9.23/build/lib/enum/__init__.py", "focal_class": null, "focal_method": "_is_dunder", "tests": "import unittest\n\nclass Test_is_dunder(unittest.TestCase):\n def test_is_dunder(self):\n for s in ('__a__', '__aa__'):\n self.assertTrue(enum._is_dunder(s))\n for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_', '__', '___', '____', '_____'):\n self.assertFalse(enum._is_dunder(s))\n\n def test_is_dunder(self):\n for s in ('__a__', '__aa__'):\n self.assertTrue(enum._is_dunder(s))\n for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_', '__', '___', '____', '_____'):\n self.assertFalse(enum._is_dunder(s))\n", "method_code": "def _is_dunder(name):\n \"\"\"Returns True if a __dunder__ name, False otherwise.\"\"\"\n return name[:2] == name[-2:] == '__' and name[2:3] != '_' and (name[-3:-2] != '_') and (len(name) > 4)", "context": "def _is_dunder(name): ...\ndef _is_descriptor(obj): ...\ndef _is_dunder(name): ...\ndef _is_sunder(name): ...\ndef _make_class_unpicklable(cls): ...\ndef __new__(cls, value): ...\ndef __repr__(self): ...\ndef __str__(self): ...\ndef __dir__(self): ...\ndef __format__(self, format_spec): ...\ndef __eq__(self, other): ...\ndef __ne__(self, other): ...\ndef __getnewargs__(self): ...\ndef __hash__(self): ...\ndef __reduce_ex__(self, proto): ...\ndef name(self): ...\ndef value(self): ...\ndef unique(enumeration): ...\n", "repository": "str8Astud3nt/SuperConductor", "test_name": "test_is_dunder", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001462.py"} {"focal_file": "enum34-0.9.23/build/lib/enum/__init__.py", "focal_class": null, "focal_method": "unique", "tests": "import unittest\n\nclass Test_unique(unittest.TestCase):\n def test_unique_clean(self):\n\n class Clean(Enum):\n one = 1\n two = 'dos'\n tres = 4.0\n unique(Clean)\n\n class Cleaner(IntEnum):\n single = 1\n double = 2\n triple = 3\n unique(Cleaner)\n\n def test_unique_dirty(self):\n try:\n\n class Dirty(Enum):\n __order__ = 'one two tres'\n one = 1\n two = 'dos'\n tres = 1\n unique(Dirty)\n except ValueError:\n exc = sys.exc_info()[1]\n message = exc.args[0]\n self.assertTrue('tres -> one' in message)\n try:\n\n class Dirtier(IntEnum):\n __order__ = 'single double triple turkey'\n single = 1\n double = 1\n triple = 3\n turkey = 3\n unique(Dirtier)\n except ValueError:\n exc = sys.exc_info()[1]\n message = exc.args[0]\n self.assertTrue('double -> single' in message)\n self.assertTrue('turkey -> triple' in message)\n\n def test_unique_clean(self):\n\n class Clean(Enum):\n one = 1\n two = 'dos'\n tres = 4.0\n unique(Clean)\n\n class Cleaner(IntEnum):\n single = 1\n double = 2\n triple = 3\n unique(Cleaner)\n\n def test_unique_dirty(self):\n try:\n\n class Dirty(Enum):\n __order__ = 'one two tres'\n one = 1\n two = 'dos'\n tres = 1\n unique(Dirty)\n except ValueError:\n exc = sys.exc_info()[1]\n message = exc.args[0]\n self.assertTrue('tres -> one' in message)\n try:\n\n class Dirtier(IntEnum):\n __order__ = 'single double triple turkey'\n single = 1\n double = 1\n triple = 3\n turkey = 3\n unique(Dirtier)\n except ValueError:\n exc = sys.exc_info()[1]\n message = exc.args[0]\n self.assertTrue('double -> single' in message)\n self.assertTrue('turkey -> triple' in message)\n", "method_code": "def unique(enumeration):\n \"\"\"Class decorator that ensures only unique members exist in an enumeration.\"\"\"\n duplicates = []\n for name, member in enumeration.__members__.items():\n if name != member.name:\n duplicates.append((name, member.name))\n if duplicates:\n duplicate_names = ', '.join(['%s -> %s' % (alias, name) for alias, name in duplicates])\n raise ValueError('duplicate names found in %r: %s' % (enumeration, duplicate_names))\n return enumeration", "context": "def unique(enumeration): ...\ndef _is_descriptor(obj): ...\ndef _is_dunder(name): ...\ndef _is_sunder(name): ...\ndef _make_class_unpicklable(cls): ...\ndef __new__(cls, value): ...\ndef __repr__(self): ...\ndef __str__(self): ...\ndef __dir__(self): ...\ndef __format__(self, format_spec): ...\ndef __eq__(self, other): ...\ndef __ne__(self, other): ...\ndef __getnewargs__(self): ...\ndef __hash__(self): ...\ndef __reduce_ex__(self, proto): ...\ndef name(self): ...\ndef value(self): ...\ndef unique(enumeration): ...\n", "repository": "str8Astud3nt/SuperConductor", "test_name": "test_unique_clean", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], "pynose_source_file": "test_001463.py"} {"focal_file": "packages/RStar/rstar/test/momentum_test.py", "focal_class": null, "focal_method": "doTestArbitrarilyPassMomentum", "tests": "import unittest\n\nclass Test_doTestArbitrarilyPassMomentum(unittest.TestCase):\n def testArbitrarilyPassMomentum(self):\n self.doTestArbitrarilyPassMomentum('ee12|23|3|ee|:(0,0)_(0,0)_(1,0)_(1,0)|(1,0)_(1,0)|(1,0)|(0,0)_(0,0)|:::', 3)\n self.doTestArbitrarilyPassMomentum('ee12|3|3|ee|:(0,0)_(0,0)_(1,0)_(1,0)|(1,0)|(1,0)|(0,0)_(0,0)|:::', 2)\n self.doTestArbitrarilyPassMomentum('11||:(1,0)_(1,0)||:::', 1)\n", "method_code": " def doTestArbitrarilyPassMomentum(self, graph_state_str, graphs_number):\n g = graph_util.graph_from_str(graph_state_str)\n graphs_with_passed_momentum = [x for x in momentum.arbitrarily_pass_momentum(g)]\n for _g in graphs_with_passed_momentum:\n self.assertEquals(len(_g.edges(_g.external_vertex)), 2)\n self.assertEquals(len(graphs_with_passed_momentum), graphs_number, graphs_with_passed_momentum)\n ", "context": "class SubGraphReducerTestCase(unittest.TestCase):\n def doTestArbitrarilyPassMomentum(self, graph_state_str, graphs_number): ...\n def testArbitrarilyPassMomentum(self): ...\n def testArbitraryPassMomentum(self): ...\n", "repository": "batya239/rg-graph", "test_name": "testArbitrarilyPassMomentum", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001464.py"} {"focal_file": "change_prediction/tests.py", "focal_class": null, "focal_method": "construct", "tests": "import unittest\n\nclass Test_construct(unittest.TestCase):\n def test_construct(self):\n with self.assertRaises(predict.DataFactoryException):\n self.d.construct()\n", "method_code": " def construct(self):\n return ([(1, 0), (0, 1), (0, 0), (1, 1)], [(1,), (1,), (0,), (0,)])\n ", "context": "class CustomData(predict.DataFactory):\n def construct(self): ...", "repository": "0x1001/StockMarket", "test_name": "test_construct", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001465.py"} {"focal_file": "crypto/exchange.py", "focal_class": null, "focal_method": "get_chart_data", "tests": "import unittest\n\nclass Test_get_chart_data(unittest.TestCase):\n def test_get_chart_data(self):\n for k, v in exchange.get_chart_data('USDT_BTC')[0].items():\n print('{0} - {1}'.format(k, v))\n", "method_code": "def get_chart_data(currency_pair):\n polo = poloniex.Poloniex()\n error = Exception('Cannot get data from exchange')\n for i in range(10):\n try:\n data = polo.returnChartData(currency_pair, 300, start=time.time() - 1 * polo.YEAR, end=time.time())\n except poloniex.PoloniexError as error:\n pass\n else:\n break\n else:\n raise error\n return data", "context": "def get_chart_data(currency_pair): ...\ndef get_chart_data(currency_pair): ...\ndef get_all_coin_pairs(): ...\ndef plot_chart_data(data, currency_pair, file_name=None, ymin=None, ymax=None): ...\ndef find_tree_line_strike(data): ...\ndef find_two_black_gapping(data): ...\ndef find_three_black_crows(data): ...\ndef find_evening_star(data): ...\ndef find_abandoned_baby(data): ...\ndef what_to_sell(): ...\ndef what_to_buy(): ...\ndef get_balance(): ...\ndef get_open_orders(): ...\ndef filter_open_orders(data): ...\ndef display_open_orders(data): ...\ndef display_balance(coins): ...\ndef plot_balance(coins): ...\ndef convert_to_float(data): ...\ndef convert_to_float_balance(data): ...\ndef display_predictions(found, prefix): ...\ndef get_key(): ...\n", "repository": "0x1001/StockMarket", "test_name": "test_get_chart_data", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_001466.py"} {"focal_file": "crypto/exchange.py", "focal_class": null, "focal_method": "plot_chart_data", "tests": "import unittest\n\nclass Test_plot_chart_data(unittest.TestCase):\n def test_plot_chart_data(self):\n data = exchange.get_chart_data('USDT_BTC')\n exchange.plot_chart_data(data[-10:], 'USDT_BTC')\n", "method_code": "def plot_chart_data(data, currency_pair, file_name=None, ymin=None, ymax=None):\n fig1, ax1 = plt.subplots()\n candlestick2_ochl(ax1, opens=[float(d['open']) for d in data], closes=[float(d['close']) for d in data], highs=[float(d['high']) for d in data], lows=[float(d['low']) for d in data], width=0.5, colorup='green')\n change = helper.calculate_difference_in_percent(float(data[0]['open']), float(data[-1]['close']))\n plt.title('{0} {1:.2f}%'.format(currency_pair, change))\n if ymin and ymax:\n plt.ylim(ymin=ymin, ymax=ymax)\n plt.tight_layout()\n if file_name:\n plt.savefig(file_name)\n plt.close()\n else:\n plt.show()", "context": "def plot_chart_data(data, currency_pair, file_name=None, ymin=None, ymax=None): ...\ndef get_chart_data(currency_pair): ...\ndef get_all_coin_pairs(): ...\ndef plot_chart_data(data, currency_pair, file_name=None, ymin=None, ymax=None): ...\ndef find_tree_line_strike(data): ...\ndef find_two_black_gapping(data): ...\ndef find_three_black_crows(data): ...\ndef find_evening_star(data): ...\ndef find_abandoned_baby(data): ...\ndef what_to_sell(): ...\ndef what_to_buy(): ...\ndef get_balance(): ...\ndef get_open_orders(): ...\ndef filter_open_orders(data): ...\ndef display_open_orders(data): ...\ndef display_balance(coins): ...\ndef plot_balance(coins): ...\ndef convert_to_float(data): ...\ndef convert_to_float_balance(data): ...\ndef display_predictions(found, prefix): ...\ndef get_key(): ...\n", "repository": "0x1001/StockMarket", "test_name": "test_plot_chart_data", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001467.py"} {"focal_file": "crypto/exchange.py", "focal_class": null, "focal_method": "get_all_coin_pairs", "tests": "import unittest\n\nclass Test_get_all_coin_pairs(unittest.TestCase):\n def test_get_all_coin_pairs(self):\n print(exchange.get_all_coin_pairs())\n", "method_code": "def get_all_coin_pairs():\n polo = poloniex.Poloniex()\n data = polo.returnTicker()\n return list(data.keys())", "context": "def get_all_coin_pairs(): ...\ndef get_chart_data(currency_pair): ...\ndef get_all_coin_pairs(): ...\ndef plot_chart_data(data, currency_pair, file_name=None, ymin=None, ymax=None): ...\ndef find_tree_line_strike(data): ...\ndef find_two_black_gapping(data): ...\ndef find_three_black_crows(data): ...\ndef find_evening_star(data): ...\ndef find_abandoned_baby(data): ...\ndef what_to_sell(): ...\ndef what_to_buy(): ...\ndef get_balance(): ...\ndef get_open_orders(): ...\ndef filter_open_orders(data): ...\ndef display_open_orders(data): ...\ndef display_balance(coins): ...\ndef plot_balance(coins): ...\ndef convert_to_float(data): ...\ndef convert_to_float_balance(data): ...\ndef display_predictions(found, prefix): ...\ndef get_key(): ...\n", "repository": "0x1001/StockMarket", "test_name": "test_get_all_coin_pairs", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_001468.py"} {"focal_file": "crypto/generate_training_data.py", "focal_class": null, "focal_method": "get_data", "tests": "import unittest\n\nclass Test_get_data(unittest.TestCase):\n def test_get_data(self):\n all_data = generate_training_data.get_data()\n k = 0\n for d in all_data:\n k += len(d)\n print(k)\n", "method_code": "def get_data():\n print('Getting data from exchange. For {0}'.format(CURRENCY_PAIRS))\n all_data = []\n for currency_pair in CURRENCY_PAIRS:\n path = currency_pair + '_' + EXCHANGE_DATA\n if os.path.isfile(path):\n with open(path, 'rb') as fp:\n all_data.append(pickle.load(fp))\n else:\n data = exchange.get_chart_data(currency_pair)\n all_data.append(data)\n with open(path, 'wb') as fp:\n pickle.dump(data, fp)\n print('Progress {2}: {0} / {1}'.format(CURRENCY_PAIRS.index(currency_pair), len(CURRENCY_PAIRS), currency_pair))\n return all_data", "context": "def get_data(): ...\ndef get_data(): ...\ndef generate_automatic(data, file_name, number_of_samples): ...\ndef expected_output(data, idx): ...\ndef one_hot_encoding(data): ...\n", "repository": "0x1001/StockMarket", "test_name": "test_get_data", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_001469.py"} {"focal_file": "crypto/neural_network.py", "focal_class": null, "focal_method": "batch_data", "tests": "import unittest\n\nclass Test_batch_data(unittest.TestCase):\n def test_batch_data(self):\n for data, expected in neural_network.batch_data(100):\n print(len(data), len(expected))\n", "method_code": "def batch_data(batch_size):\n with open(generate_training_data.TRAINING_DB_FILE, 'r', buffering=100000) as fp:\n while True:\n y = []\n x = []\n for _ in range(batch_size):\n line = fp.readline()\n if line != '':\n stimuli_data, expected_data = _read_data(line)\n x.append(stimuli_data)\n y.append(expected_data)\n else:\n if x and y:\n yield (x, y)\n raise StopIteration\n yield (x, y)", "context": "def batch_data(batch_size): ...\ndef neural_network_model(data): ...\ndef train_neural_network(x): ...\ndef batch_data(batch_size): ...\ndef _read_data(line): ...\ndef test_data(): ...\n", "repository": "0x1001/StockMarket", "test_name": "test_batch_data", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_001470.py"} {"focal_file": "crypto/training_data.py", "focal_class": null, "focal_method": "ask", "tests": "import unittest\n\nclass Test_ask(unittest.TestCase):\n def test_ask(self):\n training_data.ask()\n", "method_code": "def ask():\n currency_pair = 'USDT_BTC'\n data = exchange.get_chart_data(currency_pair)\n while True:\n start = random.randint(0, len(data) - (RANGE + RANGE_AFTER) - 1)\n slice = data[start:start + RANGE]\n slice_after = data[start + RANGE:start + (RANGE + RANGE_AFTER)]\n ymin = min([float(d['low']) for d in slice + slice_after])\n ymax = max([float(d['high']) for d in slice + slice_after])\n exchange.plot_chart_data(slice, currency_pair, TEMP_FILE_BEFORE, ymin, ymax)\n exchange.plot_chart_data(slice_after, currency_pair, TEMP_FILE_AFTER, ymin, ymax)\n answer = _gui_question()\n if answer:\n td = TrainingData()\n td.data = slice\n td.feedback = answer\n td.currency_pair = currency_pair\n _save(td)\n else:\n break", "context": "def ask(): ...\ndef ask(): ...\ndef _gui_question(): ...\ndef generate_automatic(): ...\ndef _save(data): ...\n", "repository": "0x1001/StockMarket", "test_name": "test_ask", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001471.py"} {"focal_file": "crypto/training_data.py", "focal_class": null, "focal_method": "generate_automatic", "tests": "import unittest\n\nclass Test_generate_automatic(unittest.TestCase):\n def test_generate_automatic(self):\n training_data.generate_automatic()\n", "method_code": "def generate_automatic():\n currency_pairs = ['USDT_BTC', 'USDT_ETH', 'USDT_LTC', 'USDT_ZEC', 'USDT_ETC', 'USDT_REP', 'USDT_XMR', 'USDT_STR', 'USDT_DASH', 'USDT_XRP']\n all_data = []\n for currency_pair in currency_pairs:\n data = exchange.get_chart_data(currency_pair)\n all_data.append(data)\n print('Progress {2}: {0} / {1}'.format(currency_pairs.index(currency_pair), len(currency_pairs), currency_pair))\n _save(all_data)", "context": "def generate_automatic(): ...\ndef ask(): ...\ndef _gui_question(): ...\ndef generate_automatic(): ...\ndef _save(data): ...\n", "repository": "0x1001/StockMarket", "test_name": "test_generate_automatic", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001472.py"} {"focal_file": "jarvis/database/databasebuilder.py", "focal_class": null, "focal_method": "addTxtFile", "tests": "import unittest\n\nclass Test_addTxtFile(unittest.TestCase):\n def test_addTxtFile(self):\n self.builder.addTxtFile('sample.txt')\n", "method_code": " def addTxtFile(self, path):\n \"\"\"\n This function adds file to list that is used to generate word database\n \n Input\n path - File path\n \n Returns:\n Nothing\n \"\"\"\n self._file_list.append(path)\n ", "context": "class DataBaseBuilder(object):\n def addTxtFile(self, path): ...\n def __init__(self): ...\n def generateDataBase(self): ...\n def _readFileContents(self, file_path): ...\n\n self._file_list = []\n", "repository": "0x1001/jarvis", "test_name": "test_addTxtFile", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001473.py"} {"focal_file": "jarvis/database/databasebuilder.py", "focal_class": null, "focal_method": "generateDataBase", "tests": "import unittest\n\nclass Test_generateDataBase(unittest.TestCase):\n def test_generateDataBase_exception(self):\n from database import DataBaseBuilderException\n with self.assertRaises(DataBaseBuilderException):\n self.builder.generateDataBase()\n", "method_code": " def generateDataBase(self):\n \"\"\"\n This method has to be implemented in child class.\n \n Input:\n Nothing\n \n Returns:\n database\n \"\"\"\n raise DataBaseBuilderException('Not implemented!')\n ", "context": "class DataBaseBuilder(object):\n def generateDataBase(self): ...\n def __init__(self): ...\n def addTxtFile(self, path): ...\n def _readFileContents(self, file_path): ...\n\n self._file_list = []\n", "repository": "0x1001/jarvis", "test_name": "test_generateDataBase_exception", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001474.py"} {"focal_file": "jarvis/database/databasebuilder.py", "focal_class": null, "focal_method": "_readFileContents", "tests": "import unittest\n\nclass Test_readFileContents(unittest.TestCase):\n def test_readFileContents_exception(self):\n from database import DataBaseBuilderException\n with self.assertRaises(DataBaseBuilderException):\n contents = self.builder._readFileContents('fff.txt')\n\n def test_readFileContents(self):\n contents = self.builder._readFileContents('sample.txt')\n self.assertIsInstance(contents, str)\n self.assertIn('aaa', contents)\n self.assertIn('ddd', contents)\n", "method_code": " def _readFileContents(self, file_path):\n \"\"\"\n Reads file contents\n \n Input:\n file_path - Path to file\n \n Returns:\n list of lines\n \"\"\"\n import lowlevel\n try:\n return lowlevel.readFileContents(file_path)\n except lowlevel.LowLevelException as error:\n raise DataBaseBuilderException('Cannot open: ' + file_path + ' . Error: ' + str(error))\n ", "context": "class DataBaseBuilder(object):\n def _readFileContents(self, file_path): ...\n def __init__(self): ...\n def addTxtFile(self, path): ...\n def generateDataBase(self): ...\n\n self._file_list = []\n", "repository": "0x1001/jarvis", "test_name": "test_readFileContents_exception", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001475.py"} {"focal_file": "jarvis/abilities/a_test.py", "focal_class": null, "focal_method": "execute", "tests": "import unittest\n\nclass Test_execute(unittest.TestCase):\n def test_execute(self):\n from database import WordRecord\n from abilities import a_didyouknow\n ability = a_didyouknow.DidYouKnow()\n result = ability.execute()\n for element in result:\n self.assertIsInstance(element, WordRecord)\n", "method_code": " def execute(self):\n \"\"\"\n Test ability\n \n Input:\n Nothing\n \n Returns:\n Nothing\n \"\"\"\n from database import WordRecord\n return [WordRecord('test')]\n ", "context": "class Test(Ability):\n def execute(self): ...", "repository": "0x1001/jarvis", "test_name": "test_execute", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001476.py"} {"focal_file": "app/photo_tests.py", "focal_class": null, "focal_method": "_prep_photo", "tests": "import unittest\n\nclass Test_prep_photo(unittest.TestCase):\n def test_photo(self):\n import photo\n import tempfile\n import os\n s = self._prep_photo()\n p = photo.Photo(s)\n p.save(tempfile.gettempdir())\n img_path = os.path.join(tempfile.gettempdir(), p.name)\n thm_path = os.path.join(tempfile.gettempdir(), p.thumbnail)\n self.assertTrue(os.path.isfile(img_path))\n self.assertTrue(os.path.isfile(thm_path))\n os.unlink(img_path)\n os.unlink(thm_path)\n p.get_base64_contents()\n p.get_contents()\n", "method_code": " def _prep_photo(self):\n with open('test_data/sample1.jpg', 'rb') as fp:\n return fp.read()\n ", "context": "class Test_Photo(unittest.TestCase):\n def _prep_photo(self): ...\n def test_photo(self): ...\n", "repository": "0x1001/Webcam", "test_name": "test_photo", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001477.py"} {"focal_file": "app/storage_tests.py", "focal_class": null, "focal_method": "_prep_recording", "tests": "import unittest\n\nclass Test_prep_recording(unittest.TestCase):\n def test_save_recording(self):\n self._create_env()\n r = self._prep_recording()\n p = self._prep_photo()\n s = self.TStorage()\n s.save_recording(r, p)\n s.save_photo(p)\n s.save_motion(r, p)\n", "method_code": " def _prep_recording(self):\n import recording\n with open('test_data/test.h264', 'rb') as fp:\n s = fp.read()\n return recording.Recording(s, 2)\n ", "context": "class Test_Storage(unittest.TestCase):\n def _prep_recording(self): ...\n def _prep_photo(self): ...\n def _create_env(self): ...\n def test_basic(self): ...\n def test_save_recording(self): ...\n def test_get_all_photos(self): ...\n def test_get_all_recordings(self): ...\n", "repository": "0x1001/Webcam", "test_name": "test_save_recording", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001478.py"} {"focal_file": "process_trace.py", "focal_class": null, "focal_method": "check", "tests": "import unittest\n\nclass Test_check(unittest.TestCase):\n def test_simple_make_cycle(self):\n with TemporaryDirectory() as tmpdir:\n makefile = Path(tmpdir, 'Makefile')\n hello_c = Path(tmpdir, 'hello.c')\n hello = Path(tmpdir, 'hello')\n with makefile.open('w') as f:\n f.write(self.makefile_contents)\n with hello_c.open('w') as f:\n f.write(self.hello_c_contents)\n argv = ['make']\n expect_make = ExpectedProcessTrace(argv, cwd=tmpdir)\n expect_make.make()\n expect_make.check(makefile.name, True)\n expect_make.read(makefile.name)\n expect_make.check(hello_c.name, True)\n expect_make.check(hello.name, False)\n expect_make.check(hello.name, True)\n argv_rule = ['cp', hello_c.name, hello.name]\n expect_rule = expect_make.fork_exec(argv_rule, cwd=tmpdir)\n expect_rule.path_lookup('cp', only_missing=True)\n expect_rule.ld('acl', 'attr')\n expect_rule.check(hello_c.name, True)\n expect_rule.check(hello.name, False)\n expect_rule.read(hello_c.name)\n expect_rule.write(hello.name)\n self.assertFalse(hello.exists())\n self.run_test(expect_make, argv, cwd=tmpdir)\n self.assertTrue(hello.exists())\n expect_make2 = ExpectedProcessTrace(argv, cwd=tmpdir)\n expect_make2.make()\n expect_make2.check(makefile.name, True)\n expect_make2.read(makefile.name)\n expect_make2.check(hello_c.name, True)\n expect_make2.check(hello.name, True)\n self.assertTrue(hello.exists())\n self.run_test(expect_make2, argv, cwd=tmpdir)\n self.assertTrue(hello.exists())\n argv = ['make', 'clean']\n expect_make3 = ExpectedProcessTrace(argv, cwd=tmpdir)\n expect_make3.make()\n expect_make3.check(makefile.name, True)\n expect_make3.read(makefile.name)\n argv_clean = ['rm', '-f', hello.name]\n expect_clean = expect_make3.fork_exec(argv_clean, cwd=tmpdir)\n expect_clean.path_lookup('rm', only_missing=True)\n expect_clean.ld()\n expect_clean.check(hello.name, True)\n expect_clean.write(hello.name)\n self.assertTrue(hello.exists())\n self.run_test(expect_make3, argv, cwd=tmpdir)\n self.assertFalse(hello.exists())\n", "method_code": " def check(self, path, exists):\n self.paths_checked.add((str(path), self.cwd / path, exists))\n ", "context": "class ProcessTrace():\n def check(self, path, exists): ...\n def from_events(cls, events, cwd=None): ...\n def __init__(self, pid=None, ppid=None, cwd=None, executable=None, argv=None, env=None, paths_read=None, paths_written=None, paths_checked=None, exit_code=None): ...\n def json(self): ...\n def collapsed(self): ...\n def exec(self, executable, argv, env): ...\n def read(self, path): ...\n def write(self, path): ...\n def exit(self, exit_code): ...\n def fork(self, child_pid): ...\n def chdir(self, path): ...\n\n self.pid = pid\n self.ppid = ppid\n self.cwd = Path.cwd() if cwd is None else Path(cwd)\n self.executable = None if executable is None else self.cwd / executable\n self.argv = argv\n self.env = env\n self.paths_read = set()\n self.paths_written = set()\n self.paths_checked = set()\n self.exit_code = exit_code\n self.children = []\n", "repository": "jherland/depfinder", "test_name": "test_simple_make_cycle", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001479.py"} {"focal_file": "downloading_data/country_codes.py", "focal_class": null, "focal_method": "get_country_code", "tests": "import unittest\n\nclass Test_get_country_code(unittest.TestCase):\n def test_country_code(self):\n \"\"\" Does the program return the right country codes. \"\"\"\n country_code = get_country_code('Finland')\n self.assertEqual(country_code, 'fi')\n country_code = get_country_code('United Arab Emirates')\n self.assertEqual(country_code, 'ae')\n country_code = get_country_code('Sweden')\n self.assertEqual(country_code, 'se')\n country_code = get_country_code('Lebanon')\n self.assertEqual(country_code, 'lb')\n", "method_code": "def get_country_code(country_name):\n \"\"\" Return the pygal 2-digit country code for the given country. \"\"\"\n for code, name in COUNTRIES.items():\n if name == country_name:\n return code\n else:\n if country_name == 'Yemen, Rep.':\n return 'ye'\n if country_name == 'Bolivia':\n return 'bo'\n elif country_name == 'Congo, Rep.':\n return 'cg'\n elif country_name == 'Dominica':\n return 'do'\n elif country_name == 'Egypt, Arab Rep.':\n return 'eg'\n elif country_name == 'Iran, Islamic Rep.':\n return 'ir'\n elif country_name == 'Korea, Rep.':\n return 'kr'\n elif country_name == 'Kyrgyz Republic':\n return 'kg'\n elif country_name == 'Libya':\n return 'ly'\n elif country_name == 'Slovak Republic':\n return 'sk'\n elif country_name == 'Tanzania':\n return 'tz'\n elif country_name == 'Venezuela, RB':\n return 've'\n elif country_name == 'Vietnam':\n return 'vn'\n return None", "context": "def get_country_code(country_name): ...\ndef get_country_code(country_name): ...\n", "repository": "0mppula/Python_Data_Visualization", "test_name": "test_country_code", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001480.py"} {"focal_file": "sql/__init__.py", "focal_class": null, "focal_method": "select", "tests": "import unittest\n\nclass Test_select(unittest.TestCase):\n def test_as_select(self):\n query = self.table.select(self.column.as_('foo'))\n self.assertEqual(str(query), 'SELECT \"a\".\"c\" AS \"foo\" FROM \"t\" AS \"a\"')\n self.assertEqual(query.params, ())\n", "method_code": " def select(self, *args, **kwargs):\n return From((self,)).select(*args, **kwargs)\n ", "context": "class FromItem(object):\n def select(self, *args, **kwargs): ...\n def alias(self): ...\n def __getattr__(self, name): ...\n def __add__(self, other): ...\n def join(self, right, type_='INNER', condition=None): ...\n def lateral(self): ...\n\n __slots__ = ()\n", "repository": "duoyume/python-sql", "test_name": "test_as_select", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001481.py"} {"focal_file": "sql/__init__.py", "focal_class": "Cast", "focal_method": "cast", "tests": "import unittest\n\nclass Test_Cast_cast(unittest.TestCase):\n def test_cast(self):\n for cast in [Cast(self.column, 'int'), self.column.cast('int')]:\n self.assertEqual(str(cast), 'CAST(\"c\" AS int)')\n self.assertEqual(cast.params, ())\n", "method_code": " def cast(self, typename):\n return Cast(self, typename)\n ", "context": "class Expression(object):\n def cast(self, typename): ...\n def __str__(self): ...\n def params(self): ...\n def __and__(self, other): ...\n def __or__(self, other): ...\n def __invert__(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __mul__(self, other): ...\n def __div__(self, other): ...\n def __floordiv__(self, other): ...\n def __mod__(self, other): ...\n def __pow__(self, other): ...\n def __neg__(self): ...\n def __pos__(self): ...\n def __abs__(self): ...\n def __lshift__(self, other): ...\n def __rshift__(self, other): ...\n def __lt__(self, other): ...\n def __le__(self, other): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __gt__(self, other): ...\n def __ge__(self, other): ...\n def in_(self, values): ...\n def like(self, test): ...\n def ilike(self, test): ...\n def as_(self, output_name): ...\n def asc(self): ...\n def desc(self): ...\n\n __slots__ = ()\n __truediv__ = __div__\n __hash__ = object.__hash__\n", "repository": "duoyume/python-sql", "test_name": "test_cast", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001482.py"} {"focal_file": "sql/__init__.py", "focal_class": null, "focal_method": "delete", "tests": "import unittest\n\nclass Test_delete(unittest.TestCase):\n def test_delete1(self):\n query = self.table.delete()\n self.assertEqual(str(query), 'DELETE FROM \"t\"')\n self.assertEqual(query.params, ())\n\n def test_delete2(self):\n query = self.table.delete(where=self.table.c == 'foo')\n self.assertEqual(str(query), 'DELETE FROM \"t\" WHERE (\"c\" = %s)')\n self.assertEqual(query.params, ('foo',))\n", "method_code": " def delete(self, only=False, using=None, where=None, returning=None, with_=None):\n return Delete(self, only=only, using=using, where=where, returning=returning, with_=with_)\n ", "context": "class Table(FromItem):\n def delete(self, only=False, using=None, where=None, returning=None, with_=None): ...\n def __init__(self, name, schema=None, database=None): ...\n def __str__(self): ...\n def params(self): ...\n def insert(self, columns=None, values=None, returning=None, with_=None): ...\n def update(self, columns, values, from_=None, where=None, returning=None, with_=None): ...\n\n self._name = name\n self._schema = schema\n self._database = database\n\n __slots__ = ('_name', '_schema', '_database')\n", "repository": "duoyume/python-sql", "test_name": "test_delete1", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001483.py"} {"focal_file": "sql/__init__.py", "focal_class": "Table", "focal_method": "delete", "tests": "import unittest\n\nclass Test_Table_delete(unittest.TestCase):\n def test_delete3(self):\n t1 = Table('t1')\n t2 = Table('t2')\n query = t1.delete(where=t1.c.in_(t2.select(t2.c)))\n self.assertEqual(str(query), 'DELETE FROM \"t1\" WHERE (\"c\" IN (SELECT \"a\".\"c\" FROM \"t2\" AS \"a\"))')\n self.assertEqual(query.params, ())\n", "method_code": " def delete(self, only=False, using=None, where=None, returning=None, with_=None):\n return Delete(self, only=only, using=using, where=where, returning=returning, with_=with_)\n ", "context": "class Table(FromItem):\n def delete(self, only=False, using=None, where=None, returning=None, with_=None): ...\n def __init__(self, name, schema=None, database=None): ...\n def __str__(self): ...\n def params(self): ...\n def insert(self, columns=None, values=None, returning=None, with_=None): ...\n def update(self, columns, values, from_=None, where=None, returning=None, with_=None): ...\n\n self._name = name\n self._schema = schema\n self._database = database\n\n __slots__ = ('_name', '_schema', '_database')\n", "repository": "duoyume/python-sql", "test_name": "test_delete3", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001484.py"} {"focal_file": "sql/__init__.py", "focal_class": "Table", "focal_method": "select", "tests": "import unittest\n\nclass Test_Table_select(unittest.TestCase):\n def test_insert_subselect(self):\n t1 = Table('t1')\n t2 = Table('t2')\n subquery = t2.select(t2.c1, t2.c2)\n query = t1.insert([t1.c1, t1.c2], subquery)\n self.assertEqual(str(query), 'INSERT INTO \"t1\" (\"c1\", \"c2\") SELECT \"a\".\"c1\", \"a\".\"c2\" FROM \"t2\" AS \"a\"')\n self.assertEqual(query.params, ())\n\n def test_lateral_select(self):\n t1 = Table('t1')\n t2 = Table('t2')\n lateral = Lateral(t2.select(where=t2.id == t1.t2))\n query = From([t1, lateral]).select()\n self.assertEqual(str(query), 'SELECT * FROM \"t1\" AS \"a\", LATERAL (SELECT * FROM \"t2\" AS \"c\" WHERE (\"c\".\"id\" = \"a\".\"t2\")) AS \"b\"')\n self.assertEqual(query.params, ())\n\n def test_update_subselect(self):\n t1 = Table('t1')\n t2 = Table('t2')\n query_list = t1.update([t1.c], [t2.select(t2.c, where=t2.i == t1.i)])\n query_nolist = t1.update([t1.c], t2.select(t2.c, where=t2.i == t1.i))\n for query in [query_list, query_nolist]:\n self.assertEqual(str(query), 'UPDATE \"t1\" SET \"c\" = (SELECT \"b\".\"c\" FROM \"t2\" AS \"b\" WHERE (\"b\".\"i\" = \"t1\".\"i\"))')\n self.assertEqual(query.params, ())\n", "method_code": " def select(self, *args, **kwargs):\n return From((self,)).select(*args, **kwargs)\n ", "context": "class FromItem(object):\n def select(self, *args, **kwargs): ...\n def alias(self): ...\n def __getattr__(self, name): ...\n def __add__(self, other): ...\n def join(self, right, type_='INNER', condition=None): ...\n def lateral(self): ...\n\n __slots__ = ()\n", "repository": "duoyume/python-sql", "test_name": "test_insert_subselect", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001485.py"} {"focal_file": "sql/__init__.py", "focal_class": "AliasManager", "focal_method": "select", "tests": "import unittest\n\nclass Test_AliasManager_select(unittest.TestCase):\n def test_join_subselect(self):\n t1 = Table('t1')\n t2 = Table('t2')\n select = t2.select()\n join = Join(t1, select)\n join.condition = t1.c == select.c\n with AliasManager():\n self.assertEqual(str(join), '\"t1\" AS \"a\" INNER JOIN (SELECT * FROM \"t2\" AS \"c\") AS \"b\" ON (\"a\".\"c\" = \"b\".\"c\")')\n self.assertEqual(join.params, ())\n", "method_code": " def select(self, *args, **kwargs):\n return From((self,)).select(*args, **kwargs)\n ", "context": "class FromItem(object):\n def select(self, *args, **kwargs): ...\n def alias(self): ...\n def __getattr__(self, name): ...\n def __add__(self, other): ...\n def join(self, right, type_='INNER', condition=None): ...\n def lateral(self): ...\n\n __slots__ = ()\n", "repository": "duoyume/python-sql", "test_name": "test_join_subselect", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001486.py"} {"focal_file": "sql/__init__.py", "focal_class": "Literal", "focal_method": "update", "tests": "import unittest\n\nclass Test_Literal_update(unittest.TestCase):\n def test_update1(self):\n query = self.table.update([self.table.c], ['foo'])\n self.assertEqual(str(query), 'UPDATE \"t\" SET \"c\" = %s')\n self.assertEqual(query.params, ('foo',))\n query.where = self.table.b == Literal(True)\n self.assertEqual(str(query), 'UPDATE \"t\" SET \"c\" = %s WHERE (\"t\".\"b\" = %s)')\n self.assertEqual(query.params, ('foo', True))\n", "method_code": " def update(self, columns, values, from_=None, where=None, returning=None, with_=None):\n return Update(self, columns=columns, values=values, from_=from_, where=where, returning=returning, with_=with_)\n ", "context": "class Table(FromItem):\n def update(self, columns, values, from_=None, where=None, returning=None, with_=None): ...\n def __init__(self, name, schema=None, database=None): ...\n def __str__(self): ...\n def params(self): ...\n def insert(self, columns=None, values=None, returning=None, with_=None): ...\n def delete(self, only=False, using=None, where=None, returning=None, with_=None): ...\n\n self._name = name\n self._schema = schema\n self._database = database\n\n __slots__ = ('_name', '_schema', '_database')\n", "repository": "duoyume/python-sql", "test_name": "test_update1", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001487.py"} {"focal_file": "sql/__init__.py", "focal_class": "Table", "focal_method": "update", "tests": "import unittest\n\nclass Test_Table_update(unittest.TestCase):\n def test_update2(self):\n t1 = Table('t1')\n t2 = Table('t2')\n query = t1.update([t1.c], ['foo'], from_=[t2], where=t1.c == t2.c)\n self.assertEqual(str(query), 'UPDATE \"t1\" AS \"b\" SET \"c\" = %s FROM \"t2\" AS \"a\" WHERE (\"b\".\"c\" = \"a\".\"c\")')\n self.assertEqual(query.params, ('foo',))\n", "method_code": " def update(self, columns, values, from_=None, where=None, returning=None, with_=None):\n return Update(self, columns=columns, values=values, from_=from_, where=where, returning=returning, with_=with_)\n ", "context": "class Table(FromItem):\n def update(self, columns, values, from_=None, where=None, returning=None, with_=None): ...\n def __init__(self, name, schema=None, database=None): ...\n def __str__(self): ...\n def params(self): ...\n def insert(self, columns=None, values=None, returning=None, with_=None): ...\n def delete(self, only=False, using=None, where=None, returning=None, with_=None): ...\n\n self._name = name\n self._schema = schema\n self._database = database\n\n __slots__ = ('_name', '_schema', '_database')\n", "repository": "duoyume/python-sql", "test_name": "test_update2", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001488.py"} {"focal_file": "sql/__init__.py", "focal_class": "Values", "focal_method": "select", "tests": "import unittest\n\nclass Test_Values_select(unittest.TestCase):\n def test_select(self):\n values = Values([[1], [2], [3]])\n query = values.select()\n self.assertEqual(str(query), 'SELECT * FROM (VALUES (%s), (%s), (%s)) AS \"a\"')\n self.assertEqual(query.params, (1, 2, 3))\n", "method_code": " def select(self, *args, **kwargs):\n return From((self,)).select(*args, **kwargs)\n ", "context": "class FromItem(object):\n def select(self, *args, **kwargs): ...\n def alias(self): ...\n def __getattr__(self, name): ...\n def __add__(self, other): ...\n def join(self, right, type_='INNER', condition=None): ...\n def lateral(self): ...\n\n __slots__ = ()\n", "repository": "duoyume/python-sql", "test_name": "test_select", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001489.py"} {"focal_file": "apixu/client.py", "focal_class": "ApixuClient", "focal_method": "conditions", "tests": "import unittest\n\nclass Test_ApixuClient_conditions(unittest.TestCase):\n @staticmethod\n def test_conditions():\n client = ApixuClient()\n conditions = client.conditions()\n validate(conditions, schema.read('conditions.json'))\n", "method_code": " def conditions(self):\n url = DOC_WEATHER_CONDITIONS_URL % FORMAT\n return self._get(url)\n ", "context": "class ApixuClient():\n def conditions(self): ...\n def __init__(self, api_key=None, api_url=API_URL, lang=None): ...\n def _get(self, url, args=None): ...\n def _url(self, method): ...\n def current(self, q=None): ...\n def search(self, q=None): ...\n def forecast(self, q=None, days=None, hour=None): ...\n def history(self, q=None, since=None, until=None): ...\n\n self.api_key = api_key\n self.api_url = api_url.rstrip('/')\n self.lang = lang\n", "repository": "apixu/apixu-python", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001490.py"} {"focal_file": "apixu/client.py", "focal_class": "ApixuClient", "focal_method": "current", "tests": "import unittest\n\nclass Test_ApixuClient_current(unittest.TestCase):\n @staticmethod\n def test_current():\n api_key = os.environ['APIXUKEY']\n client = ApixuClient(api_key)\n current = client.current('London')\n validate(current, schema.read('current.json'))\n", "method_code": " def current(self, q=None):\n url = self._url('current')\n args = {}\n if q:\n args['q'] = q\n if self.lang:\n args['lang'] = self.lang\n return self._get(url, args)\n ", "context": "class ApixuClient():\n def current(self, q=None): ...\n def __init__(self, api_key=None, api_url=API_URL, lang=None): ...\n def _get(self, url, args=None): ...\n def _url(self, method): ...\n def conditions(self): ...\n def search(self, q=None): ...\n def forecast(self, q=None, days=None, hour=None): ...\n def history(self, q=None, since=None, until=None): ...\n\n self.api_key = api_key\n self.api_url = api_url.rstrip('/')\n self.lang = lang\n", "repository": "apixu/apixu-python", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001491.py"} {"focal_file": "apixu/client.py", "focal_class": "ApixuClient", "focal_method": "forecast", "tests": "import unittest\n\nclass Test_ApixuClient_forecast(unittest.TestCase):\n @staticmethod\n def test_forecast():\n api_key = os.environ['APIXUKEY']\n client = ApixuClient(api_key)\n forecast = client.forecast('London', 1, 12)\n validate(forecast, schema.read('forecast.json'))\n\n def test_forecast_no_api_key(self):\n client = ApixuClient()\n with self.assertRaises(ApixuException) as cm:\n client.forecast()\n self.assertEqual(cm.exception.code, errors.API_KEY_NOT_PROVIDED)\n", "method_code": " def forecast(self, q=None, days=None, hour=None):\n url = self._url('forecast')\n args = {}\n if q:\n args['q'] = q\n if days:\n args['days'] = days\n if hour:\n args['hour'] = hour\n if self.lang:\n args['lang'] = self.lang\n return self._get(url, args)\n ", "context": "class ApixuClient():\n def forecast(self, q=None, days=None, hour=None): ...\n def __init__(self, api_key=None, api_url=API_URL, lang=None): ...\n def _get(self, url, args=None): ...\n def _url(self, method): ...\n def conditions(self): ...\n def current(self, q=None): ...\n def search(self, q=None): ...\n def history(self, q=None, since=None, until=None): ...\n\n self.api_key = api_key\n self.api_url = api_url.rstrip('/')\n self.lang = lang\n", "repository": "apixu/apixu-python", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001492.py"} {"focal_file": "apixu/client.py", "focal_class": "ApixuClient", "focal_method": "history", "tests": "import unittest\n\nclass Test_ApixuClient_history(unittest.TestCase):\n @staticmethod\n def test_history():\n api_key = os.environ['APIXUKEY']\n client = ApixuClient(api_key)\n now = datetime.datetime.now()\n history = client.history(q='London', since=datetime.date(now.year, now.month, now.day), until=datetime.date(now.year, now.month, now.day))\n validate(history, schema.read('history.json'))\n", "method_code": " def history(self, q=None, since=None, until=None):\n url = self._url('history')\n args = {}\n if q:\n args['q'] = q\n if since:\n if not isinstance(since, datetime.date):\n raise ApixuException(message='\"since\" must be a date', code=0)\n args['dt'] = since.strftime('%Y-%m-%d')\n if until:\n if not isinstance(until, datetime.date):\n raise ApixuException(message='\"until\" must be a date', code=0)\n args['end_dt'] = until.strftime('%Y-%m-%d')\n if self.lang:\n args['lang'] = self.lang\n return self._get(url, args)\n ", "context": "class ApixuClient():\n def history(self, q=None, since=None, until=None): ...\n def __init__(self, api_key=None, api_url=API_URL, lang=None): ...\n def _get(self, url, args=None): ...\n def _url(self, method): ...\n def conditions(self): ...\n def current(self, q=None): ...\n def search(self, q=None): ...\n def forecast(self, q=None, days=None, hour=None): ...\n\n self.api_key = api_key\n self.api_url = api_url.rstrip('/')\n self.lang = lang\n", "repository": "apixu/apixu-python", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001493.py"} {"focal_file": "beantop/beanstalkd.py", "focal_class": null, "focal_method": "connect", "tests": "import unittest\n\nclass Test_connect(unittest.TestCase):\n def test_connect(self):\n self.beanstalkd.connect()\n self.assertTrue(self.telnet.openCalled)\n", "method_code": " def connect(self):\n self._conn.open(self._host, self._port)\n ", "context": "class Beanstalkd():\n def connect(self): ...\n def __init__(self, conn, host, port): ...\n def yaml_data_filtered(self, msg, fields_to_show): ...\n def yaml_data(self, msg): ...\n def _send(self, mess): ...\n def _read_line(self): ...\n\n self._conn = conn\n self._host = host\n self._port = port\n", "repository": "alexsiri7/beantop", "test_name": "test_connect", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001494.py"} {"focal_file": "beantop/beanstalkd.py", "focal_class": null, "focal_method": "yaml_data", "tests": "import unittest\n\nclass Test_yaml_data(unittest.TestCase):\n def test_yaml_data(self):\n line = self.beanstalkd.yaml_data('stats')\n self.assertEquals({'current-jobs-ready': 5, 'current-waiting': 12, 'current-workers': 4, 'pid': 1223}, line)\n", "method_code": " def yaml_data(self, msg):\n self._send(msg)\n self._read_line()\n self._read_line()\n stats = yaml.load(self._conn.read_until('\\r\\n'))\n return stats\n ", "context": "class Beanstalkd():\n def yaml_data(self, msg): ...\n def __init__(self, conn, host, port): ...\n def connect(self): ...\n def yaml_data_filtered(self, msg, fields_to_show): ...\n def _send(self, mess): ...\n def _read_line(self): ...\n\n self._conn = conn\n self._host = host\n self._port = port\n", "repository": "alexsiri7/beantop", "test_name": "test_yaml_data", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001495.py"} {"focal_file": "beantop/beanstalkd.py", "focal_class": null, "focal_method": "yaml_data_filtered", "tests": "import unittest\n\nclass Test_yaml_data_filtered(unittest.TestCase):\n def test_yaml_data_filtered(self):\n line = self.beanstalkd.yaml_data_filtered('stats', ['current-jobs-ready', 'current-waiting'])\n self.assertEquals({'current-jobs-ready': 5, 'current-waiting': 12}, line)\n", "method_code": " def yaml_data_filtered(self, msg, fields_to_show):\n stats = self.yaml_data(msg)\n ret_data = dict()\n for field in fields_to_show:\n ret_data[field] = stats[field]\n return ret_data\n ", "context": "class Beanstalkd():\n def yaml_data_filtered(self, msg, fields_to_show): ...\n def __init__(self, conn, host, port): ...\n def connect(self): ...\n def yaml_data(self, msg): ...\n def _send(self, mess): ...\n def _read_line(self): ...\n\n self._conn = conn\n self._host = host\n self._port = port\n", "repository": "alexsiri7/beantop", "test_name": "test_yaml_data_filtered", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001496.py"} {"focal_file": "beantop/beanstalkdstats.py", "focal_class": null, "focal_method": "render_screen", "tests": "import unittest\n\nclass Test_render_screen(unittest.TestCase):\n def test_renderScreen(self):\n stats = self.beanstalkdstats.render_screen()\n self.assertEquals(['current-jobs-ready: 1', 'current-waiting: 2', 'pid: 1223', 'current-workers: 3', 'Tube tube_1 tube_2 ', ' current-jobs-delayed 1 1', ' current-jobs-ready 3 3', ' current-jobs-reserved 2 2', ' current-waiting 12 12', ' current-watching 32 32'], stats)\n", "method_code": " def render_screen(self):\n status = self._fetch_global_stats()\n tube_stats = self._fetch_tube_stats()\n return status + tube_stats\n ", "context": "class BeanstalkdStats():\n def render_screen(self): ...\n def __init__(self, beanstalkd): ...\n def _fetch_global_stats(self): ...\n def _format(dic): ...\n def _fetch_tube_stats(self): ...\n def _get_filtered_tubes(self): ...\n def _get_tubes(self): ...\n def _tube_has_meaningful_info(tube): ...\n def _render_row(tubes_in_row): ...\n\n self._beanstalkd = beanstalkd\n", "repository": "alexsiri7/beantop", "test_name": "test_renderScreen", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001497.py"} {"focal_file": "beantop/charreader.py", "focal_class": null, "focal_method": "setup_terminal_for_char_read", "tests": "import unittest\n\nclass Test_setup_terminal_for_char_read(unittest.TestCase):\n def test_setup_terminal_for_char_read(self):\n self.char_reader.setup_terminal_for_char_read()\n", "method_code": " def setup_terminal_for_char_read(self):\n self._stdin_file_descriptor = self._sys.stdin.fileno()\n self._oldterm = self._termios.tcgetattr(self._stdin_file_descriptor)\n newattr = self._termios.tcgetattr(self._stdin_file_descriptor)\n newattr[3] = newattr[3] & ~self._termios.ICANON & ~self._termios.ECHO\n self._termios.tcsetattr(self._stdin_file_descriptor, self._termios.TCSANOW, newattr)\n self._oldflags = self._fcntl.fcntl(self._stdin_file_descriptor, self._fcntl.F_GETFL)\n newflags = self._oldflags | self._operative_system.O_NONBLOCK\n self._fcntl.fcntl(self._stdin_file_descriptor, self._fcntl.F_SETFL, newflags)\n ", "context": "class CharReader():\n def setup_terminal_for_char_read(self): ...\n def __init__(self, operative_system, sys, termios, fcntl): ...\n def get_char(self): ...\n def reset_terminal_options(self): ...\n\n self._operative_system = operative_system\n self._sys = sys\n self._termios = termios\n self._fcntl = fcntl\n self._stdin_file_descriptor = None\n self._oldterm = None\n self._oldflags = None\n", "repository": "alexsiri7/beantop", "test_name": "test_setup_terminal_for_char_read", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001498.py"} {"focal_file": "beantop/charreader.py", "focal_class": null, "focal_method": "reset_terminal_options", "tests": "import unittest\n\nclass Test_reset_terminal_options(unittest.TestCase):\n def test_reset_terminal_options(self):\n self.char_reader.reset_terminal_options()\n", "method_code": " def reset_terminal_options(self):\n self._termios.tcsetattr(self._stdin_file_descriptor, self._termios.TCSAFLUSH, self._oldterm)\n self._fcntl.fcntl(self._stdin_file_descriptor, self._fcntl.F_SETFL, self._oldflags)\n ", "context": "class CharReader():\n def reset_terminal_options(self): ...\n def __init__(self, operative_system, sys, termios, fcntl): ...\n def get_char(self): ...\n def setup_terminal_for_char_read(self): ...\n\n self._operative_system = operative_system\n self._sys = sys\n self._termios = termios\n self._fcntl = fcntl\n self._stdin_file_descriptor = None\n self._oldterm = None\n self._oldflags = None\n", "repository": "alexsiri7/beantop", "test_name": "test_reset_terminal_options", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001499.py"} {"focal_file": "beantop/clock.py", "focal_class": null, "focal_method": "get_printable_time", "tests": "import unittest\n\nclass Test_get_printable_time(unittest.TestCase):\n def test_get_printable_time(self):\n t = self.time.get_printable_time()\n self.assertEquals('timestring', t)\n", "method_code": " def get_printable_time(self):\n return self._time_library.strftime('%a, %d %b %Y %X', self._time_library.gmtime())\n ", "context": "class Clock():\n def get_printable_time(self): ...\n def __init__(self, time_library): ...\n def gmtime(self): ...\n def sleep(self, secs): ...\n\n self._time_library = time_library\n", "repository": "alexsiri7/beantop", "test_name": "test_get_printable_time", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001500.py"} {"focal_file": "beantop/clock.py", "focal_class": null, "focal_method": "gmtime", "tests": "import unittest\n\nclass Test_gmtime(unittest.TestCase):\n def test_gmtime(self):\n t = self.time.gmtime()\n self.assertEquals(1234, t)\n", "method_code": " def gmtime(self):\n return self._time_library.time()\n ", "context": "class Clock():\n def gmtime(self): ...\n def __init__(self, time_library): ...\n def sleep(self, secs): ...\n def get_printable_time(self): ...\n\n self._time_library = time_library\n", "repository": "alexsiri7/beantop", "test_name": "test_gmtime", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001501.py"} {"focal_file": "beantop/clock.py", "focal_class": null, "focal_method": "sleep", "tests": "import unittest\n\nclass Test_sleep(unittest.TestCase):\n def test_sleep(self):\n self.time.sleep(10)\n self.assertTrue(10, self.mock_time.sleepSecs)\n", "method_code": " def sleep(self, secs):\n return self._time_library.sleep(secs)\n ", "context": "class Clock():\n def sleep(self, secs): ...\n def __init__(self, time_library): ...\n def gmtime(self): ...\n def get_printable_time(self): ...\n\n self._time_library = time_library\n", "repository": "alexsiri7/beantop", "test_name": "test_sleep", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001502.py"} {"focal_file": "beantop/console.py", "focal_class": null, "focal_method": "main_loop", "tests": "import unittest\n\nclass Test_main_loop(unittest.TestCase):\n def test_mainloop(self):\n self.char_reader.put_char(list('asdfr') + [None] * 10 + list('ffasq'))\n self.console.main_loop()\n self.assertEquals(11, self.time.totalsleep)\n self.assertEquals(3, self.screen.printcalls)\n", "method_code": " def main_loop(self):\n try:\n self._char_reader.setup_terminal_for_char_read()\n while not self._finished:\n self._run_loop_once()\n finally:\n self._char_reader.reset_terminal_options()\n ", "context": "class Console():\n def main_loop(self): ...\n def __init__(self, time, char_reader, screen_printer, screen): ...\n def _run_loop_once(self): ...\n def _process_char(self): ...\n def _process_char_queue(self): ...\n\n self._time = time\n self._char_reader = char_reader\n self._screen_printer = screen_printer\n self._screen = screen\n self._finished = False\n", "repository": "alexsiri7/beantop", "test_name": "test_mainloop", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001503.py"} {"focal_file": "beantop/factory.py", "focal_class": null, "focal_method": "create_arguments_parser", "tests": "import unittest\n\nclass Test_create_arguments_parser(unittest.TestCase):\n def test_create_arguments_parser(self):\n create_arguments_parser()\n", "method_code": "def create_arguments_parser():\n return Arguments(sys, getopt)", "context": "def create_arguments_parser(): ...\ndef create_arguments_parser(): ...\ndef start_application(host, port): ...\n", "repository": "alexsiri7/beantop", "test_name": "test_create_arguments_parser", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001504.py"} {"focal_file": "beantop/factory.py", "focal_class": null, "focal_method": "start_application", "tests": "import unittest\n\nclass Test_start_application(unittest.TestCase):\n def test_start_application(self):\n start_application('', '')\n", "method_code": "def start_application(host, port):\n telnet = telnetlib.Telnet()\n beanstalkd = Beanstalkd(telnet, host, port)\n stats = BeanstalkdStats(beanstalkd)\n char_reader = CharReader(os, sys, termios, fcntl)\n screen_printer = ScreenPrinter(os, sys)\n console = Console(Clock(time), char_reader, screen_printer, stats)\n return (beanstalkd, console)", "context": "def start_application(host, port): ...\ndef create_arguments_parser(): ...\ndef start_application(host, port): ...\n", "repository": "alexsiri7/beantop", "test_name": "test_start_application", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001505.py"} {"focal_file": "beantop/screenprinter.py", "focal_class": null, "focal_method": "print_lines", "tests": "import unittest\n\nclass Test_print_lines(unittest.TestCase):\n def test_print_lines(self):\n lines = ['a', 'b']\n self.screen_printer.print_lines(lines)\n self.file.write.assert_has_calls([call('a\\n'), call('b\\n')])\n", "method_code": " def print_lines(self, lines):\n for line in lines:\n self._sys.stdout.write(line + '\\n')\n ", "context": "class ScreenPrinter():\n def print_lines(self, lines): ...\n def __init__(self, operative_system, sys): ...\n def clear(self): ...\n\n self._operative_system = operative_system\n self._sys = sys\n", "repository": "alexsiri7/beantop", "test_name": "test_print_lines", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001506.py"} {"focal_file": "beantop/screenprinter.py", "focal_class": null, "focal_method": "clear", "tests": "import unittest\n\nclass Test_clear(unittest.TestCase):\n def test_clear(self):\n self.screen_printer.clear()\n self.assertTrue(self.os.wasClearCalled)\n self.os.clear.assert_called()\n", "method_code": " def clear(self):\n self._operative_system.system('clear')\n ", "context": "class ScreenPrinter():\n def clear(self): ...\n def __init__(self, operative_system, sys): ...\n def print_lines(self, lines): ...\n\n self._operative_system = operative_system\n self._sys = sys\n", "repository": "alexsiri7/beantop", "test_name": "test_clear", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001507.py"} {"focal_file": "server/foodlab_serve/lib/python3.6/site-packages/psycopg2/tests/dbapi20.py", "focal_class": null, "focal_method": "_connect", "tests": "import unittest\n\nclass Test_connect(unittest.TestCase):\n def test_connect(self):\n con = self._connect()\n con.close()\n", "method_code": " def _connect(self):\n try:\n return self.driver.connect(*self.connect_args, **self.connect_kw_args)\n except AttributeError:\n self.fail('No connect method found in self.driver module')\n ", "context": "class DatabaseAPI20Test(unittest.TestCase):\n def _connect(self): ...\n def executeDDL1(self, cursor): ...\n def executeDDL2(self, cursor): ...\n def setUp(self): ...\n def tearDown(self): ...\n def test_connect(self): ...\n def test_apilevel(self): ...\n def test_threadsafety(self): ...\n def test_paramstyle(self): ...\n def test_Exceptions(self): ...\n def test_ExceptionsAsConnectionAttributes(self): ...\n def test_commit(self): ...\n def test_rollback(self): ...\n def test_cursor(self): ...\n def test_cursor_isolation(self): ...\n def test_description(self): ...\n def test_rowcount(self): ...\n def test_callproc(self): ...\n def test_close(self): ...\n def test_execute(self): ...\n def _paraminsert(self, cur): ...\n def test_executemany(self): ...\n def test_fetchone(self): ...\n def _populate(self): ...\n def test_fetchmany(self): ...\n def test_fetchall(self): ...\n def test_mixedfetch(self): ...\n def help_nextset_setUp(self, cur): ...\n def help_nextset_tearDown(self, cur): ...\n def test_nextset(self): ...\n def test_nextset(self): ...\n def test_arraysize(self): ...\n def test_setinputsizes(self): ...\n def test_setoutputsize_basic(self): ...\n def test_setoutputsize(self): ...\n def test_None(self): ...\n def test_Date(self): ...\n def test_Time(self): ...\n def test_Timestamp(self): ...\n def test_Binary(self): ...\n def test_STRING(self): ...\n def test_BINARY(self): ...\n def test_NUMBER(self): ...\n def test_DATETIME(self): ...\n def test_ROWID(self): ...\n\n driver = None\n connect_args = ()\n connect_kw_args = {}\n table_prefix = 'dbapi20test_'\n ddl1 = 'create table %sbooze (name varchar(20))' % table_prefix\n ddl2 = 'create table %sbarflys (name varchar(20))' % table_prefix\n xddl1 = 'drop table %sbooze' % table_prefix\n xddl2 = 'drop table %sbarflys' % table_prefix\n lowerfunc = 'lower'\n lower_func = 'lower'\n samples = ['Carlton Cold', 'Carlton Draft', 'Mountain Goat', 'Redback', 'Victoria Bitter', 'XXXX']\n", "repository": "ranyishere/Food-Lab", "test_name": "test_connect", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001508.py"} {"focal_file": "server/foodlab_serve/lib/python3.6/site-packages/psycopg2/tests/dbapi20.py", "focal_class": null, "focal_method": "help_nextset_setUp", "tests": "import unittest\n\nclass Test_help_nextset_setUp(unittest.TestCase):\n def test_nextset(self):\n con = self._connect()\n try:\n cur = con.cursor()\n if not hasattr(cur, 'nextset'):\n return\n try:\n self.executeDDL1(cur)\n sql = self._populate()\n for sql in self._populate():\n cur.execute(sql)\n self.help_nextset_setUp(cur)\n cur.callproc('deleteme')\n numberofrows = cur.fetchone()\n assert numberofrows[0] == len(self.samples)\n assert cur.nextset()\n names = cur.fetchall()\n assert len(names) == len(self.samples)\n s = cur.nextset()\n assert s == None, 'No more return sets, should return None'\n finally:\n self.help_nextset_tearDown(cur)\n finally:\n con.close()\n", "method_code": " def help_nextset_setUp(self, cur):\n \"\"\" Should create a procedure called deleteme\n that returns two result sets, first the \n \t number of rows in booze then \"name from booze\"\n \"\"\"\n raise NotImplementedError('Helper not implemented')\n ", "context": "class DatabaseAPI20Test(unittest.TestCase):\n def help_nextset_setUp(self, cur): ...\n def executeDDL1(self, cursor): ...\n def executeDDL2(self, cursor): ...\n def setUp(self): ...\n def tearDown(self): ...\n def _connect(self): ...\n def test_connect(self): ...\n def test_apilevel(self): ...\n def test_threadsafety(self): ...\n def test_paramstyle(self): ...\n def test_Exceptions(self): ...\n def test_ExceptionsAsConnectionAttributes(self): ...\n def test_commit(self): ...\n def test_rollback(self): ...\n def test_cursor(self): ...\n def test_cursor_isolation(self): ...\n def test_description(self): ...\n def test_rowcount(self): ...\n def test_callproc(self): ...\n def test_close(self): ...\n def test_execute(self): ...\n def _paraminsert(self, cur): ...\n def test_executemany(self): ...\n def test_fetchone(self): ...\n def _populate(self): ...\n def test_fetchmany(self): ...\n def test_fetchall(self): ...\n def test_mixedfetch(self): ...\n def help_nextset_tearDown(self, cur): ...\n def test_nextset(self): ...\n def test_nextset(self): ...\n def test_arraysize(self): ...\n def test_setinputsizes(self): ...\n def test_setoutputsize_basic(self): ...\n def test_setoutputsize(self): ...\n def test_None(self): ...\n def test_Date(self): ...\n def test_Time(self): ...\n def test_Timestamp(self): ...\n def test_Binary(self): ...\n def test_STRING(self): ...\n def test_BINARY(self): ...\n def test_NUMBER(self): ...\n def test_DATETIME(self): ...\n def test_ROWID(self): ...\n\n driver = None\n connect_args = ()\n connect_kw_args = {}\n table_prefix = 'dbapi20test_'\n ddl1 = 'create table %sbooze (name varchar(20))' % table_prefix\n ddl2 = 'create table %sbarflys (name varchar(20))' % table_prefix\n xddl1 = 'drop table %sbooze' % table_prefix\n xddl2 = 'drop table %sbarflys' % table_prefix\n lowerfunc = 'lower'\n lower_func = 'lower'\n samples = ['Carlton Cold', 'Carlton Draft', 'Mountain Goat', 'Redback', 'Victoria Bitter', 'XXXX']\n", "repository": "ranyishere/Food-Lab", "test_name": "test_nextset", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001509.py"} {"focal_file": "board.py", "focal_class": null, "focal_method": "check_end_condition", "tests": "import unittest\n\nclass Test_check_end_condition(unittest.TestCase):\n def test_end_condition_over(self):\n self.assertFalse(self.b.true_history.has_key('game_result'))\n self.b.players['Tom'].gold = 13\n self.b.check_end_condition()\n self.assertTrue(self.b.true_history.has_key('game_result'))\n game_result = OrderedDict([('type_of_end', 'rich_win'), ('name', 'Tom'), ('gold', 13), ('info', None)])\n self.assertEqual(self.b.true_history['game_result'], game_result)\n\n def test_end_condition_under(self):\n self.assertFalse(self.b.true_history.has_key('game_result'))\n self.b.players['Tom'].gold = 0\n self.b.check_end_condition()\n self.assertTrue(self.b.true_history.has_key('game_result'))\n game_result = OrderedDict([('type_of_end', 'poor_win'), ('name', 'Ben'), ('gold', 6), ('info', None)])\n self.assertEqual(self.b.true_history['game_result'], game_result)\n", "method_code": " def check_end_condition(self, cheat_player=None):\n if cheat_player != None:\n if cheat_player.gold >= 10:\n result = OrderedDict([('type_of_end', 'rich_win'), ('name', cheat_player.name), ('gold', cheat_player.gold), ('info', 'cheat_win')])\n self.true_history.update([('game_result', result)])\n return\n richest = self.max_rich_player()\n poorest = self.min_rich_player()\n if richest[0].val >= 13:\n result = OrderedDict([('type_of_end', 'rich_win'), ('name', richest[0].name), ('gold', richest[0].val), ('info', None)])\n self.true_history.update([('game_result', result)])\n return\n if poorest[0].val <= 0:\n result = OrderedDict([('type_of_end', 'poor_win'), ('name', richest[0].name), ('gold', richest[0].val), ('info', None)])\n self.true_history.update([('game_result', result)])\n return\n ", "context": "class Board(object):\n def check_end_condition(self, cheat_player=None): ...\n def __init__(self, players_num, types_of_players, players_names, cards_names, start_gold): ...\n def public_board_update(self): ...\n def reshufle_cards(self): ...\n def next_step(self): ...\n def announcement(self): ...\n def next_player(self): ...\n def method_from_players(self, method, players=None): ...\n def max_rich_player(self, all_players=False): ...\n def min_rich_player(self, all_players=False): ...\n\n self.players_num = players_num\n self.types_of_players = types_of_players\n self.players_names = players_names\n self.cards_names = cards_names\n self.players = OrderedDict()\n self.current_player = self.players.items()[0][1]\n self.court = 0\n self.round_num = 0\n self.public_history = GameHistory({})\n self.true_history = GameHistory({})\n self.public_board = PublicBoard(self.method_from_players('gold'), self.public_history)\n", "repository": "pirtim/mascarade_table", "test_name": "test_end_condition_over", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001510.py"} {"focal_file": "board.py", "focal_class": null, "focal_method": "max_rich_player", "tests": "import unittest\n\nclass Test_max_rich_player(unittest.TestCase):\n def test_max_rich_player1(self):\n result = self.b.max_rich_player()\n self.assertIsInstance(result, list)\n self.assertEqual(len(result), 3)\n\n def test_max_rich_player2(self):\n self.b.players['Tom'].gold += 1\n result = self.b.max_rich_player()\n self.assertIsInstance(result, list)\n self.assertListEqual(result, [('Tom', 7)])\n self.assertEqual(len(result), 1)\n", "method_code": " def max_rich_player(self, all_players=False):\n \"\"\"Returns list(tuple(richest_player1, his_gold),tuple(richest_player2, his_gold),...)\"\"\"\n gold = self.method_from_players('gold')\n gold_sorted = sorted(gold.iteritems_p(), key=lambda x: -x.val)\n if all_players:\n return gold_sorted\n else:\n return filter(lambda x: x.val == gold_sorted[0].val, gold_sorted)\n ", "context": "class Board(object):\n def max_rich_player(self, all_players=False): ...\n def __init__(self, players_num, types_of_players, players_names, cards_names, start_gold): ...\n def public_board_update(self): ...\n def reshufle_cards(self): ...\n def next_step(self): ...\n def announcement(self): ...\n def next_player(self): ...\n def method_from_players(self, method, players=None): ...\n def check_end_condition(self, cheat_player=None): ...\n def min_rich_player(self, all_players=False): ...\n\n self.players_num = players_num\n self.types_of_players = types_of_players\n self.players_names = players_names\n self.cards_names = cards_names\n self.players = OrderedDict()\n self.current_player = self.players.items()[0][1]\n self.court = 0\n self.round_num = 0\n self.public_history = GameHistory({})\n self.true_history = GameHistory({})\n self.public_board = PublicBoard(self.method_from_players('gold'), self.public_history)\n", "repository": "pirtim/mascarade_table", "test_name": "test_max_rich_player1", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001511.py"} {"focal_file": "board.py", "focal_class": null, "focal_method": "min_rich_player", "tests": "import unittest\n\nclass Test_min_rich_player(unittest.TestCase):\n def test_min_rich_player(self):\n result = self.b.min_rich_player()\n self.assertIsInstance(result, list)\n self.assertEqual(len(result), 3)\n\n def test_min_rich_player2(self):\n self.b.players['Tom'].gold += 1\n result = self.b.min_rich_player()\n self.assertIsInstance(result, list)\n self.assertListEqual(result, [('Ben', 6), ('Mat', 6)])\n self.assertEqual(len(result), 2)\n", "method_code": " def min_rich_player(self, all_players=False):\n \"\"\"Returns list(tuple(poorest_player1, his_gold),tuple(poorest_player2, his_gold),...)\"\"\"\n gold = self.method_from_players('gold')\n gold_sorted = sorted(gold.iteritems_p(), key=lambda x: +x.val)\n if all_players:\n return gold_sorted\n else:\n return filter(lambda x: x.val == gold_sorted[0].val, gold_sorted)\n ", "context": "class Board(object):\n def min_rich_player(self, all_players=False): ...\n def __init__(self, players_num, types_of_players, players_names, cards_names, start_gold): ...\n def public_board_update(self): ...\n def reshufle_cards(self): ...\n def next_step(self): ...\n def announcement(self): ...\n def next_player(self): ...\n def method_from_players(self, method, players=None): ...\n def check_end_condition(self, cheat_player=None): ...\n def max_rich_player(self, all_players=False): ...\n\n self.players_num = players_num\n self.types_of_players = types_of_players\n self.players_names = players_names\n self.cards_names = cards_names\n self.players = OrderedDict()\n self.current_player = self.players.items()[0][1]\n self.court = 0\n self.round_num = 0\n self.public_history = GameHistory({})\n self.true_history = GameHistory({})\n self.public_board = PublicBoard(self.method_from_players('gold'), self.public_history)\n", "repository": "pirtim/mascarade_table", "test_name": "test_min_rich_player", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001512.py"} {"focal_file": "py_skiplist/iterators.py", "focal_class": null, "focal_method": "geometric", "tests": "import unittest\n\nclass Test_geometric(unittest.TestCase):\n def test_geometric(self):\n p = 0.5\n g = geometric(p)\n expected = [p ** i for i in range(1, 5)]\n sample = [next(g) for _ in range(10000)]\n actual = [float(sum((1 for n in sample if n == t))) / len(sample) for t in range(10)]\n self.assertAlmostEqual(1, sum((i for i in actual)), delta=0.01)\n self.assertAlmostEqual(0, sum((i - j for i, j in zip(expected, actual))), delta=0.01)\n", "method_code": "def geometric(p):\n return (next(dropwhile(lambda _: random.randint(1, int(1.0 / p)) == 1, count())) for _ in repeat(1))", "context": "def geometric(p): ...\ndef geometric(p): ...\n", "repository": "ZhukovAlexander/py-skiplist", "test_name": "test_geometric", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001513.py"} {"focal_file": "flask_rest_toolkit/auth.py", "focal_class": "And", "focal_method": "authenticate", "tests": "import unittest\n\nclass Test_And_authenticate(unittest.TestCase):\n def test_valid_authentication(self):\n is_valid_mock = mock.MagicMock(return_value=True)\n builder = EnvironBuilder()\n request = Request(builder.get_environ())\n request.authorization = {'username': 'john', 'password': 'xxx'}\n dummy = DummyAuthentication(valid_auth=True)\n dummy_auth_mock = mock.MagicMock(return_value=True)\n dummy.authenticate = dummy_auth_mock\n auth = And(BasicAuth(is_valid_user=is_valid_mock), dummy)\n result = auth.authenticate(request)\n self.assertEqual(result, None)\n is_valid_mock.assert_called_once_with('john', 'xxx')\n dummy_auth_mock.assert_called_once_with(request)\n", "method_code": " def authenticate(self, request):\n raise NotImplementedError()\n ", "context": "class AuthenticationStrategy(object):\n def authenticate(self, request): ...\n def authorize(self, request): ...\n", "repository": "santiagobasulto/flask-rest-toolkit", "test_name": "test_valid_authentication", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001514.py"} {"focal_file": "i2plib/utils.py", "focal_class": null, "focal_method": "get_sam_address", "tests": "import unittest\n\nclass Test_get_sam_address(unittest.TestCase):\n def test_sam_address_getter(self):\n oldenv = os.environ\n if 'I2P_SAM_ADDRESS' in os.environ:\n del os.environ['I2P_SAM_ADDRESS']\n a = i2plib.utils.get_sam_address()\n self.assertEqual(a, i2plib.sam.DEFAULT_ADDRESS)\n os.environ['I2P_SAM_ADDRESS'] = '127.0.0.1:11223'\n a = i2plib.utils.get_sam_address()\n self.assertEqual(a, ('127.0.0.1', 11223))\n os.environ = oldenv\n", "method_code": "def get_sam_address():\n \"\"\"\n Get SAM address from environment variable I2P_SAM_ADDRESS, or use a default\n value\n \"\"\"\n value = os.getenv('I2P_SAM_ADDRESS')\n return address_from_string(value) if value else i2plib.sam.DEFAULT_ADDRESS", "context": "def get_sam_address(): ...\ndef get_free_port(): ...\ndef is_address_accessible(address): ...\ndef address_from_string(address_string): ...\ndef get_sam_address(): ...\ndef generate_session_id(length=6): ...\n", "repository": "l-n-s/i2plib", "test_name": "test_sam_address_getter", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001515.py"} {"focal_file": "common/data_manager/cache.py", "focal_class": null, "focal_method": "bulk_get", "tests": "import unittest\n\nclass Test_bulk_get(unittest.TestCase):\n def test_bulk_get(self):\n \"\"\" Tests that we can use the bulk_get method to load a bunch of data from\n the cache at once. \"\"\"\n image_pairs = set()\n for i, image in enumerate(self.__images):\n name = 'image%d' % i\n self.__cache.add(image, name, 'synset1')\n image_pairs.add(('synset1', name))\n bad_name = 'image%d' % len(self.__images)\n bad_id = utils.make_img_id('synset1', bad_name)\n image_pairs.add(('synset1', bad_name))\n loaded, not_found = self.__cache.bulk_get(image_pairs)\n for i, image in enumerate(self.__images):\n name = 'image%d' % i\n img_id = utils.make_img_id('synset1', name)\n self.assertIn(img_id, loaded)\n got_image = loaded[img_id]\n self.assertTrue(np.array_equal(image, got_image))\n self.assertEqual(1, len(not_found))\n self.assertEqual(bad_id, not_found[0])\n", "method_code": " def bulk_get(self, image_pairs):\n \"\"\" Gets a large number of images from the cache at once.\n For a large batch of images, this can be a lot faster than running get\n individually.\n Args:\n image_pairs: Set of (synset, name) pairs for each image to load.\n Returns:\n A dictionary mapping the unique IDs of loaded images to the actual image\n data, and a list of the unique IDs of images that were not found. \"\"\"\n \n def compare_offsets(image1_pair, image2_pair):\n \"\"\" Compares the offsets of two images in the file.\n Args:\n image1_pair: The (label, name) pair of the first image.\n image2_pair: The (label, name) pair of the second image.\n Returns:\n True if image1 has a smaller offset than image2, False otherwise. \"\"\"\n label1, name1 = image1_pair\n label2, name2 = image2_pair\n offset1, _ = self.__labels[label1][name1]\n offset2, _ = self.__labels[label2][name2]\n return offset1 < offset2\n self.__data_file.flush()\n not_found = []\n to_remove = []\n for label, name in image_pairs:\n img_id = utils.make_img_id(label, name)\n if not self.is_in_cache(label, name):\n not_found.append(img_id)\n to_remove.append((label, name))\n for pair in to_remove:\n image_pairs.remove(pair)\n sorted_pairs = sorted(image_pairs, cmp=compare_offsets)\n loaded = {}\n for label, name in sorted_pairs:\n image = self.__do_get(label, name)\n assert image is not None\n img_id = utils.make_img_id(label, name)\n loaded[img_id] = image\n return (loaded, not_found)\n ", "context": "class DiskCache(Cache):\n def bulk_get(self, image_pairs): ...\n def __init__(self, location, max_size=None, extension='.jpg'): ...\n def __del__(self): ...\n def __update_free_counter(self): ...\n def __add_image_data(self, size): ...\n def __remove_image_data(self, size): ...\n def __load_existing_cache(self): ...\n def __maintain_size(self): ...\n def evict_next_image(self): ...\n def __add_label(self, name): ...\n def add(self, image, name, label): ...\n def __do_get(self, label, name): ...\n def is_in_cache(self, label, name): ...\n def get(self, synset, name): ...\n def get_sequential(self, start_label, start_name, number_of_images, use_only=None): ...\n def get_first_in_cache(self, use_only=None): ...\n def get_cache_size(self): ...\n\n self.__extension = extension\n self.__total_cache_size = 0\n self.__total_space_used = 0\n self.__max_size = max_size\n self.__location = location\n self.__labels = {}\n self.__offsets = {}\n self.__free_start = 0\n self.__free_end = 0\n", "repository": "djpetti/rpinets", "test_name": "test_bulk_get", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001516.py"} {"focal_file": "common/data_manager/cache.py", "focal_class": null, "focal_method": "get_sequential", "tests": "import unittest\n\nclass Test_get_sequential(unittest.TestCase):\n def test_get_sequential(self):\n \"\"\" Tests that we can use the get_sequential method to load a bunch of\n contiguous data from the cache. \"\"\"\n for i, image in enumerate(self.__images):\n name = 'image%d' % i\n self.__cache.add(image, name, 'synset1')\n loaded, new = self.__cache.get_sequential('synset1', 'image0', len(self.__images))\n self.assertEqual(None, new)\n for i, image in enumerate(self.__images):\n name = 'image%d' % i\n img_id = utils.make_img_id('synset1', name)\n self.assertIn(img_id, loaded)\n got_image = loaded[img_id]\n self.assertTrue(np.array_equal(image, got_image))\n\n def test_sequential_use_only(self):\n \"\"\" Tests that get_sequential works when we give it a set of the images it\n can use. \"\"\"\n use_only = set()\n for i, image in enumerate(self.__images):\n name = 'image%d' % i\n use_only.add(utils.make_img_id('synset1', name))\n self.__cache.add(image, name, 'synset1')\n use_only.remove(utils.make_img_id('synset1', 'image0'))\n loaded, _ = self.__cache.get_sequential('synset1', 'image0', len(self.__images), use_only=use_only)\n for i, image in enumerate(self.__images[1:]):\n name = 'image%d' % (i + 1)\n img_id = utils.make_img_id('synset1', name)\n self.assertIn(img_id, loaded)\n got_image = loaded[img_id]\n self.assertTrue(np.array_equal(image, got_image))\n self.assertNotIn('synset1_image0', loaded)\n", "method_code": " def get_sequential(self, start_label, start_name, number_of_images, use_only=None):\n \"\"\" Gets a number of images that are stored sequentially in the cache. This\n is the fastest way to load a large number of images from the cache.\n Args:\n start_label: The label of the image to start form.\n start_name: The name of the image to start from.\n number_of_images: Total number of images to load, including the start one.\n use_only: Specifies a set of images. If a loaded image is not in that set,\n it will not be included. Images are specified by image ID.\n Returns:\n A dictionary mapping unique IDs of loaded images to the actual image data.\n It may not contain all the images requested, if there is not sufficient\n data in the cache. It will also return None if the first image is not in\n the cache. Furthermore, it returns the image ID to start at if loading the\n sequential batch directly after this one. This will be None if it hits the\n end of the cache. \"\"\"\n if not self.is_in_cache(start_label, start_name):\n return None\n self.__data_file.flush()\n images = {}\n cache_data_location = os.path.join(self.__location, 'cache_data.dat')\n total_size = os.path.getsize(cache_data_location)\n start_offset, size = self.__labels[start_label][start_name]\n end_offset = start_offset\n num_loaded = 0\n to_load = []\n num_rejected = 0\n while num_loaded < number_of_images + 1 and end_offset < total_size:\n if end_offset not in self.__offsets:\n raise RuntimeError('Unexpected free space in cache. Please repair the cache.')\n img_id = self.__offsets[end_offset]\n label, name = utils.split_img_id(img_id)\n end_offset, size = self.__labels[label][name]\n old_end_offset = end_offset\n end_offset = end_offset + size\n if end_offset == self.__free_start:\n end_offset = self.__free_end\n elif end_offset > self.__free_start and end_offset < self.__free_end:\n raise RuntimeError('Data overlaps free space in cache. Please repair the cache.')\n to_load.append((img_id, end_offset - old_end_offset))\n if use_only == None or img_id in use_only:\n num_loaded += 1\n else:\n num_rejected += 1\n if num_rejected > number_of_images:\n logger.debug('Got too many bad images, giving up.')\n break\n next_image = None\n if num_loaded > number_of_images:\n next_image, _ = to_load.pop()\n logger.debug('First image of next sequential batch: %s' % next_image)\n logger.debug('Reading file from %d to %d.' % (start_offset, end_offset))\n self.__data_file.seek(start_offset)\n raw_data = self.__data_file.read(end_offset - start_offset)\n raw_data = np.asarray(bytearray(raw_data), dtype=np.uint8)\n for img_id, size in to_load:\n if use_only == None or img_id in use_only:\n image = cv2.imdecode(raw_data, cv2.IMREAD_COLOR)\n images[img_id] = image\n else:\n logger.debug('Skipping image: %s' % img_id)\n raw_data = raw_data[size:]\n return (images, next_image)\n ", "context": "class DiskCache(Cache):\n def get_sequential(self, start_label, start_name, number_of_images, use_only=None): ...\n def __init__(self, location, max_size=None, extension='.jpg'): ...\n def __del__(self): ...\n def __update_free_counter(self): ...\n def __add_image_data(self, size): ...\n def __remove_image_data(self, size): ...\n def __load_existing_cache(self): ...\n def __maintain_size(self): ...\n def evict_next_image(self): ...\n def __add_label(self, name): ...\n def add(self, image, name, label): ...\n def __do_get(self, label, name): ...\n def is_in_cache(self, label, name): ...\n def get(self, synset, name): ...\n def bulk_get(self, image_pairs): ...\n def get_first_in_cache(self, use_only=None): ...\n def get_cache_size(self): ...\n\n self.__extension = extension\n self.__total_cache_size = 0\n self.__total_space_used = 0\n self.__max_size = max_size\n self.__location = location\n self.__labels = {}\n self.__offsets = {}\n self.__free_start = 0\n self.__free_end = 0\n", "repository": "djpetti/rpinets", "test_name": "test_get_sequential", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001517.py"} {"focal_file": "pytz/tzinfo.py", "focal_class": null, "focal_method": "localize", "tests": "import unittest\n\nclass Test_localize(unittest.TestCase):\n def testLocalize(self):\n loc_tz = pytz.timezone('Europe/Amsterdam')\n loc_time = loc_tz.localize(datetime(1930, 5, 10, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'AMT+0020')\n loc_time = loc_tz.localize(datetime(1930, 5, 20, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'NST+0120')\n loc_time = loc_tz.localize(datetime(1940, 5, 10, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'NET+0020')\n loc_time = loc_tz.localize(datetime(1940, 5, 20, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CEST+0200')\n loc_time = loc_tz.localize(datetime(2004, 2, 1, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CET+0100')\n loc_time = loc_tz.localize(datetime(2004, 4, 1, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CEST+0200')\n tz = pytz.timezone('Europe/Amsterdam')\n loc_time = loc_tz.localize(datetime(1943, 3, 29, 1, 59, 59))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CET+0100')\n loc_tz = pytz.timezone('US/Eastern')\n loc_time = loc_tz.localize(datetime(1918, 10, 27, 1, 59, 59), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EDT-0400')\n loc_time = loc_tz.localize(datetime(1918, 10, 27, 1, 59, 59), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n self.assertRaises(pytz.AmbiguousTimeError, loc_tz.localize, datetime(1918, 10, 27, 1, 59, 59), is_dst=None)\n loc_time = loc_tz.localize(datetime(1918, 3, 31, 2, 0, 0), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n loc_time = loc_tz.localize(datetime(1918, 3, 31, 2, 0, 0), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EDT-0400')\n self.assertRaises(pytz.NonExistentTimeError, loc_tz.localize, datetime(1918, 3, 31, 2, 0, 0), is_dst=None)\n loc_time = loc_tz.localize(datetime(1942, 2, 9, 3, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'EWT-0400')\n loc_time = loc_tz.localize(datetime(1945, 8, 14, 19, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'EPT-0400')\n loc_time = loc_tz.localize(datetime(1945, 9, 30, 1, 0, 0), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EPT-0400')\n loc_time = loc_tz.localize(datetime(1945, 9, 30, 1, 0, 0), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n for zonename, ambiguous_naive, expected in [('Europe/Warsaw', datetime(1915, 8, 4, 23, 59, 59), ['1915-08-04 23:59:59 WMT+0124', '1915-08-04 23:59:59 CET+0100']), ('Europe/Moscow', datetime(2014, 10, 26, 1, 30), ['2014-10-26 01:30:00 MSK+0400', '2014-10-26 01:30:00 MSK+0300'])]:\n loc_tz = pytz.timezone(zonename)\n self.assertRaises(pytz.AmbiguousTimeError, loc_tz.localize, ambiguous_naive, is_dst=None)\n for dst in [True, timedelta(1), False, timedelta(0)]:\n loc_time = loc_tz.localize(ambiguous_naive, is_dst=dst)\n self.assertEqual(loc_time.strftime(fmt), expected[not dst])\n", "method_code": " def localize(self, dt, is_dst=False):\n \"\"\"Convert naive time to local time\"\"\"\n if dt.tzinfo is not None:\n raise ValueError('Not naive datetime (tzinfo is already set)')\n return dt.replace(tzinfo=self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def localize(self, dt, is_dst=False): ...\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "varunarya10/pytz_2015_4", "test_name": "testLocalize", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001518.py"} {"focal_file": "pytz/tzinfo.py", "focal_class": null, "focal_method": "normalize", "tests": "import unittest\n\nclass Test_normalize(unittest.TestCase):\n def testNormalize(self):\n tz = pytz.timezone('US/Eastern')\n dt = datetime(2004, 4, 4, 7, 0, 0, tzinfo=UTC).astimezone(tz)\n dt2 = dt - timedelta(minutes=10)\n self.assertEqual(dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'), '2004-04-04 02:50:00 EDT-0400')\n dt2 = tz.normalize(dt2)\n self.assertEqual(dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'), '2004-04-04 01:50:00 EST-0500')\n\n def test_normalize(self):\n other_tz = pytz.timezone('Europe/Paris')\n self.assertTrue(self.tz is not other_tz)\n dt = datetime(2012, 3, 26, 12, 0)\n other_dt = other_tz.localize(dt)\n local_dt = self.tz.normalize(other_dt)\n self.assertTrue(local_dt.tzinfo is not other_dt.tzinfo)\n self.assertNotEqual(local_dt.replace(tzinfo=None), other_dt.replace(tzinfo=None))\n", "method_code": " def normalize(self, dt, is_dst=False):\n \"\"\"Correct the timezone information on the given datetime.\n \n This is normally a no-op, as StaticTzInfo timezones never have\n ambiguous cases to correct:\n \n >>> from pytz import timezone\n >>> gmt = timezone('GMT')\n >>> isinstance(gmt, StaticTzInfo)\n True\n >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt)\n >>> gmt.normalize(dt) is dt\n True\n \n The supported method of converting between timezones is to use\n datetime.astimezone(). Currently normalize() also works:\n \n >>> la = timezone('America/Los_Angeles')\n >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3))\n >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'\n >>> gmt.normalize(dt).strftime(fmt)\n '2011-05-07 08:02:03 GMT (+0000)'\n \"\"\"\n if dt.tzinfo is self:\n return dt\n if dt.tzinfo is None:\n raise ValueError('Naive time - no tzinfo set')\n return dt.astimezone(self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def normalize(self, dt, is_dst=False): ...\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def localize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "varunarya10/pytz_2015_4", "test_name": "testNormalize", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001519.py"} {"focal_file": "pytz/tzinfo.py", "focal_class": null, "focal_method": "fromutc", "tests": "import unittest\n\nclass Test_fromutc(unittest.TestCase):\n def test_fromutc(self):\n dt1 = datetime(2011, 10, 31)\n dt2 = self.tz.localize(dt1)\n for dt in [dt1, dt2]:\n loc_dt = self.tz.fromutc(dt)\n loc_dt2 = pytz.utc.localize(dt1).astimezone(self.tz)\n self.assertEqual(loc_dt, loc_dt2)\n new_tz = pytz.timezone('Europe/Paris')\n self.assertTrue(self.tz is not new_tz)\n dt3 = new_tz.localize(dt1)\n self.assertRaises(ValueError, self.tz.fromutc, dt3)\n", "method_code": " def fromutc(self, dt):\n \"\"\"See datetime.tzinfo.fromutc\"\"\"\n if dt.tzinfo is not None and dt.tzinfo is not self:\n raise ValueError('fromutc: dt.tzinfo is not self')\n return (dt + self._utcoffset).replace(tzinfo=self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def localize(self, dt, is_dst=False): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "varunarya10/pytz_2015_4", "test_name": "test_fromutc", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001520.py"} {"focal_file": "test/unit/message_pipeline_controller_test.py", "focal_class": null, "focal_method": "receiveMessage", "tests": "import unittest\n\nclass Test_receiveMessage(unittest.TestCase):\n def testCheckMessages(self):\n self.customers.append(Customer(msisdn='323456789012345', status='new'))\n self.session.add(self.customers[-1])\n consumption = Consumption(total_consumed=50.0, consumed_since_last_report=20.0)\n self.session.add(consumption)\n self.session.commit()\n messages = []\n messages.append(self.receiveMessage(self.customers[-1], 'ADD 100'))\n time.sleep(1)\n messages.append(self.receiveMessage(self.customers[-1], 'yes'))\n time.sleep(1)\n messages.append(self.receiveMessage(self.customers[-1], 'bal'))\n self.pipeline.check_messages()\n [self.session.refresh(msg) for msg in messages]\n [self.assertTrue(msg.handled) for msg in messages]\n\n def testProcessMessage(self):\n duff_message = self.receiveMessage(self.customers[0], 'slartibartfast')\n outgoing_message_count = self.outgoingCount()\n customer_status = self.customers[0].status\n self.pipeline.process_message(duff_message)\n self.assertEqual(outgoing_message_count + 1, self.outgoingCount())\n self.assertEqual(\"This is Grassroots Mobile Power. To add credit to the power strip, text 'ADD 100' to this number.\", self.lastSentMessage().message)\n self.assertEqual(customer_status, self.customers[0].status)\n self.assertTrue(duff_message.handled)\n outgoing_message_count = self.outgoingCount()\n add_credit_message = self.receiveMessage(self.customers[0], 'ADD 100')\n self.assertEqual('new', self.customers[0].status)\n self.pipeline.process_message(add_credit_message)\n self.assertEqual(outgoing_message_count + 1, self.outgoingCount())\n self.assertEqual('You have offered to add 100 credits to the power strip. Confirm by sending \"Yes\"', self.lastSentMessage().message)\n self.assertEqual('100', self.customers[0].status_value)\n self.assertEqual('topup_offered_inactive', self.customers[0].status)\n self.assertTrue(add_credit_message.handled)\n outgoing_message_count = self.outgoingCount()\n confirm_credit_message = self.receiveMessage(self.customers[0], 'yes')\n self.assertEqual('started', MeterState.latest().action)\n self.assertEqual(0.0, MeterState.latest().balance)\n self.pipeline.process_message(confirm_credit_message)\n self.assertEqual(outgoing_message_count + 1, self.outgoingCount())\n self.assertEqual('You have added 100 credits to the power strip.', self.lastSentMessage().message)\n self.assertEqual('active', self.customers[0].status)\n self.assertEqual('topup', MeterState.latest().action)\n self.assertEqual(100.0, MeterState.latest().balance)\n self.assertTrue(confirm_credit_message.handled)\n meter_balance = MeterState.latest().balance\n add_credit_message = self.receiveMessage(self.customers[0], 'ADD 200')\n self.pipeline.process_message(add_credit_message)\n decline_credit_message = self.receiveMessage(self.customers[0], 'no you silly bean')\n self.pipeline.process_message(decline_credit_message)\n self.assertEqual(meter_balance, MeterState.latest().balance)\n self.assertEqual(\"Topup successfully declined. To add credit to the power strip, text 'ADD 100' to this number.\", self.lastSentMessage().message)\n self.assertEqual(None, self.customers[0].status_value)\n self.assertTrue(add_credit_message.handled)\n consumption = Consumption(total_consumed=50.0, consumed_since_last_report=20.0)\n self.session.add(consumption)\n self.customers.append(Customer(msisdn='223456789012345', status='new'))\n self.session.add(self.customers[-1])\n self.session.commit()\n invalid_check_balance = self.receiveMessage(self.customers[-1], 'balance')\n self.pipeline.process_message(invalid_check_balance)\n self.assertEqual(\"Only current customers can check the balance. To add credit to the power strip, text 'ADD 100' to this number.\", self.lastSentMessage().message)\n self.assertTrue(invalid_check_balance.handled)\n self.customers[0].status = 'active'\n self.session.add(self.customers[0])\n self.session.commit()\n self.assertEqual('active', self.customers[0].status)\n check_balance = self.receiveMessage(self.customers[0], 'balance')\n self.pipeline.process_message(check_balance)\n self.assertEqual(\"Current balance: 50.0 credits remaining. 50.0 kilowatt-minutes used. 50.0 kilowatt-minutes remaining. To add credit to the power strip, text 'ADD 100' to this number.\", self.lastSentMessage().message)\n self.assertTrue(check_balance.handled)\n return None\n", "method_code": " def receiveMessage(self, customer, message_text):\n message = IncomingMessage(message=message_text)\n self.messages.append(message)\n customer.incoming_messages.append(message)\n self.session.commit()\n return message\n ", "context": "class MessagePipelineControllerTest(unittest.TestCase):\n def receiveMessage(self, customer, message_text): ...\n def setUp(self): ...\n def tearDown(self): ...\n def outgoingCount(self): ...\n def testSendMessage(self): ...\n def lastSentMessage(self): ...\n def testCheckMessages(self): ...\n def testProcessMessage(self): ...\n", "repository": "mitmedialab/grassroots-mobile", "test_name": "testCheckMessages", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001521.py"} {"focal_file": "coursebuilder/common/locales.py", "focal_class": null, "focal_method": "get_system_supported_locales", "tests": "import unittest\n\nclass Test_get_system_supported_locales(unittest.TestCase):\n def test_supported_locale_count(self):\n self.assertEquals(59, len(locales.get_system_supported_locales()))\n", "method_code": "def get_system_supported_locales():\n translations_path = os.path.join(appengine_config.BUNDLE_ROOT, 'modules/i18n/resources/locale')\n return sorted(os.listdir(translations_path) + ['ln'])", "context": "def get_system_supported_locales(): ...\ndef get_system_supported_locales(): ...\ndef get_locale_display_name(locale): ...\ndef parse_accept_language(accept_language_str): ...\n", "repository": "0svaldo/course-builder", "test_name": "test_supported_locale_count", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001522.py"} {"focal_file": "coursebuilder/common/locales.py", "focal_class": null, "focal_method": "get_locale_display_name", "tests": "import unittest\n\nclass Test_get_locale_display_name(unittest.TestCase):\n def test_localized_display_name(self):\n self.assertEquals('Deutsch (de)', locales.get_locale_display_name('de'))\n", "method_code": "def get_locale_display_name(locale):\n return LOCALES_DISPLAY_NAMES.get(locale, locale)", "context": "def get_locale_display_name(locale): ...\ndef get_system_supported_locales(): ...\ndef get_locale_display_name(locale): ...\ndef parse_accept_language(accept_language_str): ...\n", "repository": "0svaldo/course-builder", "test_name": "test_localized_display_name", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001523.py"} {"focal_file": "coursebuilder/common/safe_dom.py", "focal_class": "common.safe_dom.Element", "focal_method": "add_text", "tests": "import unittest\n\nclass Test_common_safe_dom_Element_add_text(unittest.TestCase):\n def test_add_text(self):\n \"\"\"Adding text should add text which will be sanitized.\"\"\"\n self.assertEqual('1<2', safe_dom.Element('a').add_text('1<2').__str__())\n", "method_code": " def add_text(self, unsafe_string):\n self._value += unicode(unsafe_string)\n ", "context": "class Comment(Node):\n def add_text(self, unsafe_string): ...\n def __init__(self, unsafe_string=''): ...\n def get_value(self): ...\n def sanitized(self): ...\n def add_attribute(self, **attr): ...\n\n self._value = unicode(unsafe_string)\n", "repository": "0svaldo/course-builder", "test_name": "test_add_text", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001524.py"} {"focal_file": "coursebuilder/common/safe_dom.py", "focal_class": "common.safe_dom.Element", "focal_method": "add_attribute", "tests": "import unittest\n\nclass Test_common_safe_dom_Element_add_attribute(unittest.TestCase):\n def test_add_attribute(self):\n \"\"\"Attributes can be added after initialization.\"\"\"\n self.assertEqual('', safe_dom.Element('a', b='c', d='e').add_attribute(f='g', h='i').__str__())\n", "method_code": " def add_attribute(self, **attr):\n pass\n ", "context": "class Comment(Node):\n def add_attribute(self, **attr): ...\n def __init__(self, unsafe_string=''): ...\n def get_value(self): ...\n def sanitized(self): ...\n def add_text(self, unsafe_string): ...\n\n self._value = unicode(unsafe_string)\n", "repository": "0svaldo/course-builder", "test_name": "test_add_attribute", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001525.py"} {"focal_file": "coursebuilder/common/schema_fields.py", "focal_class": "common.schema_fields.SchemaField", "focal_method": "add_property", "tests": "import unittest\n\nclass Test_common_schema_fields_SchemaField_add_property(unittest.TestCase):\n def test_single_property(self):\n reg = schema_fields.FieldRegistry('registry_name', 'registry_description')\n reg.add_property(schema_fields.SchemaField('field_name', 'field_label', 'property_type', description='property_description'))\n expected = '\\n{\\n \"properties\": {\\n \"field_name\": {\\n \"type\": \"property_type\",\\n \"description\": \"property_description\"\\n }\\n },\\n \"type\": \"object\",\\n \"id\": \"registry_name\",\\n \"description\": \"registry_description\"\\n}'\n self.assert_json_schema_value(expected, reg)\n expected = '\\n[\\n [[\"title\"], \"registry_name\"],\\n [[\"properties\",\"field_name\",\"_inputex\"], {\\n \"description\": \"property_description\",\\n \"label\":\"field_label\"\\n }]\\n]\\n'\n self.assert_schema_dict_value(expected, reg)\n\n def test_mc_question_schema(self):\n \"\"\"The multiple choice question schema is a good end-to-end example.\"\"\"\n mc_question = schema_fields.FieldRegistry('MC Question', extra_schema_dict_values={'className': 'mc-question'})\n mc_question.add_property(schema_fields.SchemaField('question', 'Question', 'string'))\n choice_type = schema_fields.FieldRegistry('choice', extra_schema_dict_values={'className': 'mc-choice'})\n choice_type.add_property(schema_fields.SchemaField('text', 'Text', 'string'))\n choice_type.add_property(schema_fields.SchemaField('score', 'Score', 'string'))\n choice_type.add_property(schema_fields.SchemaField('feedback', 'Feedback', 'string'))\n choices_array = schema_fields.FieldArray('choices', 'Choices', item_type=choice_type)\n mc_question.add_property(choices_array)\n expected = '\\n{\\n \"type\":\"object\",\\n \"id\":\"MCQuestion\",\\n \"properties\":{\\n \"question\":{\"type\":\"string\"},\\n \"choices\":{\\n \"items\":{\\n \"type\":\"object\",\\n \"id\":\"choice\",\\n \"properties\":{\\n \"text\":{\"type\":\"string\"},\\n \"score\":{\"type\":\"string\"},\\n \"feedback\":{\"type\":\"string\"}\\n }\\n },\\n \"type\":\"array\"\\n }\\n }\\n}\\n'\n self.assert_json_schema_value(expected, mc_question)\n expected = '\\n[\\n [[\"title\"],\"MCQuestion\"],\\n [[\"_inputex\"],{\"className\":\"mc-question\"}],\\n [[\"properties\",\"question\",\"_inputex\"],{\"label\":\"Question\"}],\\n [[\"properties\",\"choices\",\"_inputex\"],{\"label\":\"Choices\"}],\\n [[\"properties\",\"choices\",\"items\",\"title\"],\"choice\"],\\n [[\"properties\",\"choices\",\"items\",\"_inputex\"],{\"className\":\"mc-choice\"}],\\n [[\"properties\",\"choices\",\"items\",\"properties\",\"text\",\"_inputex\"],{\\n \"label\":\"Text\"\\n }],\\n [[\"properties\",\"choices\",\"items\",\"properties\",\"score\",\"_inputex\"],{\\n \"label\":\"Score\"\\n }],\\n [[\"properties\",\"choices\",\"items\",\"properties\",\"feedback\",\"_inputex\"],{\\n \"label\":\"Feedback\"\\n }]\\n ]\\n'\n self.assert_schema_dict_value(expected, mc_question)\n", "method_code": " def add_property(self, schema_field):\n \"\"\"Add a Property to this Registry.\"\"\"\n self._properties.append(schema_field)\n ", "context": "class Registry(object):\n def add_property(self, schema_field): ...\n def __init__(self, title, description=None, extra_schema_dict_values=None): ...\n def title(self): ...\n def sub_registries(self): ...\n def get_property(self, property_name): ...\n def get_sub_registry(self, sub_registry_name): ...\n def remove_property(self, property_name): ...\n def add_sub_registry(self, name, title=None, description=None, registry=None, extra_schema_dict_values=None): ...\n def has_subregistries(self): ...\n def get_display_dict(self): ...\n def clone_only_items_named(self, paths): ...\n\n self._title = title\n self._registry = {'id': title, 'type': 'object'}\n self._description = description\n self._extra_schema_dict_values = extra_schema_dict_values\n self._properties = []\n self._sub_registries = collections.OrderedDict()\n", "repository": "0svaldo/course-builder", "test_name": "test_single_property", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001526.py"} {"focal_file": "coursebuilder/common/schema_fields.py", "focal_class": "common.schema_fields.SchemaField", "focal_method": "validate", "tests": "import unittest\n\nclass Test_common_schema_fields_SchemaField_validate(unittest.TestCase):\n def test_validate(self):\n\n def fail(value, errors):\n errors.append(value)\n registry = schema_fields.FieldRegistry('Test Registry')\n registry.add_property(schema_fields.SchemaField('top_level_bad', 'Top Level Bad Item', 'string', optional=True, validator=fail))\n registry.add_property(schema_fields.SchemaField('top_level_good', 'Top Level Good Item', 'string', optional=True))\n sub_registry = registry.add_sub_registry('child', 'Child Registry')\n sub_registry.add_property(schema_fields.SchemaField('child:bad', 'Top Level Bad Item', 'string', optional=True, validator=fail))\n sub_registry.add_property(schema_fields.SchemaField('child:good', 'Top Level Good Item', 'string', optional=True))\n child_bad_value = 'child_bad_value'\n top_level_bad_value = 'top_level_bad_value'\n errors = []\n payload = {'top_level_bad': top_level_bad_value, 'top_level_good': 'top_level_good_value', 'child': {'bad': child_bad_value, 'good': 'child_good_value'}}\n registry.validate(payload, errors)\n self.assertEqual([top_level_bad_value, child_bad_value], errors)\n", "method_code": " def validate(self, value, errors):\n if self._validator:\n self._validator(value, errors)\n ", "context": "class SchemaField(Property):\n def validate(self, value, errors): ...\n def __init__(self, name, label, property_type, select_data=None, description=None, optional=False, hidden=False, editable=True, i18n=None, extra_schema_dict_values=None, validator=None, default_value=None): ...\n def hidden(self): ...\n def editable(self): ...\n def i18n(self): ...\n def get_json_schema_dict(self): ...\n def _get_schema_dict(self, prefix_key): ...\n\n self._hidden = hidden\n self._editable = editable\n self._validator = validator\n self._i18n = i18n\n self._default_value = default_value\n", "repository": "0svaldo/course-builder", "test_name": "test_validate", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001527.py"} {"focal_file": "coursebuilder/common/utils.py", "focal_class": null, "focal_method": "parse_timedelta_string", "tests": "import unittest\n\nclass Test_parse_timedelta_string(unittest.TestCase):\n def test_parse_empty_string(self):\n self.assertEquals(utils.parse_timedelta_string(''), datetime.timedelta())\n", "method_code": "def parse_timedelta_string(timedelta_string):\n return datetime.timedelta(**_parse_timedelta_string(timedelta_string))", "context": "def parse_timedelta_string(timedelta_string): ...\ndef text_to_list(text, splitter=SPLITTER): ...\ndef list_to_text(items): ...\ndef generate_instance_id(): ...\ndef truncate(x, precision=2): ...\ndef iter_all(query, batch_size=100): ...\ndef run_hooks(hooks, *args, **kwargs): ...\ndef log_exception_origin(): ...\ndef find(predicate, iterable, default=None): ...\ndef _parse_timedelta_string(timedelta_string): ...\ndef parse_timedelta_string(timedelta_string): ...\n", "repository": "0svaldo/course-builder", "test_name": "test_parse_empty_string", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001528.py"} {"focal_file": "coursebuilder/tools/etl/mapreduce.py", "focal_class": "tools.etl.mapreduce.Histogram", "focal_method": "_get_bin_number", "tests": "import unittest\n\nclass Test_tools_etl_mapreduce_Histogram_get_bin_number(unittest.TestCase):\n def test_get_bin_number(self):\n bucket_size = 30\n histogram = mapreduce.Histogram(bucket_size)\n self.assertEquals(histogram._get_bin_number(0), 0)\n self.assertEquals(histogram._get_bin_number(bucket_size), 0)\n self.assertEquals(histogram._get_bin_number(bucket_size + 1), 1)\n self.assertEquals(histogram._get_bin_number(bucket_size * 2), 1)\n self.assertEquals(histogram._get_bin_number(bucket_size * 2 + 1), 2)\n", "method_code": " def _get_bin_number(self, value):\n \"\"\"Returns appropriate bin number for given value.\"\"\"\n if value < 0:\n raise ValueError('Cannot calculate index for negative value')\n return max(0, (value - 1) // self._bucket_size)\n ", "context": "class Histogram(object):\n def _get_bin_number(self, value): ...\n def __init__(self, bucket_size): ...\n def add(self, value): ...\n def _increment_bin(self, n): ...\n def to_list(self): ...\n def to_noise_filtered_list(self): ...\n\n self._values = {}\n self._bucket_size = bucket_size\n\n _NUM_ZEROS = 3\n", "repository": "0svaldo/course-builder", "test_name": "test_get_bin_number", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001529.py"} {"focal_file": "coursebuilder/tools/etl/mapreduce.py", "focal_class": "tools.etl.mapreduce.Histogram", "focal_method": "add", "tests": "import unittest\n\nclass Test_tools_etl_mapreduce_Histogram_add(unittest.TestCase):\n def test_add(self):\n histogram = mapreduce.Histogram(30)\n histogram.add(0)\n histogram.add(1)\n histogram.add(31)\n histogram.add(60)\n histogram.add(61)\n histogram.add(123)\n self.assertEquals(histogram._values, {0: 2, 1: 2, 2: 1, 4: 1})\n", "method_code": " def add(self, value):\n \"\"\"Adds value into self._values.\"\"\"\n bin_number = self._get_bin_number(value)\n self._increment_bin(bin_number)\n ", "context": "class Histogram(object):\n def add(self, value): ...\n def __init__(self, bucket_size): ...\n def _get_bin_number(self, value): ...\n def _increment_bin(self, n): ...\n def to_list(self): ...\n def to_noise_filtered_list(self): ...\n\n self._values = {}\n self._bucket_size = bucket_size\n\n _NUM_ZEROS = 3\n", "repository": "0svaldo/course-builder", "test_name": "test_add", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001530.py"} {"focal_file": "coursebuilder/tools/etl/mapreduce.py", "focal_class": "tools.etl.mapreduce.Histogram", "focal_method": "to_list", "tests": "import unittest\n\nclass Test_tools_etl_mapreduce_Histogram_to_list(unittest.TestCase):\n def test_to_list(self):\n histogram = mapreduce.Histogram(30)\n histogram.add(0)\n histogram.add(1)\n histogram.add(31)\n histogram.add(60)\n histogram.add(61)\n histogram.add(123)\n self.assertEquals(histogram.to_list(), [2, 2, 1, 0, 1])\n histogram = mapreduce.Histogram(30)\n histogram.add(121)\n self.assertEquals(histogram.to_list(), [0, 0, 0, 0, 1])\n", "method_code": " def to_list(self):\n \"\"\"Returns self._values converted into a list, sorted by its keys.\"\"\"\n try:\n max_key = max(self._values.iterkeys())\n return [self._values.get(n, 0) for n in xrange(0, max_key + 1)]\n except ValueError:\n return []\n ", "context": "class Histogram(object):\n def to_list(self): ...\n def __init__(self, bucket_size): ...\n def add(self, value): ...\n def _get_bin_number(self, value): ...\n def _increment_bin(self, n): ...\n def to_noise_filtered_list(self): ...\n\n self._values = {}\n self._bucket_size = bucket_size\n\n _NUM_ZEROS = 3\n", "repository": "0svaldo/course-builder", "test_name": "test_to_list", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001531.py"} {"focal_file": "coursebuilder/models/transforms.py", "focal_class": null, "focal_method": "value_to_string", "tests": "import unittest\n\nclass Test_value_to_string(unittest.TestCase):\n def test_value_to_string(self):\n assert transforms.value_to_string(True, bool) == 'True'\n assert transforms.value_to_string(False, bool) == 'False'\n assert transforms.value_to_string(None, bool) == 'False'\n", "method_code": "def value_to_string(value, value_type):\n \"\"\"Converts value to a string representation.\"\"\"\n if value_type == str:\n return value\n elif value_type == bool:\n if value:\n return 'True'\n else:\n return 'False'\n elif value_type == int or value_type == long:\n return str(value)\n else:\n raise ValueError('Unknown type: %s' % value_type)", "context": "def value_to_string(value, value_type): ...\ndef dict_to_json(source_dict, unused_schema): ...\ndef validate_object_matches_json_schema(obj, schema, path='', complaints=None): ...\ndef dumps(*args, **kwargs): ...\ndef loads(s, prefix=JSON_XSSI_PREFIX, strict=True, **kwargs): ...\ndef _json_to_datetime(value, date_only=False): ...\ndef json_to_dict(source_dict, schema, permit_none_values=False): ...\ndef string_to_value(string, value_type): ...\ndef value_to_string(value, value_type): ...\ndef dict_to_instance(adict, instance, defaults=None): ...\ndef instance_to_dict(instance): ...\ndef send_json_response(handler, status_code, message, payload_dict=None, xsrf_token=None): ...\ndef send_file_upload_response(handler, status_code, message, payload_dict=None): ...\ndef convert_dict_to_xml(element, python_object): ...\ndef convert_json_rows_file_to_xml(json_fn, xml_fn): ...\ndef nested_lists_as_string_to_dict(stringified_list_of_lists): ...\ndef dict_to_nested_lists_as_string(d): ...\n", "repository": "0svaldo/course-builder", "test_name": "test_value_to_string", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001532.py"} {"focal_file": "coursebuilder/models/transforms.py", "focal_class": null, "focal_method": "string_to_value", "tests": "import unittest\n\nclass Test_string_to_value(unittest.TestCase):\n def test_string_to_value(self):\n assert transforms.string_to_value('True', bool)\n assert transforms.string_to_value('1', bool)\n assert transforms.string_to_value(1, bool)\n assert not transforms.string_to_value('False', bool)\n assert not transforms.string_to_value('0', bool)\n assert not transforms.string_to_value('5', bool)\n assert not transforms.string_to_value(0, bool)\n assert not transforms.string_to_value(5, bool)\n assert not transforms.string_to_value(None, bool)\n assert transforms.string_to_value('15', int) == 15\n assert transforms.string_to_value(15, int) == 15\n assert transforms.string_to_value(None, int) == 0\n assert transforms.string_to_value('foo', str) == 'foo'\n assert transforms.string_to_value(None, str) == str('')\n", "method_code": "def string_to_value(string, value_type):\n \"\"\"Converts string representation to a value.\"\"\"\n if value_type == str:\n if not string:\n return ''\n else:\n return string\n elif value_type == bool:\n if string == '1' or string == 'True' or string == 1:\n return True\n else:\n return False\n elif value_type == int or value_type == long:\n if not string:\n return 0\n else:\n return long(string)\n else:\n raise ValueError('Unknown type: %s' % value_type)", "context": "def string_to_value(string, value_type): ...\ndef dict_to_json(source_dict, unused_schema): ...\ndef validate_object_matches_json_schema(obj, schema, path='', complaints=None): ...\ndef dumps(*args, **kwargs): ...\ndef loads(s, prefix=JSON_XSSI_PREFIX, strict=True, **kwargs): ...\ndef _json_to_datetime(value, date_only=False): ...\ndef json_to_dict(source_dict, schema, permit_none_values=False): ...\ndef string_to_value(string, value_type): ...\ndef value_to_string(value, value_type): ...\ndef dict_to_instance(adict, instance, defaults=None): ...\ndef instance_to_dict(instance): ...\ndef send_json_response(handler, status_code, message, payload_dict=None, xsrf_token=None): ...\ndef send_file_upload_response(handler, status_code, message, payload_dict=None): ...\ndef convert_dict_to_xml(element, python_object): ...\ndef convert_json_rows_file_to_xml(json_fn, xml_fn): ...\ndef nested_lists_as_string_to_dict(stringified_list_of_lists): ...\ndef dict_to_nested_lists_as_string(d): ...\n", "repository": "0svaldo/course-builder", "test_name": "test_string_to_value", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001533.py"} {"focal_file": "src/you_get/common.py", "focal_class": null, "focal_method": "match1", "tests": "import unittest\n\nclass Test_match1(unittest.TestCase):\n def test_match1(self):\n self.assertEqual(match1('http://youtu.be/1234567890A', 'youtu.be/([^/]+)'), '1234567890A')\n self.assertEqual(match1('http://youtu.be/1234567890A', 'youtu.be/([^/]+)', 'youtu.(\\\\w+)'), ['1234567890A', 'be'])\n", "method_code": "def match1(text, *patterns):\n \"\"\"Scans through a string for substrings matched some patterns (first-subgroups only).\n\n Args:\n text: A string to be scanned.\n patterns: Arbitrary number of regex patterns.\n\n Returns:\n When only one pattern is given, returns a string (None if no match found).\n When more than one pattern are given, returns a list of strings ([] if no match found).\n \"\"\"\n if len(patterns) == 1:\n pattern = patterns[0]\n match = re.search(pattern, text)\n if match:\n return match.group(1)\n else:\n return None\n else:\n ret = []\n for pattern in patterns:\n match = re.search(pattern, text)\n if match:\n ret.append(match.group(1))\n return ret", "context": "def match1(text, *patterns): ...\ndef maybe_print(*s): ...\ndef tr(s): ...\ndef r1(pattern, text): ...\ndef r1_of(patterns, text): ...\ndef match1(text, *patterns): ...\ndef matchall(text, patterns): ...\ndef launch_player(player, urls): ...\ndef parse_query_param(url, param): ...\ndef unicodize(text): ...\ndef escape_file_path(path): ...\ndef ungzip(data): ...\ndef undeflate(data): ...\ndef get_response(url, faker=False): ...\ndef get_html(url, encoding=None, faker=False): ...\ndef get_decoded_html(url, faker=False): ...\ndef get_location(url): ...\ndef urlopen_with_retry(*args, **kwargs): ...\ndef get_content(url, headers={}, decoded=True): ...\ndef post_content(url, headers={}, post_data={}, decoded=True): ...\ndef url_size(url, faker=False, headers={}): ...\ndef urls_size(urls, faker=False, headers={}): ...\ndef get_head(url, headers={}, get_method='HEAD'): ...\ndef url_info(url, faker=False, headers={}): ...\ndef url_locations(urls, faker=False, headers={}): ...\ndef url_save(url, filepath, bar, refer=None, is_part=False, faker=False, headers={}, timeout=None, **kwargs): ...\ndef url_save_chunked(url, filepath, bar, dyn_callback=None, chunk_size=0, ignore_range=False, refer=None, is_part=False, faker=False, headers={}): ...\ndef get_output_filename(urls, title, ext, output_dir, merge): ...\ndef download_urls(urls, title, ext, total_size, output_dir='.', refer=None, merge=True, faker=False, headers={}, **kwargs): ...\ndef download_urls_chunked(urls, title, ext, total_size, output_dir='.', refer=None, merge=True, faker=False, headers={}, **kwargs): ...\ndef download_rtmp_url(url, title, ext, params={}, total_size=0, output_dir='.', refer=None, merge=True, faker=False): ...\ndef download_url_ffmpeg(url, title, ext, params={}, total_size=0, output_dir='.', refer=None, merge=True, faker=False): ...\ndef playlist_not_supported(name): ...\ndef print_info(site_info, title, type, size): ...\ndef mime_to_container(mime): ...\ndef parse_host(host): ...\ndef set_proxy(proxy): ...\ndef unset_proxy(): ...\ndef set_http_proxy(proxy): ...\ndef print_more_compatible(*args, **kwargs): ...\ndef download_main(download, download_playlist, urls, playlist, **kwargs): ...\ndef script_main(script_name, download, download_playlist, **kwargs): ...\ndef google_search(url): ...\ndef url_to_module(url): ...\ndef any_download(url, **kwargs): ...\ndef any_download_playlist(url, **kwargs): ...\ndef main(**kwargs): ...\n", "repository": "zhangzhaolei/my_video", "test_name": "test_match1", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001534.py"} {"focal_file": "src/you_get/util/fs.py", "focal_class": null, "focal_method": "legitimize", "tests": "import unittest\n\nclass Test_legitimize(unittest.TestCase):\n def test_legitimize(self):\n self.assertEqual(legitimize('1*2', os='Linux'), '1*2')\n self.assertEqual(legitimize('1*2', os='Darwin'), '1*2')\n self.assertEqual(legitimize('1*2', os='Windows'), '1-2')\n", "method_code": "def legitimize(text, os=platform.system()):\n \"\"\"Converts a string to a valid filename.\n \"\"\"\n text = text.translate({0: None, ord('/'): '-', ord('|'): '-'})\n if os == 'Windows':\n text = text.translate({ord(':'): '-', ord('*'): '-', ord('?'): '-', ord('\\\\'): '-', ord('\"'): \"'\", ord('+'): '-', ord('<'): '-', ord('>'): '-', ord('['): '(', ord(']'): ')'})\n else:\n if os == 'Darwin':\n text = text.translate({ord(':'): '-'})\n if text.startswith('.'):\n text = text[1:]\n text = text[:82]\n return text", "context": "def legitimize(text, os=platform.system()): ...\ndef legitimize(text, os=platform.system()): ...\n", "repository": "zhangzhaolei/my_video", "test_name": "test_legitimize", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001535.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getDbVersion", "tests": "import unittest\n\nclass Test_getDbVersion(unittest.TestCase):\n def test_getDbVersion(self):\n \"\"\" Test if the getDbVersion function returns the version properly \"\"\"\n self.assertEqual(self.db.getDbVersion(), '18', 'Database version is not returned correctly.')\n", "method_code": " def getDbVersion(self):\n \"\"\"\n Returns the version of the currently opened database file.\n \n Returns\n -------\n version : string\n the version of the database\n \n \"\"\"\n return self._current_version\n ", "context": "class DataFile():\n def getDbVersion(self): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getDbVersion", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001536.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setPath", "tests": "import unittest\n\nclass Test_setPath(unittest.TestCase):\n def test_setPath(self):\n \"\"\" Test the setPath function \"\"\"\n path = self.db.setPath(path_string='test')\n self.assertEqual(path.path, 'test', 'Path was not set properly')\n", "method_code": " def setPath(self, path_string=None, id=None):\n \"\"\"\n Update or create a new :py:class:`Path` entry with the given parameters.\n \n See also: :py:meth:`~.DataFile.getPath`, :py:meth:`~.DataFile.getPaths`, :py:meth:`~.DataFile.deletePaths`\n \n Parameters\n ----------\n path_string: string, optional\n the string specifying the path.\n id: int, optional\n the id of the paths.\n \n Returns\n -------\n entries : :py:class:`Path`\n the changed or created :py:class:`Path` entry.\n \"\"\"\n try:\n path = self.table_path.get(**noNoneDict(id=id, path=path_string))\n except peewee.DoesNotExist:\n path = self.table_path()\n setFields(path, dict(path=path_string))\n path.save()\n return path\n ", "context": "class DataFile():\n def setPath(self, path_string=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setPath", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001537.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getPath", "tests": "import unittest\n\nclass Test_getPath(unittest.TestCase):\n def test_getPath(self):\n \"\"\" Test the getPath function \"\"\"\n self.db.setPath(path_string='test')\n path = self.db.getPath(path_string='test')\n self.assertEqual(path.path, 'test', 'Retrieving a path does not work')\n path = self.db.getPath(path_string='testX')\n self.assertEqual(path, None, 'Retrieving an non existent path does not work')\n path = self.db.getPath(path_string='testX', create=True)\n self.assertEqual(path.path, 'testX', 'Creating a non existent path does not work')\n", "method_code": " def getPath(self, path_string=None, id=None, create=False, absolute=False):\n \"\"\"\n Get a :py:class:`Path` entry from the database.\n \n See also: :py:meth:`~.DataFile.getPaths`, :py:meth:`~.DataFile.setPath`, :py:meth:`~.DataFile.deletePaths`\n \n Parameters\n ----------\n path_string: string, optional\n the string specifying the path.\n id: int, optional\n the id of the path.\n create: bool, optional\n whether the path should be created if it does not exist. (default: False)\n absolute: bool, optional\n whether the created path should be absolute or relative to the database file. (default: False)\n \n Returns\n -------\n path : :py:class:`Path`\n the created/requested :py:class:`Path` entry.\n \"\"\"\n assert any((e is not None for e in [id, path_string])), 'Path and ID may not be both None'\n kwargs = {}\n if path_string is not None:\n if not absolute:\n if self._database_filename:\n try:\n path_string = os.path.relpath(path_string, os.path.dirname(self._database_filename))\n except ValueError:\n path_string = os.path.abspath(path_string)\n path_string = os.path.normpath(path_string)\n kwargs['path'] = path_string\n if id:\n kwargs['id'] = id\n try:\n path = self.table_path.get(**kwargs)\n except peewee.DoesNotExist as err:\n if create:\n path = self.table_path(**kwargs)\n path.save()\n else:\n return None\n return path\n ", "context": "class DataFile():\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getPath", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001538.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getPaths", "tests": "import unittest\n\nclass Test_getPaths(unittest.TestCase):\n def test_getPaths(self):\n \"\"\" Test the getPaths function \"\"\"\n p1 = os.path.join('foo', 'bar1')\n p2 = os.path.join('foo', 'bar2')\n p3 = os.path.join('loo', 'bar1')\n self.db.setPath(path_string=p1)\n self.db.setPath(path_string=p2)\n self.db.setPath(path_string=p3)\n paths = self.db.getPaths(path_string=p2)\n self.assertEqual([p.path for p in paths], [p2], 'Retrieving a single path works does not work.')\n paths = self.db.getPaths(path_string=[p1, p2])\n self.assertEqual([p.path for p in paths], [p1, p2], 'Retrieving multiple paths does not work.')\n paths = self.db.getPaths()\n self.assertEqual(paths.count(), 3, 'Retrieving all paths does not work.')\n paths = self.db.getPaths(base_path='foo')\n self.assertEqual([p.path for p in paths], [p1, p2], 'Retrieving paths with basepath does not work.')\n", "method_code": " def getPaths(self, path_string=None, base_path=None, id=None):\n \"\"\"\n Get all :py:class:`Path` entries from the database, which match the given criteria. If no critera a given, return all paths.\n \n See also: :py:meth:`~.DataFile.getPath`, :py:meth:`~.DataFile.setPath`, :py:meth:`~.DataFile.deletePaths`\n \n Parameters\n ----------\n path_string : string, path_string, optional\n the string/s specifying the path/s.\n base_path : string, optional\n return only paths starting with the base_path string.\n id: int, array_like, optional\n the id/s of the path/s.\n \n Returns\n -------\n entries : array_like\n a query object containing all the matching :py:class:`Path` entries in the database file.\n \"\"\"\n query = self.table_path.select()\n query = addFilter(query, id, self.table_path.id)\n query = addFilter(query, path_string, self.table_path.path)\n if base_path is not None:\n query = query.where(self.table_path.path.startswith(base_path))\n return query\n ", "context": "class DataFile():\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getPaths", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001539.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deletePaths", "tests": "import unittest\n\nclass Test_deletePaths(unittest.TestCase):\n def test_deletePaths(self):\n \"\"\" Test the deletePaths function \"\"\"\n p1 = os.path.join('foo', 'bar1')\n p2 = os.path.join('foo', 'bar2')\n p3 = os.path.join('loo', 'bar1')\n self.db.setPath(path_string=p1)\n self.db.setPath(path_string=p2)\n self.db.setPath(path_string=p3)\n self.db.deletePaths(path_string=p1)\n paths = self.db.getPaths()\n self.assertEqual(paths.count(), 2, 'Deleting one path does not work')\n self.db.setPath(path_string=p1)\n self.db.deletePaths(path_string=[p1, p3])\n paths = self.db.getPaths()\n self.assertEqual(paths.count(), 1, 'Deleting two paths does not work')\n self.db.setPath(path_string=p1)\n self.db.setPath(path_string=p3)\n self.db.deletePaths(base_path='foo')\n paths = self.db.getPaths()\n self.assertEqual(paths.count(), 1, 'Deleting two paths with base_path does not work')\n", "method_code": " def deletePaths(self, path_string=None, base_path=None, id=None):\n \"\"\"\n Delete all :py:class:`Path` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getPath`, :py:meth:`~.DataFile.getPaths`, :py:meth:`~.DataFile.setPath`\n \n Parameters\n ----------\n path_string: string, optional\n the string/s specifying the paths.\n base_path: string, optional\n return only paths starting with the base_path string.\n id: int, optional\n the id/s of the paths.\n \n Returns\n -------\n rows : int\n the number of affected rows.\n \"\"\"\n query = self.table_path.delete()\n query = addFilter(query, id, self.table_path.id)\n query = addFilter(query, path_string, self.table_path.path)\n if base_path is not None:\n query = query.where(self.table_path.path.startswith(base_path))\n return query.execute()\n ", "context": "class DataFile():\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deletePaths", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001540.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setImage", "tests": "import unittest\n\nclass Test_setImage(unittest.TestCase):\n def test_setImage(self):\n \"\"\" Test the setImage function \"\"\"\n im1 = self.db.setImage('test.jpg')\n self.assertEqual(im1.filename, 'test.jpg', \"Creating an image didn't work\")\n", "method_code": " def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None):\n \"\"\"\n Update or create new :py:class:`Image` entry with the given parameters.\n \n See also: :py:meth:`~.DataFile.getImage`, :py:meth:`~.DataFile.getImages`, :py:meth:`~.DataFile.getImageIterator`, :py:meth:`~.DataFile.deleteImages`.\n \n Parameters\n ----------\n filename : string, optional\n the filename of the image (including the extension)\n path : string, int, :py:class:`Path`, optional\n the path string, id or entry of the image to insert\n frame : int, optional\n the frame number if the image is part of a video\n external_id : int, optional\n an external id for the image. Only necessary if the annotation server is used\n timestamp : datetime object, optional\n the timestamp of the image\n width : int, optional\n the width of the image\n height : int, optional\n the height of the image\n id : int, optional\n the id of the image\n layer : int, string, optional\n the layer_id of the image, always use with sort_index\n sort_index: int, only use with layer\n the sort index (position in the time line) if not in layer 0\n \n Returns\n -------\n image : :py:class:`Image`\n the changed or created :py:class:`Image` entry\n \"\"\"\n try:\n item = self.table_image.get(id=id, filename=filename)\n new_image = False\n except peewee.DoesNotExist:\n item = self.table_image()\n new_image = True\n if isinstance(layer, basestring):\n layer = self.getLayer(layer, create=True)\n if filename is not None:\n item.filename = os.path.split(filename)[1]\n item.ext = os.path.splitext(filename)[1]\n if path is None:\n item.path = self.getPath(path_string=os.path.split(filename)[0], create=True)\n if isinstance(path, basestring):\n path = self.getPath(path)\n setFields(item, noNoneDict(frame=frame, path=path, external_id=external_id, timestamp=timestamp, width=width, height=height, layer=layer, sort_index=sort_index))\n if new_image:\n if sort_index is None:\n if self._next_sort_index is None:\n try:\n self._next_sort_index = self.db.execute_sql('SELECT MAX(sort_index) FROM image LIMIT 1;').fetchone()[0] + 1\n except IndexError:\n self._next_sort_index = 0\n item.sort_index = self._next_sort_index\n self._next_sort_index += 1\n item.save()\n return item\n ", "context": "class DataFile():\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setImage", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001541.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getImage", "tests": "import unittest\n\nclass Test_getImage(unittest.TestCase):\n def test_getImage(self):\n \"\"\" Test the setImage function \"\"\"\n self.db.setImage('test1.jpg')\n self.db.setImage('test2.jpg')\n self.db.setImage('test3.jpg')\n im = self.db.getImage(2)\n self.assertEqual(im.filename, 'test3.jpg', 'Getting an image does not work.')\n", "method_code": " def getImage(self, frame=None, filename=None, id=None, layer=None):\n \"\"\"\n Returns the :py:class:`Image` entry with the given frame number and layer.\n \n See also: :py:meth:`~.DataFile.getImages`, :py:meth:`~.DataFile.getImageIterator`, :py:meth:`~.DataFile.setImage`,\n :py:meth:`~.DataFile.deleteImages`.\n \n Parameters\n ----------\n frame : int, optional\n the frame number of the desired image, as displayed in ClickPoints.\n filename : string, optional\n the filename of the desired image.\n id : int, optional\n the id of the image.\n layer : int, string, optional\n the layer_id or name of the layer of the image.\n \n Returns\n -------\n image : :py:class:`Image`\n the image entry.\n \"\"\"\n layer = self._processLayerNameField(layer)\n kwargs = noNoneDict(sort_index=frame, filename=filename, id=id, layer=layer)\n try:\n return self.table_image.get(**kwargs)\n except peewee.DoesNotExist:\n KeyError('No image with %s found.' % VerboseDict(kwargs))\n ", "context": "class DataFile():\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getImage", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001542.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getImages", "tests": "import unittest\n\nclass Test_getImages(unittest.TestCase):\n def test_getImages(self):\n \"\"\" Test the getImages function \"\"\"\n self.db.setImage('test1.jpg')\n self.db.setImage('test2.jpg')\n self.db.setImage('test3.jpg')\n ims = self.db.getImages([1, 2])\n self.assertEqual(ims.count(), 2, 'Getting images does not work')\n ims = self.db.getImageIterator(1)\n self.assertEqual([im.filename for im in ims], ['test2.jpg', 'test3.jpg'], 'Getting images does not work')\n self.db.setImage('test4.jpg')\n self.db.setImage('test5.jpg')\n self.db.setImage('test6.jpg')\n self.db.setImage('test7.jpg')\n ims = self.db.getImages(frame=slice(1, 5))\n self.assertTrue([im.sort_index for im in ims] == [1, 2, 3, 4, 5], 'Failed get by slice uppder and lower limit')\n ims = self.db.getImages(frame=slice(4, None))\n self.assertTrue([im.sort_index for im in ims] == [4, 5, 6], 'Failed get by slice lower limit')\n ims = self.db.getImages(frame=slice(None, 3))\n self.assertTrue([im.sort_index for im in ims] == [0, 1, 2], 'Failed get by slice uppder limit')\n", "method_code": " def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'):\n \"\"\"\n Get all :py:class:`Image` entries sorted by sort index. For large databases\n :py:meth:`~.DataFile.getImageIterator`, should be used as it doesn't load all frames at once.\n \n See also: :py:meth:`~.DataFile.getImage`, :py:meth:`~.DataFile.getImageIterator`, :py:meth:`~.DataFile.setImage`,\n :py:meth:`~.DataFile.deleteImages`.\n \n Parameters\n ----------\n frame : int, array_like, optional\n the frame number/s of the image/s as displayed in ClickPoints (sort_index in the database).\n filename : string, array_like, optional\n the filename/s of the image/s.\n ext : string, array_like, optional\n the extension/s of the image/s.\n external_id : int, array_like, optional\n the external id/s of the image/s.\n timestamp : datetime, array_like, optional\n the timestamp/s of the image/s.\n width : int, array_like, optional\n the width/s of the image/s.\n height : int, array_like, optional\n the height/s of the image/s\n path : int, :py:class:`Path`, array_like, optional\n the path/s (or path id/s) of the image/s\n layer : int, string, array_like, optional\n the layer/s of the image/s\n order_by : string, optional\n sort by either 'sort_index' (default) or 'timestamp'.\n \n Returns\n -------\n entries : array_like\n a query object containing all the :py:class:`Image` entries in the database file.\n \"\"\"\n layer = self._processLayerNameField(layer)\n query = self.table_image.select()\n query = addFilter(query, frame, self.table_image.sort_index)\n query = addFilter(query, filename, self.table_image.filename)\n query = addFilter(query, ext, self.table_image.ext)\n query = addFilter(query, external_id, self.table_image.external_id)\n query = addFilter(query, timestamp, self.table_image.timestamp)\n query = addFilter(query, width, self.table_image.width)\n query = addFilter(query, height, self.table_image.height)\n query = addFilter(query, path, self.table_image.path)\n query = addFilter(query, layer, self.table_image.layer)\n if order_by == 'sort_index':\n query = query.order_by(self.table_image.sort_index)\n elif order_by == 'timestamp':\n query = query.order_by(self.table_image.timestamp)\n else:\n raise Exception('Unknown order_by parameter - use sort_index or timestamp')\n return query\n ", "context": "class DataFile():\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getImages", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001543.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteImages", "tests": "import unittest\n\nclass Test_deleteImages(unittest.TestCase):\n def test_deleteImages(self):\n \"\"\" Test the deleteImages function \"\"\"\n self.db.setImage('test1.jpg')\n self.db.setImage('test2.jpg')\n self.db.setImage('test3.jpg')\n ims = self.db.getImages()\n self.assertEqual(ims.count(), 3, 'Getting images does not work')\n self.db.deleteImages(filename='test1.jpg')\n ims = self.db.getImages()\n self.assertEqual(ims.count(), 2, 'Deleting image does not work')\n self.db.deleteImages(filename=['test2.jpg', 'test3.jpg'])\n ims = self.db.getImages()\n self.assertEqual(ims.count(), 0, 'Deleting images does not work')\n", "method_code": " def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None):\n \"\"\"\n Delete all :py:class:`Image` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getImage`, :py:meth:`~.DataFile.getImages`, :py:meth:`~.DataFile.getImageIterator`, :py:meth:`~.DataFile.setImage`.\n \n Parameters\n ----------\n filename : string, array_like, optional\n the filename/filenames of the image (including the extension)\n path : string, int, :py:class:`Path`, array_like optional\n the path string, id or entry of the image to insert\n frame : int, array_like, optional\n the number/numbers of frames the images have\n external_id : int, array_like, optional\n an external id/ids for the images. Only necessary if the annotation server is used\n timestamp : datetime object, array_like, optional\n the timestamp/timestamps of the images\n width : int, array_like, optional\n the width/widths of the images\n height : int, optional\n the height/heights of the images\n id : int, array_like, optional\n the id/ids of the images\n layer: int, array_like, optional\n the layer/layers of the images\n \n Returns\n -------\n rows : int\n the number of affected rows.\n \"\"\"\n query = self.table_image.delete()\n layer = self._processLayerNameField(layer)\n path = self._processPathNameField(path)\n query = addFilter(query, id, self.table_image.id)\n query = addFilter(query, path, self.table_image.path)\n query = addFilter(query, filename, self.table_image.filename)\n query = addFilter(query, frame, self.table_image.frame)\n query = addFilter(query, external_id, self.table_image.external_id)\n query = addFilter(query, timestamp, self.table_image.timestamp)\n query = addFilter(query, width, self.table_image.width)\n query = addFilter(query, height, self.table_image.height)\n query = addFilter(query, layer, self.table_image.layer)\n return query.execute()\n ", "context": "class DataFile():\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteImages", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001544.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getMarkerType", "tests": "import unittest\n\nclass Test_getMarkerType(unittest.TestCase):\n def test_setgetMarkerType_Insert(self):\n \"\"\" Test set and get MarkerType - insert variant\"\"\"\n self.db.setMarkerType('rectangle', color='#00ff00', mode=1)\n item = self.db.getMarkerType('rectangle')\n self.assertEqual(item.name, 'rectangle', 'Insert MarkerType - name failed')\n self.assertEqual(item.mode, 1, 'Insert MarkerType - mode failed')\n self.assertEqual(item.color, '#00ff00', 'Insert MarkerType - color failed')\n\n def test_setgetMarkerType_Update(self):\n \"\"\" Test set and get MarkerType - update variant \"\"\"\n self.db.setMarkerType('rectangle', color='#00ff00', mode=1)\n self.db.setMarkerType('rectangle', color='#00ff00')\n item = self.db.getMarkerType('rectangle')\n self.assertEqual(item.name, 'rectangle', 'Update MarkerType - mode failed')\n self.assertEqual(item.mode, 1, 'Update MarkerType - mode failed')\n self.assertEqual(item.color, '#00ff00', 'Update MarkerType - mode failed')\n", "method_code": " def getMarkerType(self, name=None, id=None):\n \"\"\"\n Retrieve an :py:class:`MarkerType` object from the database.\n \n See also: :py:meth:`~.DataFile.getMarkerTypes`, :py:meth:`~.DataFile.setMarkerType`, :py:meth:`~.DataFile.deleteMarkerTypes`.\n \n Parameters\n ----------\n name: str, optional\n the name of the desired type\n id: int, optional\n id of the :py:class:`MarkerType` object\n \n Returns\n -------\n entries : array_like\n the :py:class:`MarkerType` with the desired name or None.\n \"\"\"\n try:\n return self.table_markertype.get(**noNoneDict(name=name, id=id))\n except peewee.DoesNotExist:\n return None\n ", "context": "class DataFile():\n def getMarkerType(self, name=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setgetMarkerType_Insert", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001545.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getMarkerTypes", "tests": "import unittest\n\nclass Test_getMarkerTypes(unittest.TestCase):\n def test_getMarkerTypes(self):\n \"\"\" Test getMarkerTypes to recover a query of all available marker types\"\"\"\n markertypes = ['rectangle', 'default', 'line', 'track']\n self.db.setMarkerType('rectangle', color='#00ff00', mode=1)\n self.db.setMarkerType('default', color='#00ff00', mode=0)\n self.db.setMarkerType('line', color='#00ff00', mode=2)\n self.db.setMarkerType('track', color='#00ff00', mode=4)\n q_markertypes = self.db.getMarkerTypes()\n markertypes_from_db = [q.name for q in q_markertypes]\n self.assertEqual(markertypes, markertypes_from_db, 'getMarkerTypes failed')\n", "method_code": " def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None):\n \"\"\"\n Retreive all :py:class:`MarkerType` objects in the database.\n \n See also: :py:meth:`~.DataFile.getMarkerType`, :py:meth:`~.DataFile.setMarkerType`, :py:meth:`~.DataFile.deleteMarkerTypes`.\n \n Parameters\n ----------\n name: str, array_like, optional\n the name of the type\n color: str, array_like, optional\n hex code string for rgb color of style \"#00ff3f\"\n mode: int, array_like, optional\n mode of the marker type (marker 0, rect 1, line 2, track 4)\n text: str, array_like, optional\n display text\n hidden: bool, array_like, optional\n whether the types should be displayed in ClickPoints\n id: int, array_like, optional\n id of the :py:class:`MarkerType` object\n \n Returns\n -------\n entries : array_like\n a query object which contains all :py:class:`MarkerType` entries.\n \"\"\"\n query = self.table_markertype.select()\n query = addFilter(query, name, self.table_markertype.name)\n query = addFilter(query, color, self.table_markertype.color)\n query = addFilter(query, mode, self.table_markertype.mode)\n query = addFilter(query, text, self.table_markertype.text)\n query = addFilter(query, hidden, self.table_markertype.hidden)\n query = addFilter(query, id, self.table_markertype.id)\n return query\n ", "context": "class DataFile():\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getMarkerTypes", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001546.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteMarkerTypes", "tests": "import unittest\n\nclass Test_deleteMarkerTypes(unittest.TestCase):\n def test_deleteMarkerType(self):\n \"\"\" Test deleteMarkerType to delete marker type instance\"\"\"\n self.db.setMarkerType('rectangle', color='#00ff00', mode=1)\n self.db.setMarkerType('default', color='#00ff00', mode=0)\n self.db.setMarkerType('line', color='#00ff00', mode=2)\n self.db.setMarkerType('track', color='#00ff00', mode=4)\n count = self.db.deleteMarkerTypes('line')\n q_markertypes = self.db.getMarkerTypes()\n markertypes_from_db = [q.name for q in q_markertypes]\n q_markertype = self.db.getMarkerType('line')\n self.assertEqual(count, 1)\n self.assertNotIn('line', markertypes_from_db)\n self.assertIsNone(q_markertype)\n", "method_code": " def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None):\n \"\"\"\n Delete all :py:class:`MarkerType` entries from the database, which match the given criteria.\n \n See also: :py:meth:`~.DataFile.getMarkerType`, :py:meth:`~.DataFile.getMarkerTypes`, :py:meth:`~.DataFile.setMarkerType`.\n \n Parameters\n ----------\n name: str, array_like, optional\n the name of the type\n color: str, array_like, optional\n hex code string for rgb color of style \"#00ff3f\"\n mode: int, array_like, optional\n mode of the marker type (marker 0, rect 1, line 2, track 4)\n text: str, array_like, optional\n display text\n hidden: bool, array_like, optional\n whether the types should be displayed in ClickPoints\n id: int, array_like, optional\n id of the :py:class:`MarkerType` object\n \n Returns\n -------\n entries : int\n nr of deleted entries\n \"\"\"\n query = self.table_markertype.delete()\n query = addFilter(query, name, self.table_markertype.name)\n query = addFilter(query, color, self.table_markertype.color)\n query = addFilter(query, mode, self.table_markertype.mode)\n query = addFilter(query, text, self.table_markertype.text)\n query = addFilter(query, hidden, self.table_markertype.hidden)\n query = addFilter(query, id, self.table_markertype.id)\n return query.execute()\n ", "context": "class DataFile():\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteMarkerType", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001547.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getTrack", "tests": "import unittest\n\nclass Test_getTrack(unittest.TestCase):\n def test_setgetTrack(self):\n \"\"\" Test deleteMarkerType to delete marker type instance\"\"\"\n self.db.setMarkerType('track', color='#00ff00', mode=4)\n self.db.setMarkerType('track2', color='#00ff00', mode=4)\n self.db.setTrack(type='track')\n self.db.setTrack(type='track')\n self.db.setTrack(type='track2')\n q_tracks = self.db.getTracks()\n self.assertEqual(q_tracks.count(), 3, 'Get all Tracks failed')\n q_tracks = self.db.getTracks(type='track')\n self.assertEqual(q_tracks.count(), 2, 'Get specific Tracks by type failed')\n track = self.db.getTrack(id=1)\n self.assertTrue(track.id == 1, 'Get specific track by ID failed')\n track = self.db.getTrack(id=100000)\n self.assertIsNone(track, 'Failing to get specific track by ID failed')\n", "method_code": " def getTrack(self, id):\n \"\"\"\n Get a specific :py:class:`Track` entry by its database ID.\n \n See also: :py:meth:`~.DataFile.getTracks`, :py:meth:`~.DataFile.deleteTracks`, :py:meth:`~.DataFile.getTracksNanPadded`.\n \n Parameters\n ----------\n id: int\n id of the track\n \n Returns\n -------\n entries : :py:class:`Track`\n requested object of class :py:class:`Track` or None\n \"\"\"\n try:\n return self.table_track.get(id=id)\n except peewee.DoesNotExist:\n return None\n ", "context": "class DataFile():\n def getTrack(self, id): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setgetTrack", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001548.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteTracks", "tests": "import unittest\n\nclass Test_deleteTracks(unittest.TestCase):\n def test_deleteTrack(self):\n \"\"\" Test deleteMarkerType to delete marker type instance\"\"\"\n self.db.setMarkerType('track', color='#00ff00', mode=4)\n self.db.setMarkerType('track2', color='#00ff00', mode=4)\n self.db.setMarkerType('track3', color='#00ff00', mode=4)\n self.db.setTrack(type='track')\n self.db.setTrack(type='track')\n self.db.setTrack(type='track2')\n self.db.setTrack(type='track2')\n self.db.setTrack(type='track')\n self.db.setTrack(type='track3')\n self.db.deleteTracks(id=1)\n q_tracks = self.db.getTracks()\n self.assertEqual(q_tracks.count(), 5, 'Failed to delete track by ID')\n self.db.deleteTracks(type='track2')\n q_tracks = self.db.getTracks()\n self.assertEqual(q_tracks.count(), 3, 'Failed to delete track by type')\n self.db.deleteTracks()\n q_tracks = self.db.getTracks()\n self.assertEqual(q_tracks.count(), 0, 'Failed to complete generic delete')\n", "method_code": " def deleteTracks(self, type=None, text=None, hidden=None, id=None):\n \"\"\"\n Delete a single :py:class:`Track` object specified by id or all :py:class:`Track` object of an type\n \n See also: :py:meth:`~.DataFile.getTrack`, :py:meth:`~.DataFile.getTracks`, :py:meth:`~.DataFile.setTrack`, :py:meth:`~.DataFile.getTracksNanPadded`.\n \n Parameters\n ----------\n type: :py:class:`MarkerType`, str, array_like, optional\n the marker type or name of the marker type\n text : str, array_like, optional\n the :py:class:`Track` specific text entry\n hidden : bool, array_like, optional\n whether the tracks should be displayed in ClickPoints\n id : int, array_like, array_like, optional\n the :py:class:`Track` ID\n \n Returns\n -------\n rows : int\n the number of affected rows.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Track'])\n query = self.table_track.delete()\n query = addFilter(query, id, self.table_track.id)\n query = addFilter(query, text, self.table_track.text)\n query = addFilter(query, hidden, self.table_track.hidden)\n query = addFilter(query, type, self.table_track.type)\n return query.execute()\n ", "context": "class DataFile():\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteTrack", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001549.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getMaskType", "tests": "import unittest\n\nclass Test_getMaskType(unittest.TestCase):\n def test_getMaskType(self):\n \"\"\" Test the getMaskType function \"\"\"\n masktype = self.db.getMaskType(name='color')\n self.assertEqual(masktype, None, 'Getting non-existent mask does not work')\n self.db.setMaskType('mask1', '#FF00FF', index=10)\n mask = self.db.getMaskType(color='#ff00FF')\n self.assertIsNotNone(mask, 'Failed retrieving mask type by color')\n", "method_code": " def getMaskType(self, name=None, color=None, index=None, id=None):\n \"\"\"\n Get a :py:class:`MaskType` from the database.\n \n See also: :py:meth:`~.DataFile.getMaskTypes`, :py:meth:`~.DataFile.setMaskType`, :py:meth:`~.DataFile.deleteMaskTypes`.\n \n Parameters\n ----------\n name : string, optional\n the name of the mask type.\n color : string, optional\n the color of the mask type.\n index : int, optional\n the index of the mask type, which is used for painting this mask type.\n id : int, optional\n the id of the mask type.\n \n Returns\n -------\n entries : :py:class:`MaskType`\n the created/requested :py:class:`MaskType` entry.\n \"\"\"\n assert any((e is not None for e in [id, name, color, index])), 'Path, ID, color and index may not be all None'\n if color:\n color = NormalizeColor(color)\n try:\n return self.table_masktype.get(**noNoneDict(id=id, name=name, color=color, index=index))\n except peewee.DoesNotExist:\n return None\n ", "context": "class DataFile():\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getMaskType", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001550.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setMaskType", "tests": "import unittest\n\nclass Test_setMaskType(unittest.TestCase):\n def test_setMaskType(self):\n \"\"\" Test the setMaskType function \"\"\"\n self.db.setMaskType(name='color', color='#FF0000', index=2)\n masktype = self.db.getMaskType(name='color')\n self.assertEqual(masktype.name, 'color', 'Creating a new mask type does not work')\n self.db.setMaskType(id=masktype.id, name='color2', color='#FF0000', index=2)\n masktype = self.db.getMaskType(id=masktype.id)\n self.assertEqual(masktype.name, 'color2', 'Alterning a mask type does not work')\n self.db.setMaskType(name='color3', color='#FF0000')\n self.db.setMaskType(name='color4', color='#FF0000')\n masktype = self.db.setMaskType(name='color5', color='#FF0000')\n self.assertTrue(masktype.index == 4, 'Failed to automatically create correct index entries')\n", "method_code": " def setMaskType(self, name=None, color=None, index=None, id=None):\n \"\"\"\n Update or create a new a :py:class:`MaskType` entry with the given parameters.\n \n See also: :py:meth:`~.DataFile.getMaskType`, :py:meth:`~.DataFile.getMaskTypes`, :py:meth:`~.DataFile.setMaskType`, :py:meth:`~.DataFile.deleteMaskTypes`.\n \n Parameters\n ----------\n name : string, optional\n the name of the mask type.\n color : string, optional\n the color of the mask type.\n index : int, optional\n the index of the mask type, which is used for painting this mask type.\n id : int, optional\n the id of the mask type.\n \n Returns\n -------\n entries : :py:class:`MaskType`\n the changed or created :py:class:`MaskType` entry.\n \"\"\"\n if color:\n color = NormalizeColor(color)\n if not index:\n index_list = [l.index for l in self.table_masktype.select().order_by(self.table_masktype.index)]\n free_idxs = list(set(range(1, 254)) - set(index_list))\n new_index = free_idxs[0]\n else:\n new_index = index\n try:\n if id:\n mask_type = self.table_masktype.get(id=id)\n elif name:\n mask_type = self.table_masktype.get(name=name)\n else:\n raise peewee.DoesNotExist\n if index is None or mask_type.index is not None:\n new_index = mask_type.index\n except peewee.DoesNotExist:\n mask_type = self.table_masktype()\n setFields(mask_type, dict(name=name, color=color, index=new_index))\n mask_type.save()\n return mask_type\n ", "context": "class DataFile():\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setMaskType", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001551.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getMaskTypes", "tests": "import unittest\n\nclass Test_getMaskTypes(unittest.TestCase):\n def test_getMaskTypes(self):\n \"\"\" Test the getMaskTypes function \"\"\"\n self.db.setMaskType(name='color1', color='#FF1c00', index=1)\n self.db.setMaskType(name='color2', color='#FF00ff', index=2)\n self.db.setMaskType(name='color3', color='#FF00FF', index=3)\n self.db.setMaskType(name='color4', color='#FFFFFF', index=4)\n masktypes = self.db.getMaskTypes(name='color1')\n self.assertEqual([m.name for m in masktypes], ['color1'], 'Retrieving one mask type does not work')\n masktypes = self.db.getMaskTypes(name=['color1', 'color2'])\n self.assertEqual([m.name for m in masktypes], ['color1', 'color2'], 'Retrieving two mask types does not work')\n masktypes = self.db.getMaskTypes(color=['#ff00ff', '#ff1c00'])\n self.assertTrue(masktypes.count() == 3, 'Retrieving multiple mask by colors (normalized string) failed')\n", "method_code": " def getMaskTypes(self, name=None, color=None, index=None, id=None):\n \"\"\"\n Get all :py:class:`MaskType` entries from the database, which match the given criteria. If no criteria a given,\n return all mask types.\n \n See also: :py:meth:`~.DataFile.getMaskType`, :py:meth:`~.DataFile.setMaskType`,\n :py:meth:`~.DataFile.deleteMaskTypes`.\n \n Parameters\n ----------\n name : string, array_like, optional\n the name/names of the mask types.\n color : string, array_like, optional\n the color/colors of the mask types.\n index : int, array_like, optional\n the index/indices of the mask types, which is used for painting this mask types.\n id : int, array_like, optional\n the id/ids of the mask types.\n \n Returns\n -------\n entries : array_like\n a query object containing all the matching :py:class:`MaskType` entries in the database file.\n \"\"\"\n query = self.table_masktype.select()\n if color:\n color = NormalizeColor(color)\n query = addFilter(query, id, self.table_masktype.id)\n query = addFilter(query, name, self.table_masktype.name)\n query = addFilter(query, color, self.table_masktype.color)\n query = addFilter(query, index, self.table_masktype.index)\n return query\n ", "context": "class DataFile():\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getMaskTypes", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001552.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteMaskTypes", "tests": "import unittest\n\nclass Test_deleteMaskTypes(unittest.TestCase):\n def test_deleteMaskTypes(self):\n \"\"\" Test the deleteMaskTypes function \"\"\"\n self.db.setMaskType(name='color1', color='#FF0000', index=1)\n self.db.setMaskType(name='color2', color='#FF0000', index=2)\n self.db.setMaskType(name='color3', color='#FF0000', index=3)\n self.db.deleteMaskTypes(name='color1')\n masktypes = self.db.getMaskTypes()\n self.assertEqual(masktypes.count(), 2, 'Deleting one mask type does not work')\n self.db.deleteMaskTypes(name=['color2', 'color3'])\n masktypes = self.db.getMaskTypes()\n self.assertEqual(masktypes.count(), 0, 'Deleting two mask types does not work')\n self.db.setMaskType(name='color1', color='#FF0000', index=1)\n self.db.setMaskType(name='color2', color='#FF0000', index=2)\n self.db.setMaskType(name='color3', color='#FF0000', index=3)\n self.db.deleteMaskTypes(color=['#ff0000'])\n masktypes = self.db.getMaskTypes()\n self.assertEqual(masktypes.count(), 0, 'Failed deleting mask types by color')\n", "method_code": " def deleteMaskTypes(self, name=None, color=None, index=None, id=None):\n \"\"\"\n Delete all :py:class:`MaskType` entries from the database, which match the given criteria.\n \n See also: :py:meth:`~.DataFile.getMaskType`, :py:meth:`~.DataFile.getMaskTypes`, :py:meth:`~.DataFile.setMaskType`.\n \n Parameters\n ----------\n name : string, array_like, optional\n the name/names of the mask types.\n color : string, array_like, optional\n the color/colors of the mask types.\n index : int, array_like, optional\n the index/indices of the mask types, which is used for painting this mask types.\n id : int, array_like, optional\n the id/ids of the mask types.\n \"\"\"\n query = self.table_masktype.delete()\n if color:\n color = NormalizeColor(color)\n query = addFilter(query, id, self.table_masktype.id)\n query = addFilter(query, name, self.table_masktype.name)\n query = addFilter(query, color, self.table_masktype.color)\n query = addFilter(query, index, self.table_masktype.index)\n query.execute()\n ", "context": "class DataFile():\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteMaskTypes", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001553.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setMask", "tests": "import unittest\n\nclass Test_setMask(unittest.TestCase):\n def test_setMask(self):\n \"\"\" Test the setMask function \"\"\"\n im = self.db.setImage(filename='test.jpg', width=100, height=100)\n im2 = self.db.setImage(filename='test2.jpg', width=100, height=100)\n im3 = self.db.setImage(filename='test3.jpg', width=100, height=100)\n masktype = self.db.setMaskType(name='color', color='#FF0000', index=2)\n masktype2 = self.db.setMaskType(name='color2', color='#FF0000')\n mask = self.db.setMask(image=im)\n self.assertTrue(mask.image == im, 'Failed adding a new mask')\n mdata = np.ones((100, 100), dtype='uint8')\n mask = self.db.setMask(image=im, data=mdata)\n mask = self.db.getMask(image=im)\n self.assertTrue(np.array_equal(mask.data, mdata), 'Failed updating mask data')\n mdata = np.ones((100, 100), dtype='int16')\n self.assertRaises(clickpoints.MaskDtypeMismatch, self.db.setMask, image=im, data=mdata)\n mdata = np.ones((100, 50), dtype='uint8')\n self.assertRaises(clickpoints.MaskDimensionMismatch, self.db.setMask, image=im, data=mdata)\n mdata = np.ones((100, 100), dtype='int8')\n self.assertRaises(clickpoints.MaskDtypeMismatch, self.db.setMask, image=im2, data=mdata)\n mdata = np.ones((100, 50), dtype='uint8')\n self.assertRaises(clickpoints.MaskDimensionMismatch, self.db.setMask, image=im3, data=mdata)\n", "method_code": " def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False):\n \"\"\"\n Update or create new :py:class:`Mask` entry with the given parameters.\n \n See also: :py:meth:`~.DataFile.getMask`, :py:meth:`~.DataFile.getMasks`, :py:meth:`~.DataFile.deleteMasks`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, optional\n the image for which the mask should be set. If omitted, frame number or filename should be specified instead.\n frame: int, optional\n frame number of the images, which masks should be set. If omitted, image or filename should be specified instead.\n filename: string, optional\n filename of the image, which masks should be set. If omitted, image or frame number should be specified instead.\n data: ndarray, optional\n the mask data of the mask to set. Must have the same dimensions as the corresponding image, but only\n one channel, and it should be using the data type uint8.\n id : int, optional\n id of the mask entry.\n layer: int, optional\n the layer of the image, which masks should be set. always use with frame.\n checkShape: bool, optional\n check if the maks and image have the same shape\n \n Returns\n -------\n mask : :py:class:`Mask`\n the changed or created :py:class:`Mask` entry.\n \"\"\"\n assert sum((e is not None for e in [id, image, frame, filename])) == 1, 'Exactly one of image, frame or filename should be specified or an id'\n if layer is not None:\n assert frame is not None, 'Frame should be specified, if layer is given.'\n image = self._processImagesField(image, frame, filename, layer)\n mask = self.getMask(image=image, filename=filename, id=id)\n if not image:\n image = self.getImage(frame=frame, filename=filename, layer=layer)\n if not image:\n raise ImageDoesNotExist('No matching parent image found (%s)' % filename)\n if data is not None:\n if not data.dtype == np.uint8:\n raise MaskDtypeMismatch('mask.data dtype is not of type uint8')\n if checkShape:\n try:\n if not tuple(data.shape) == image.getShape():\n raise MaskDimensionMismatch(\"mask.data shape doesn't match image dimensions!\")\n except IOError:\n UserWarning(\"Couldn't retrieve image dimension - shape verification not possible \")\n if not mask:\n if data is None:\n try:\n data = np.zeros(image.getShape())\n except IOError:\n raise MaskDimensionUnknown(\"Can't retreive dimensions for mask from image %s \" % image.filename)\n else:\n if not data.dtype == np.uint8:\n raise MaskDtypeMismatch('mask.data dtype is not of type uint8')\n if checkShape:\n try:\n if not tuple(data.shape) == image.getShape():\n raise MaskDimensionMismatch(\"mask.data shape doesn't match image dimensions!\")\n except IOError:\n UserWarning(\"Couldn't retrieve image dimension - shape verification not possible \")\n mask = self.table_mask(image=image, data=data)\n setFields(mask, dict(data=data, image=image))\n if frame is not None or filename is not None:\n mask.image = self.getImage(frame=frame, filename=filename, layer=layer)\n mask.save()\n return mask\n ", "context": "class DataFile():\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setMask", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001554.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getMask", "tests": "import unittest\n\nclass Test_getMask(unittest.TestCase):\n def test_getMask(self):\n im1 = self.db.setImage(filename='test1.jpg', width=100, height=100)\n im2 = self.db.setImage(filename='test2.jpg', width=100, height=100)\n im3 = self.db.setImage(filename='test3.jpg', width=100, height=100)\n im4 = self.db.setImage(filename='test4.jpg', width=100, height=100)\n im5 = self.db.setImage(filename='test5.jpg')\n mask = self.db.setMask(image=im1)\n mask = self.db.setMask(image=im2)\n mask = self.db.getMask(filename='test2.jpg')\n self.assertTrue(mask.image.filename == im2.filename, 'Failed retrieving mask by image filename')\n mask = self.db.getMask(filename='test3.jpg', create=True)\n self.assertTrue(mask.image.filename == 'test3.jpg', 'Failed creating mask on getMask')\n mask = self.db.getMask(image=im4, create=True)\n self.assertTrue(mask.image.filename == 'test4.jpg', 'Failed creating mask on getMask')\n self.assertRaises(clickpoints.ImageDoesNotExist, self.db.getMask, filename='testDOESNTEXIST.jpg', create=True)\n self.assertRaises(clickpoints.MaskDimensionUnknown, self.db.getMask, image=im5, create=True)\n", "method_code": " def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False):\n \"\"\"\n Get the :py:class:`Mask` entry for the given image frame number or filename.\n \n See also: :py:meth:`~.DataFile.getMasks`, :py:meth:`~.DataFile.setMask`, :py:meth:`~.DataFile.deleteMasks`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, optional\n the image for which the mask should be retrieved. If omitted, frame number or filename should be specified instead.\n frame : int, optional\n frame number of the image, which mask should be returned. If omitted, image or filename should be specified instead.\n filename : string, optional\n filename of the image, which mask should be returned. If omitted, image or frame number should be specified instead.\n id : int, optional\n id of the mask entry.\n create : bool, optional\n whether the mask should be created if it does not exist. (default: False)\n layer: int, optional\n layer of the image, which mask should be returned. Always use with frame.\n \n Returns\n -------\n mask : :py:class:`Mask`\n the desired :py:class:`Mask` entry.\n \"\"\"\n assert sum((e is not None for e in [id, image, frame, filename])) == 1, \"Image, frame (with layer) or filename should be specified or should be referenced by it's id.\"\n image = self._processImagesField(image, frame, filename, layer)\n query = self.table_mask.select(self.table_mask, self.table_image).join(self.table_image)\n query = addFilter(query, id, self.table_mask.id)\n query = addFilter(query, image, self.table_mask.image)\n query = addFilter(query, frame, self.table_image.sort_index)\n query = addFilter(query, filename, self.table_image.filename)\n query = addFilter(query, layer, self.table_image.layer)\n query.limit(1)\n try:\n return query[0]\n except IndexError:\n if create is True:\n if not image:\n image = self.getImage(frame=frame, filename=filename, layer=layer)\n if not image:\n raise ImageDoesNotExist('No parent image found ')\n try:\n data = np.zeros(image.getShape())\n except IOError:\n raise MaskDimensionUnknown(\"Can't retrieve dimensions for mask from image %s \" % image.filename)\n mask = self.table_mask(image=image, data=data)\n mask.save()\n return mask\n return None\n ", "context": "class DataFile():\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getMask", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001555.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getMasks", "tests": "import unittest\n\nclass Test_getMasks(unittest.TestCase):\n def test_getMasks(self):\n im1 = self.db.setImage(filename='test1.jpg', width=100, height=100)\n im2 = self.db.setImage(filename='test2.jpg', width=100, height=100)\n im3 = self.db.setImage(filename='test3.jpg', width=100, height=100)\n mask = self.db.setMask(image=im1)\n mask = self.db.setMask(image=im2)\n mask = self.db.setMask(image=im3)\n masks = self.db.getMasks()\n self.assertTrue(masks.count() == 3, 'Failed to retrieve all masks without parameter')\n masks = self.db.getMasks(image=[im1, im2])\n self.assertTrue(masks.count() == 2, 'Failed to retrieve masks by images ')\n masks = self.db.getMasks(frame=[1, 2])\n self.assertTrue(masks.count() == 2, 'Failed to retrieve masks by frames ')\n masks = self.db.getMasks(filename=['test1.jpg', 'test3.jpg'])\n self.assertTrue(masks.count() == 2, 'Failed to retrieve masks by filenames ')\n masks = self.db.getMasks(frame=[0, 2])\n self.assertTrue(masks.count() == 2, 'Failed to retrieve masks by ids ')\n", "method_code": " def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'):\n \"\"\"\n Get all :py:class:`Mask` entries from the database, which match the given criteria. If no criteria a given, return all masks.\n \n See also: :py:meth:`~.DataFile.getMask`, :py:meth:`~.DataFile.setMask`, :py:meth:`~.DataFile.deleteMasks`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/images for which the mask should be retrieved. If omitted, frame numbers or filenames should be specified instead.\n frame: int, array_like, optional\n frame number/numbers of the images, which masks should be returned. If omitted, images or filenames should be specified instead.\n filename: string, array_like, optional\n filename of the image/images, which masks should be returned. If omitted, images or frame numbers should be specified instead.\n id : int, array_like, optional\n id/ids of the masks.\n layer : int, optional\n layer of the images, which masks should be returned. Always use with frame.\n order_by: string, optional\n sorts the result according to sort paramter ('sort_index' or 'timestamp')\n \n Returns\n -------\n entries : :py:class:`Mask`\n a query object containing all the matching :py:class:`Mask` entries in the database file.\n \"\"\"\n assert sum((e is not None for e in [image, frame, filename])) <= 1, 'Exactly one of images, frames or filenames should be specified'\n if layer is not None:\n assert frame is not None, 'Frame should be specified, if layer is given.'\n image = self._processImagesField(image, frame, filename, layer)\n query = self.table_mask.select(self.table_mask, self.table_image).join(self.table_image)\n query = addFilter(query, id, self.table_mask.id)\n query = addFilter(query, image, self.table_mask.image)\n query = addFilter(query, frame, self.table_image.sort_index)\n query = addFilter(query, filename, self.table_image.filename)\n query = addFilter(query, layer, self.table_image.layer)\n if order_by == 'sort_index':\n query = query.order_by(self.table_image.sort_index)\n elif order_by == 'timestamp':\n query = query.order_by(self.table_image.timestamp)\n else:\n raise Exception('Unknown order_by parameter - use sort_index or timestamp')\n \n class QuerySelector(type(query)):\n \n def __iter__(self):\n return self.iterator()\n query.__class__ = QuerySelector\n return query\n ", "context": "class DataFile():\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getMasks", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001556.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteMasks", "tests": "import unittest\n\nclass Test_deleteMasks(unittest.TestCase):\n def test_deleteMasks(self):\n \"\"\" test delete masks function \"\"\"\n im1 = self.db.setImage(filename='test1.jpg', width=100, height=100)\n im2 = self.db.setImage(filename='test2.jpg', width=100, height=100)\n im3 = self.db.setImage(filename='test3.jpg', width=100, height=100)\n mask = self.db.setMask(image=im1)\n mask = self.db.setMask(image=im2)\n mask = self.db.setMask(image=im3)\n self.db.deleteMasks(image=im1)\n masks = self.db.getMasks()\n self.assertTrue(masks.count() == 2, 'Failed to to delete single mask by image')\n self.db.deleteMasks(filename='test3.jpg')\n masks = self.db.getMasks()\n self.assertTrue(masks.count() == 1, 'Failed to to delete single mask by image')\n self.db.deleteMasks()\n masks = self.db.getMasks()\n self.assertTrue(masks.count() == 0, 'Failed to to delete all masks')\n", "method_code": " def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None):\n \"\"\"\n Delete all :py:class:`Mask` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getMask`, :py:meth:`~.DataFile.getMasks`, :py:meth:`~.DataFile.setMask`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/images for which the mask should be deleted. If omitted, frame numbers or filenames should be specified instead.\n frame: int, array_like, optional\n frame number/numbers of the images, which masks should be deleted. If omitted, images or filenames should be specified instead.\n filename: string, array_like, optional\n filename of the image/images, which masks should be deleted. If omitted, images or frame numbers should be specified instead.\n id : int, array_like, optional\n id/ids of the masks.\n layer: int, array_like, optional\n layer/layers of the images, which masks should be deleted. Always use with frame!\n \"\"\"\n assert sum((e is not None for e in [image, frame, filename])) <= 1, 'Exactly one of images, frames or filenames should be specified'\n if layer is not None:\n assert frame is not None, 'Frame should be specified, if layer is given.'\n query = self.table_mask.delete()\n if image is None:\n images = self.table_image.select()\n images = addFilter(images, frame, self.table_image.sort_index)\n images = addFilter(images, filename, self.table_image.filename)\n images = addFilter(images, layer, self.table_image.layer)\n query = query.where(self.table_mask.image.in_(images))\n else:\n query = addFilter(query, image, self.table_mask.image)\n query = addFilter(query, id, self.table_mask.id)\n query.execute()\n ", "context": "class DataFile():\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteMasks", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001557.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setMarker", "tests": "import unittest\n\nclass Test_setMarker(unittest.TestCase):\n def test_setMarker(self):\n \"\"\" Test the setMarker function \"\"\"\n marker_type = self.db.setMarkerType(name='Test', color='#FF0000')\n image = self.db.setImage('test.jpg')\n marker = self.db.setMarker(image=image.id, x=123, y=0, type=marker_type)\n self.assertEqual(marker.x, 123, 'Setting marker does not work properly.')\n marker = self.db.setMarker(filename='test.jpg', x=123, y=20, type='Test')\n self.assertEqual(marker.x, 123, 'Setting marker does not work properly.')\n marker = self.db.setMarker(frame=0, x=123, y=0, type=marker_type)\n self.assertEqual(marker.x, 123, 'Setting marker does not work properly.')\n marker = self.db.setMarker(x=123, y=0, id=marker)\n self.assertEqual(marker.x, 123, 'Setting marker does not work properly.')\n self.assertRaises(clickpoints.ImageDoesNotExist, self.db.setMarker, frame=1, x=123, y=0, type=marker_type)\n self.assertRaises(clickpoints.ImageDoesNotExist, self.db.setMarker, filename='no.jpg', x=123, y=0, type=marker_type)\n self.assertRaises(clickpoints.MarkerTypeDoesNotExist, self.db.setMarker, image=1, x=123, y=0, type='NoType')\n self.assertRaises(AssertionError, self.db.setMarker, x=123, y=0)\n self.assertRaises(AssertionError, self.db.setMarker, x=123, y=0, type=marker_type)\n", "method_code": " def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None):\n \"\"\"\n Insert or update an :py:class:`Marker` object in the database.\n \n See also: :py:meth:`~.DataFile.getMarker`, :py:meth:`~.DataFile.getMarkers`, :py:meth:`~.DataFile.setMarkers`,\n :py:meth:`~.DataFile.deleteMarkers`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, optional\n the image of the marker.\n frame : int, optional\n the frame of the images of the marker.\n filename : string, optional\n the filename of the image of the marker.\n x : int, optional\n the x coordinate of the marker.\n y : int, optional\n the y coordinate of the marker.\n type : string, :py:class:`MarkerType`, optional\n the marker type (or name) of the marker.\n processed : int, optional\n the processed flag of the marker.\n track : int, :py:class:`Track`, optional\n the track id or instance of the marker.\n text : string, optional\n the text of the marker.\n id : int, optional\n the id of the marker.\n layer: int, optional\n the layer of the image of the marker\n \n Returns\n -------\n marker : :py:class:`Marker`\n the created or changed :py:class:`Marker` item.\n \"\"\"\n assert not (id is None and type is None and (track is None)), \"Marker must either have a type or a track or be referenced by it's id.\"\n assert not (id is None and image is None and (frame is None) and (filename is None)), \"Marker must have an image, frame or filename given or be referenced by it's id.\"\n try:\n item = self.table_marker.get(id=id)\n except peewee.DoesNotExist:\n item = self.table_marker()\n type = self._processesTypeNameField(type, ['TYPE_Normal', 'TYPE_Track'])\n if track is not None:\n self._checkTrackField(track)\n image = self._processImagesField(image, frame, filename, layer)\n setFields(item, dict(image=image, x=x, y=y, type=type, processed=processed, track=track, style=style, text=text))\n item.save()\n return item\n ", "context": "class DataFile():\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setMarker", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001558.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getMarker", "tests": "import unittest\n\nclass Test_getMarker(unittest.TestCase):\n def test_getMarker(self):\n \"\"\" Test the getMarker function \"\"\"\n marker_type1 = self.db.setMarkerType(name='Test1', color='#FF0000')\n image1 = self.db.setImage('test1.jpg')\n self.db.setMarker(image=image1, x=456, y=2, type=marker_type1)\n marker = self.db.getMarker(id=1)\n self.assertEqual(marker.x, 456, 'Getting marker does not work properly.')\n marker = self.db.getMarker(id=0)\n self.assertEqual(marker, None, 'Getting marker does not work properly.')\n", "method_code": " def getMarker(self, id):\n \"\"\"\n Retrieve an :py:class:`Marker` object from the database.\n \n See also: :py:meth:`~.DataFile.getMarkers`, :py:meth:`~.DataFile.setMarker`, :py:meth:`~.DataFile.setMarkers`,\n :py:meth:`~.DataFile.deleteMarkers`.\n \n Parameters\n ----------\n id: int\n the id of the marker\n \n Returns\n -------\n marker : :py:class:`Marker`\n the :py:class:`Marker` with the desired id or None.\n \"\"\"\n try:\n return self.table_marker.get(id=id)\n except peewee.DoesNotExist:\n return None\n ", "context": "class DataFile():\n def getMarker(self, id): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getMarker", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001559.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getMarkers", "tests": "import unittest\n\nclass Test_getMarkers(unittest.TestCase):\n def test_getMarkers(self):\n \"\"\" Test the getMarker function \"\"\"\n marker_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Track)\n marker_type2 = self.db.setMarkerType(name='Test2', color='#00FF00', mode=self.db.TYPE_Track)\n marker_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Track)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n track1 = self.db.setTrack(marker_type3)\n track2 = self.db.setTrack(marker_type3)\n self.db.setMarkers(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], type=marker_type1)\n self.db.setMarkers(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], type=marker_type2)\n self.db.setMarkers(image=image2, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], type=marker_type1)\n self.db.setMarkers(image=[image3, image4], x=[10, 20], y=[0, 0], track=track1)\n self.db.setMarkers(image=[image3, image4], x=[10, 20], y=[0, 0], track=track2)\n markers = self.db.getMarkers(image=[image1, image2])\n self.assertEqual(markers.count(), 15, 'Getting markers does not work properly.')\n markers = self.db.getMarkers(image=image1)\n self.assertEqual(markers.count(), 10, 'Getting markers does not work properly.')\n markers = self.db.getMarkers(frame=0)\n self.assertEqual(markers.count(), 10, 'Getting markers does not work properly.')\n markers = self.db.getMarkers(filename=['test1.jpg', 'test2.jpg'])\n self.assertEqual(markers.count(), 15, 'Getting markers does not work properly.')\n markers = self.db.getMarkers(x=[2, 3])\n self.assertEqual(markers.count(), 6, 'Getting markers does not work properly.')\n markers = self.db.getMarkers(x=[2, 3], y=[0, 1, 2])\n self.assertEqual(markers.count(), 6, 'Getting markers does not work properly.')\n markers = self.db.getMarkers(type=marker_type1)\n self.assertEqual(markers.count(), 10, 'Getting markers does not work properly.')\n markers = self.db.getMarkers(type=['Test1', 'Test2'])\n self.assertEqual(markers.count(), 15, 'Getting markers does not work properly.')\n self.assertRaises(clickpoints.MarkerTypeDoesNotExist, self.db.getMarkers, type=['NoType'])\n markers = self.db.getMarkers(track=track1)\n self.assertEqual(markers.count(), 2, 'Getting markers does not work properly.')\n", "method_code": " def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None):\n \"\"\"\n Get all :py:class:`Marker` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getMarker`, :py:meth:`~.DataFile.getMarkers`, :py:meth:`~.DataFile.setMarker`, :py:meth:`~.DataFile.setMarkers`, :py:meth:`~.DataFile.deleteMarkers`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the markers.\n frame : int, array_like, optional\n the frame/s of the images of the markers.\n filename : string, array_like, optional\n the filename/s of the images of the markers.\n x : int, array_like, optional\n the x coordinate/s of the markers.\n y : int, array_like, optional\n the y coordinate/s of the markers.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the markers.\n processed : int, array_like, optional\n the processed flag/s of the markers.\n track : int, :py:class:`Track`, array_like, optional\n the track id/s or instance/s of the markers.\n text : string, array_like, optional\n the text/s of the markers.\n id : int, array_like, optional\n the id/s of the markers.\n layer : int, optional\n the layer of the markers\n \n Returns\n -------\n entries : array_like\n a query object which contains all :py:class:`Marker` entries.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Normal', 'TYPE_Track'])\n query = self.table_marker.select(self.table_marker, self.table_image).join(self.table_image)\n image = self._processImagesField(image, frame, filename, layer)\n query = addFilter(query, id, self.table_marker.id)\n query = addFilter(query, image, self.table_marker.image)\n query = addFilter(query, frame, self.table_image.sort_index)\n query = addFilter(query, layer, self.table_image.layer)\n query = addFilter(query, filename, self.table_image.filename)\n query = addFilter(query, x, self.table_marker.x)\n query = addFilter(query, y, self.table_marker.y)\n query = addFilter(query, type, self.table_marker.type)\n query = addFilter(query, processed, self.table_marker.processed)\n query = addFilter(query, track, self.table_marker.track)\n query = addFilter(query, text, self.table_marker.text)\n query.__array__ = lambda: np.array([p.pos() for p in query])\n return query\n ", "context": "class DataFile():\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getMarkers", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001560.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setMarkers", "tests": "import unittest\n\nclass Test_setMarkers(unittest.TestCase):\n def test_setMarkers(self):\n \"\"\" Test the setMarkers function \"\"\"\n marker_type1 = self.db.setMarkerType(name='Test1', color='#FF0000')\n marker_type2 = self.db.setMarkerType(name='Test2', color='#00FF00')\n marker_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Track)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n track1 = self.db.setTrack(marker_type3)\n track2 = self.db.setTrack(marker_type3)\n self.db.setMarkers(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], type=marker_type1)\n self.assertEqual(self.db.getMarkers().count(), 5, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n self.db.setMarkers(image=[image1, image2], x=[1, 2], y=[0, 0], type=marker_type1)\n self.assertEqual(self.db.getMarkers().count(), 2, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n self.db.setMarkers(image=image1, x=1, y=0, type=[marker_type1, marker_type2])\n self.assertEqual(self.db.getMarkers().count(), 2, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n self.db.setMarkers(image=image1, x=1, y=0, type=marker_type1, text=['foo', 'bar', 'hu'], style='{}')\n self.assertEqual(self.db.getMarkers().count(), 3, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n self.db.setMarkers(filename='test2.jpg', x=1, y=0, type=marker_type2)\n self.assertEqual(self.db.getMarkers().count(), 1, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n self.db.setMarkers(frame=[0, 1, 2], x=1, y=0, type=marker_type2)\n self.assertEqual(self.db.getMarkers().count(), 3, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n self.db.setMarkers(frame=0, x=1, y=0, track=track1)\n self.assertEqual(self.db.getMarkers().count(), 1, 'Setting markers does not work properly.')\n ms = self.db.getMarkers(track=track1)\n for m in ms:\n print('a', m)\n self.db.setMarkers(frame=0, processed=1, track=track1)\n ms = self.db.getMarkers(track=track1)\n for m in ms:\n print('b', m)\n self.assertEqual(self.db.getMarkers().count(), 1, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n track1 = self.db.setTrack(marker_type3)\n track2 = self.db.setTrack(marker_type3)\n self.db.setMarkers(image=image1, x=np.array([1, 2]), y=np.array([10, 20]), track=[track1, track2])\n self.assertEqual(sum((m.processed == 0 for m in self.db.getMarkers(image=image1))), 2, 'Setting markers does not work properly.')\n self.db.setMarkers(frame=0, processed=1, track=[track1, track2])\n self.assertEqual(sum((m.processed == 1 for m in self.db.getMarkers(image=image1))), 2, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n track2 = self.db.setTrack(marker_type3)\n self.db.setMarkers(image=image1, x=[0, 1, 2], y=0, track=track2)\n self.assertEqual(self.db.getMarkers().count(), 1, 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n self.db.setMarkers(image=image1, x=[0, 1, 2], y=[0, 1, 2], type=marker_type1)\n markers = self.db.getMarkers()\n self.assertTrue(all((m.x < 10 for m in markers)), 'Setting markers does not work properly.')\n self.db.setMarkers(x=[10, 20, 30], y=[0, 1, 2], id=[m for m in markers])\n markers = self.db.getMarkers()\n self.assertTrue(all((m.x >= 10 for m in markers)), 'Setting markers does not work properly.')\n self.db.deleteMarkers()\n self.db.setMarkers(image=image1, x=np.arange(0, 10000), y=0)\n self.assertEqual(self.db.getMarkers().count(), 10000, 'Setting markers does not work properly.')\n", "method_code": " def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None):\n \"\"\"\n Insert or update multiple :py:class:`Marker` objects in the database.\n \n See also: :py:meth:`~.DataFile.getMarker`, :py:meth:`~.DataFile.getMarkers`, :py:meth:`~.DataFile.setMarker`,\n :py:meth:`~.DataFile.deleteMarkers`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the markers.\n frame : int, array_like, optional\n the frame/s of the images of the markers.\n filename : string, array_like, optional\n the filename/s of the images of the markers.\n x : int, array_like, optional\n the x coordinate/s of the markers.\n y : int, array_like, optional\n the y coordinate/s of the markers.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the markers.\n processed : int, array_like, optional\n the processed flag/s of the markers.\n track : int, :py:class:`Track`, array_like, optional\n the track id/s or instance/s of the markers.\n text : string, array_like, optional\n the text/s of the markers.\n id : int, array_like, optional\n the id/s of the markers.\n layer: int, optional\n the layer of the images\n \n Returns\n -------\n success : bool\n it the inserting was successful.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Normal', 'TYPE_Track'])\n if track is not None:\n self._checkTrackField(track)\n image = self._processImagesField(image, frame, filename, layer)\n data = packToDictList(self.table_marker, id=id, image=image, x=x, y=y, processed=processed, type=type, track=track, style=style, text=text)\n return self.saveReplaceMany(self.table_marker, data)\n ", "context": "class DataFile():\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setMarkers", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_001561.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteMarkers", "tests": "import unittest\n\nclass Test_deleteMarkers(unittest.TestCase):\n def test_deleteMarkers(self):\n \"\"\" Test the deleteMarkers function \"\"\"\n marker_type1 = self.db.setMarkerType(name='Test1', color='#FF0000')\n marker_type2 = self.db.setMarkerType(name='Test2', color='#00FF00')\n marker_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Track)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n track1 = None\n track2 = None\n\n def CreateMarkers():\n global track1, track2\n self.db.deleteMarkers()\n self.db.deleteTracks()\n track1 = self.db.setTrack(marker_type3)\n track2 = self.db.setTrack(marker_type3)\n self.db.setMarkers(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], type=marker_type1)\n self.db.setMarkers(image=image2, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], processed=True, text='foo', type=marker_type1)\n self.db.setMarkers(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], text='bar', type=marker_type2)\n self.db.setMarkers(image=[image1, image2, image3, image4], x=1, y=3, track=track1)\n CreateMarkers()\n self.db.deleteMarkers(image=image1)\n self.assertEqual(self.db.getMarkers().count(), 8, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n self.db.deleteMarkers(image=[image1, image2])\n self.assertEqual(self.db.getMarkers().count(), 2, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n self.db.deleteMarkers(filename='test2.jpg')\n self.assertEqual(self.db.getMarkers().count(), 13, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n self.db.deleteMarkers(frame=1)\n self.assertEqual(self.db.getMarkers().count(), 13, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n self.db.deleteMarkers(x=slice(2, 4))\n self.assertEqual(self.db.getMarkers().count(), 10, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n self.db.deleteMarkers(processed=True)\n self.assertEqual(self.db.getMarkers().count(), 14, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n self.db.deleteMarkers(text='foo')\n self.assertEqual(self.db.getMarkers().count(), 14, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n ids = [m.id for m in self.db.getMarkers(text='foo')]\n self.db.deleteMarkers(id=ids)\n self.assertEqual(self.db.getMarkers().count(), 14, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n self.db.deleteMarkers(track=self.db.getTracks())\n self.assertEqual(self.db.getMarkers().count(), 15, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n CreateMarkers()\n self.db.deleteMarkers(type='Test1')\n self.assertEqual(self.db.getMarkers().count(), 9, 'Deleting markers does not work properly.')\n self.db.deleteMarkers()\n for marker in self.db.getMarkers():\n print(marker)\n marker.print_details()\n", "method_code": " def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None):\n \"\"\"\n Delete all :py:class:`Marker` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getMarker`, :py:meth:`~.DataFile.getMarkers`, :py:meth:`~.DataFile.setMarker`,\n :py:meth:`~.DataFile.setMarkers`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the markers.\n frame : int, array_like, optional\n the frame/s of the images of the markers.\n filename : string, array_like, optional\n the filename/s of the images of the markers.\n x : int, array_like, optional\n the x coordinate/s of the markers.\n y : int, array_like, optional\n the y coordinate/s of the markers.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the markers.\n processed : int, array_like, optional\n the processed flag/s of the markers.\n track : int, :py:class:`Track`, array_like, optional\n the track id/s or instance/s of the markers.\n text : string, array_like, optional\n the text/s of the markers.\n id : int, array_like, optional\n the id/s of the markers.\n \n Returns\n -------\n rows : int\n the number of affected rows.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Normal', 'TYPE_Track'])\n query = self.table_marker.delete()\n image = self._processImagesField(image, frame, filename, layer)\n if image is None and (frame is not None or filename is not None):\n images = self.table_image.select(self.table_image.id)\n images = addFilter(images, frame, self.table_image.sort_index)\n images = addFilter(images, filename, self.table_image.filename)\n query = query.where(self.table_marker.image.in_(images))\n else:\n query = addFilter(query, image, self.table_marker.image)\n query = addFilter(query, id, self.table_marker.id)\n query = addFilter(query, x, self.table_marker.x)\n query = addFilter(query, y, self.table_marker.y)\n query = addFilter(query, type, self.table_marker.type)\n query = addFilter(query, processed, self.table_marker.processed)\n query = addFilter(query, track, self.table_marker.track)\n query = addFilter(query, text, self.table_marker.text)\n return query.execute()\n ", "context": "class DataFile():\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteMarkers", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_001562.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setLine", "tests": "import unittest\n\nclass Test_setLine(unittest.TestCase):\n def test_setLine(self):\n \"\"\" Test the setLine function \"\"\"\n Line_type = self.db.setMarkerType(name='Test', color='#FF0000', mode=self.db.TYPE_Line)\n image = self.db.setImage('test.jpg')\n Line = self.db.setLine(image=image.id, x1=123, y1=0, x2=10, y2=10, type=Line_type)\n self.assertEqual(Line.x1, 123, 'Setting Line does not work properly.')\n Line = self.db.setLine(filename='test.jpg', x1=123, y1=0, x2=10, y2=10, type='Test')\n self.assertEqual(Line.x1, 123, 'Setting Line does not work properly.')\n Line = self.db.setLine(frame=0, x1=123, y1=0, x2=10, y2=10, type=Line_type)\n self.assertEqual(Line.x1, 123, 'Setting Line does not work properly.')\n Line = self.db.setLine(x1=123, y1=0, x2=10, y2=10, id=Line)\n self.assertEqual(Line.x1, 123, 'Setting Line does not work properly.')\n self.assertRaises(clickpoints.ImageDoesNotExist, self.db.setLine, frame=1, x1=123, y1=0, x2=10, y2=10, type=Line_type)\n self.assertRaises(clickpoints.ImageDoesNotExist, self.db.setLine, filename='no.jpg', x1=123, y1=0, x2=10, y2=10, type=Line_type)\n self.assertRaises(clickpoints.MarkerTypeDoesNotExist, self.db.setLine, image=1, x1=123, y1=0, x2=10, y2=10, type='NoType')\n self.assertRaises(AssertionError, self.db.setLine, x1=123, y1=0, x2=10, y2=10)\n self.assertRaises(AssertionError, self.db.setLine, x1=123, y1=0, x2=10, y2=10, type=Line_type)\n", "method_code": " def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None):\n \"\"\"\n Insert or update an :py:class:`Line` object in the database.\n \n See also: :py:meth:`~.DataFile.getLine`, :py:meth:`~.DataFile.getLines`, :py:meth:`~.DataFile.setLines`,\n :py:meth:`~.DataFile.deleteLines`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, optional\n the image of the line.\n frame : int, optional\n the frame of the images of the line.\n filename : string, optional\n the filename of the image of the line.\n x1 : int, optional\n the x coordinate of the start of the line.\n y1 : int, optional\n the y coordinate of the start of the line.\n x2 : int, optional\n the x coordinate of the end of the line.\n y2 : int, optional\n the y coordinate of the end of the line.\n type : string, :py:class:`MarkerType`, optional\n the marker type (or name) of the line.\n processed : int, optional\n the processed flag of the line.\n text : string, optional\n the text of the line.\n id : int, optional\n the id of the line.\n layer : int, optional\n the layer of the image of the line\n \n Returns\n -------\n line : :py:class:`Line`\n the created or changed :py:class:`Line` item.\n \"\"\"\n assert not (id is None and type is None), \"Line must either have a type or be referenced by it's id.\"\n assert not (id is None and image is None and (frame is None) and (filename is None)), \"Line must have an image, frame or filename given or be referenced by it's id.\"\n try:\n item = self.table_line.get(id=id)\n except peewee.DoesNotExist:\n item = self.table_line()\n type = self._processesTypeNameField(type, ['TYPE_Line'])\n image = self._processImagesField(image, frame, filename, layer)\n setFields(item, dict(image=image, x1=x1, y1=y1, x2=x2, y2=y2, type=type, processed=processed, style=style, text=text))\n item.save()\n return item\n ", "context": "class DataFile():\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setLine", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001563.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getLine", "tests": "import unittest\n\nclass Test_getLine(unittest.TestCase):\n def test_getLine(self):\n \"\"\" Test the getLine function \"\"\"\n Line_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Line)\n image1 = self.db.setImage('test1.jpg')\n self.db.setLine(image=image1, x1=456, y1=0, x2=10, y2=10, type=Line_type1)\n Line = self.db.getLine(id=1)\n self.assertEqual(Line.x1, 456, 'Getting Line does not work properly.')\n Line = self.db.getLine(id=0)\n self.assertEqual(Line, None, 'Getting Line does not work properly.')\n", "method_code": "def getLine(image, line, width=None):\n line = np.array(line)\n x1, y1 = line[0]\n x2, y2 = line[1]\n w = x2 - x1\n h = y2 - y1\n length = np.sqrt(w ** 2 + h ** 2)\n w2 = h / length\n h2 = -w / length\n offset = getattr(image, 'offset', None)\n if offset is not None:\n offx, offy = (offset.x, offset.y)\n else:\n offx, offy = (0, 0)\n x1 -= offx\n y1 -= offy\n data = getattr(image, 'data', None)\n image = data if data is not None else image\n if width is None:\n width = 1\n return_1d = True\n else:\n return_1d = False\n datas = []\n for j in np.arange(0, width) - width / 2.0 + 0.5:\n data = []\n for i in np.linspace(0, 1, np.ceil(length)):\n x = x1 + w * i + w2 * j\n y = y1 + h * i + h2 * j\n xp = x - np.floor(x)\n yp = y - np.floor(y)\n x, y = (int(x), int(y))\n v = np.array([[1 - yp, yp]]).T @ np.array([[1 - xp, xp]])\n if len(image.shape) == 3:\n data.append(np.sum(image[y:y + 2, x:x + 2, :] * v[:, :, None], axis=(0, 1), dtype=image.dtype))\n else:\n data.append(np.sum(image[y:y + 2, x:x + 2] * v, dtype=image.dtype))\n datas.append(data)\n if return_1d:\n return np.array(datas[0])\n return np.array(datas)[::-1, :]", "context": "def getLine(image, line, width=None): ...\ndef dict_factory(cursor, row): ...\ndef CheckValidColor(color): ...\ndef NormalizeColor(color): ...\ndef HTMLColorToRGB(colorstring): ...\ndef addFilter(query, parameter, field): ...\ndef noNoneDict(**kwargs): ...\ndef setFields(entry, dict): ...\ndef packToDictList(table, **kwargs): ...\ndef VerboseDict(dictionary): ...\ndef GetCommandLineArgs(): ...\ndef getLine(image, line, width=None): ...\n", "repository": "fabrylab/clickpoints", "test_name": "test_getLine", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001564.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getLines", "tests": "import unittest\n\nclass Test_getLines(unittest.TestCase):\n def test_getLines(self):\n \"\"\" Test the getLine function \"\"\"\n Line_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Line)\n Line_type2 = self.db.setMarkerType(name='Test2', color='#00FF00', mode=self.db.TYPE_Line)\n Line_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Line)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n self.db.setLines(image=image1, x1=[1, 2, 3, 4, 5], y1=[0, 0, 0, 0, 0], x2=[1, 2, 3, 4, 5], y2=[1, 1, 1, 1, 1], type=Line_type1)\n self.db.setLines(image=image1, x1=[1, 2, 3, 4, 5], y1=[0, 0, 0, 0, 0], x2=[1, 2, 3, 4, 5], y2=[1, 1, 1, 1, 1], type=Line_type2)\n self.db.setLines(image=image2, x1=[1, 2, 3, 4, 5], y1=[0, 0, 0, 0, 0], x2=[1, 2, 3, 4, 5], y2=[1, 1, 1, 1, 1], type=Line_type1)\n Lines = self.db.getLines(image=[image1, image2])\n self.assertEqual(Lines.count(), 15, 'Getting Lines does not work properly.')\n Lines = self.db.getLines(image=image1)\n self.assertEqual(Lines.count(), 10, 'Getting Lines does not work properly.')\n Lines = self.db.getLines(frame=0)\n self.assertEqual(Lines.count(), 10, 'Getting Lines does not work properly.')\n Lines = self.db.getLines(filename=['test1.jpg', 'test2.jpg'])\n self.assertEqual(Lines.count(), 15, 'Getting Lines does not work properly.')\n Lines = self.db.getLines(x1=[2, 3])\n self.assertEqual(Lines.count(), 6, 'Getting Lines does not work properly.')\n Lines = self.db.getLines(x1=[2, 3], y1=[0, 1, 2])\n self.assertEqual(Lines.count(), 6, 'Getting Lines does not work properly.')\n Lines = self.db.getLines(type=Line_type1)\n self.assertEqual(Lines.count(), 10, 'Getting Lines does not work properly.')\n Lines = self.db.getLines(type=['Test1', 'Test2'])\n self.assertEqual(Lines.count(), 15, 'Getting Lines does not work properly.')\n self.assertRaises(clickpoints.MarkerTypeDoesNotExist, self.db.getLines, type=['NoType'])\n", "method_code": " def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None):\n \"\"\"\n Get all :py:class:`Line` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getLine`, :py:meth:`~.DataFile.setLine`, :py:meth:`~.DataFile.setLines`,\n :py:meth:`~.DataFile.deleteLines`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the lines.\n frame : int, array_like, optional\n the frame/s of the images of the lines.\n filename : string, array_like, optional\n the filename/s of the images of the lines.\n x1 : int, array_like, optional\n the x coordinate/s of the lines start.\n y1 : int, array_like, optional\n the y coordinate/s of the lines start.\n x2 : int, array_like, optional\n the x coordinate/s of the lines end.\n y2 : int, array_like, optional\n the y coordinate/s of the lines end.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the lines.\n processed : int, array_like, optional\n the processed flag/s of the lines.\n text : string, array_like, optional\n the text/s of the lines.\n id : int, array_like, optional\n the id/s of the lines.\n \n Returns\n -------\n entries : array_like\n a query object which contains all :py:class:`Line` entries.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Line'])\n query = self.table_line.select(self.table_line, self.table_image).join(self.table_image)\n query = addFilter(query, id, self.table_line.id)\n query = addFilter(query, image, self.table_line.image)\n query = addFilter(query, frame, self.table_image.sort_index)\n query = addFilter(query, filename, self.table_image.filename)\n query = addFilter(query, x1, self.table_line.x1)\n query = addFilter(query, y1, self.table_line.y1)\n query = addFilter(query, x2, self.table_line.x2)\n query = addFilter(query, y2, self.table_line.y2)\n query = addFilter(query, type, self.table_line.type)\n query = addFilter(query, processed, self.table_line.processed)\n query = addFilter(query, text, self.table_line.text)\n query.__array__ = lambda: np.array([[[l.x1, l.y1], [l.x2, l.y2]] for l in query])\n return query\n ", "context": "class DataFile():\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getLines", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001565.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setLines", "tests": "import unittest\n\nclass Test_setLines(unittest.TestCase):\n def test_setLines(self):\n \"\"\" Test the setLines function \"\"\"\n Line_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Line)\n Line_type2 = self.db.setMarkerType(name='Test2', color='#00FF00', mode=self.db.TYPE_Line)\n Line_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Track)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n track1 = self.db.setTrack(Line_type3)\n track2 = self.db.setTrack(Line_type3)\n self.db.setLines(image=image1, x1=[1, 2, 3, 4, 5], y1=[0, 0, 0, 0, 0], x2=[1, 2, 3, 4, 5], y2=[0, 0, 0, 0, 0], type=Line_type1)\n self.assertEqual(self.db.getLines().count(), 5, 'Setting Lines does not work properly.')\n self.db.deleteLines()\n self.db.setLines(image=[image1, image2], x1=[1, 2], y1=[0, 0], x2=[1, 2], y2=[0, 0], type=Line_type1)\n self.assertEqual(self.db.getLines().count(), 2, 'Setting Lines does not work properly.')\n self.db.deleteLines()\n self.db.setLines(image=image1, x1=1, y1=0, x2=10, y2=20, type=[Line_type1, Line_type2])\n self.assertEqual(self.db.getLines().count(), 2, 'Setting Lines does not work properly.')\n self.db.deleteLines()\n self.db.setLines(image=image1, x1=1, y1=0, x2=10, y2=20, type=Line_type1, text=['foo', 'bar', 'hu'], style='{}')\n self.assertEqual(self.db.getLines().count(), 3, 'Setting Lines does not work properly.')\n self.db.deleteLines()\n self.db.setLines(filename='test2.jpg', x1=1, y1=0, x2=10, y2=20, type=Line_type2)\n self.assertEqual(self.db.getLines().count(), 1, 'Setting Lines does not work properly.')\n self.db.deleteLines()\n self.db.setLines(frame=[0, 1, 2], x1=1, y1=0, x2=10, y2=20, type=Line_type2)\n self.assertEqual(self.db.getLines().count(), 3, 'Setting Lines does not work properly.')\n self.db.deleteLines()\n self.db.setLines(image=image1, x1=[0, 1, 2], y1=[0, 1, 2], x2=0, y2=0, type=Line_type1)\n Lines = self.db.getLines()\n self.assertTrue(all((m.x1 < 10 for m in Lines)), 'Setting Lines does not work properly.')\n self.db.setLines(x1=[10, 20, 30], y1=[0, 1, 2], x2=0, y2=0, id=[m for m in Lines])\n Lines = self.db.getLines()\n self.assertTrue(all((m.x1 >= 10 for m in Lines)), 'Setting Lines does not work properly.')\n self.db.deleteLines()\n", "method_code": " def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None):\n \"\"\"\n Insert or update multiple :py:class:`Line` objects in the database.\n \n See also: :py:meth:`~.DataFile.getLine`, :py:meth:`~.DataFile.getLines`, :py:meth:`~.DataFile.setLine`,\n :py:meth:`~.DataFile.deleteLines`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the lines.\n frame : int, array_like, optional\n the frame/s of the images of the lines.\n filename : string, array_like, optional\n the filename/s of the images of the lines.\n x1 : int, array_like, optional\n the x coordinate/s of the start of the lines.\n y1 : int, array_like, optional\n the y coordinate/s of the start of the lines.\n x2 : int, array_like, optional\n the x coordinate/s of the end of the lines.\n y2 : int, array_like, optional\n the y coordinate/s of the end of the lines.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the lines.\n processed : int, array_like, optional\n the processed flag/s of the lines.\n track : int, :py:class:`Track`, array_like, optional\n the track id/s or instance/s of the lines.\n text : string, array_like, optional\n the text/s of the lines.\n id : int, array_like, optional\n the id/s of the lines.\n layer: int, optional\n the layer of the images of the lines\n \n Returns\n -------\n success : bool\n it the inserting was successful.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Line'])\n image = self._processImagesField(image, frame, filename, layer)\n data = packToDictList(self.table_line, id=id, image=image, x1=x1, y1=y1, x2=x2, y2=y2, processed=processed, type=type, style=style, text=text)\n return self.saveReplaceMany(self.table_line, data)\n ", "context": "class DataFile():\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setLines", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001566.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteLines", "tests": "import unittest\n\nclass Test_deleteLines(unittest.TestCase):\n def test_deleteLines(self):\n \"\"\" Test the deleteLines function \"\"\"\n Line_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Line)\n Line_type2 = self.db.setMarkerType(name='Test2', color='#00FF00', mode=self.db.TYPE_Line)\n Line_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Track)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n\n def CreateLines():\n track1 = self.db.setTrack(Line_type3)\n track2 = self.db.setTrack(Line_type3)\n self.db.setLines(image=image1, x1=[1, 2, 3, 4, 5], y1=[0, 0, 0, 0, 0], x2=0, y2=0, type=Line_type1)\n self.db.setLines(image=image2, x1=[1, 2, 3, 4, 5], y1=[0, 0, 0, 0, 0], x2=0, y2=0, processed=True, text='foo', type=Line_type1)\n self.db.setLines(image=image1, x1=[1, 2, 3, 4, 5], y1=[0, 0, 0, 0, 0], x2=0, y2=0, text='bar', type=Line_type2)\n CreateLines()\n self.db.deleteLines(image=image1)\n self.assertEqual(self.db.getLines().count(), 5, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n CreateLines()\n self.db.deleteLines(image=[image1, image2])\n self.assertEqual(self.db.getLines().count(), 0, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n CreateLines()\n self.db.deleteLines(filename='test2.jpg')\n self.assertEqual(self.db.getLines().count(), 10, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n CreateLines()\n self.db.deleteLines(frame=1)\n self.assertEqual(self.db.getLines().count(), 10, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n CreateLines()\n self.db.deleteLines(x1=slice(2, 4))\n self.assertEqual(self.db.getLines().count(), 6, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n CreateLines()\n self.db.deleteLines(processed=True)\n self.assertEqual(self.db.getLines().count(), 10, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n CreateLines()\n self.db.deleteLines(text='foo')\n self.assertEqual(self.db.getLines().count(), 10, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n CreateLines()\n ids = [m.id for m in self.db.getLines(text='foo')]\n self.db.deleteLines(id=ids)\n self.assertEqual(self.db.getLines().count(), 10, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n CreateLines()\n self.db.deleteLines(type='Test1')\n self.assertEqual(self.db.getLines().count(), 5, 'Deleting Lines does not work properly.')\n self.db.deleteLines()\n for line in self.db.getLines():\n print(line)\n line.print_details()\n", "method_code": " def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None):\n \"\"\"\n Delete all :py:class:`Line` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getLine`, :py:meth:`~.DataFile.getLines`, :py:meth:`~.DataFile.setLine`,\n :py:meth:`~.DataFile.setLines`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the lines.\n frame : int, array_like, optional\n the frame/s of the images of the lines.\n filename : string, array_like, optional\n the filename/s of the images of the lines.\n x1 : int, array_like, optional\n the x coordinate/s of the start of the lines.\n y1 : int, array_like, optional\n the y coordinate/s of the start of the lines.\n x2 : int, array_like, optional\n the x coordinate/s of the end of the lines.\n y2 : int, array_like, optional\n the y coordinate/s of the end of the lines.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the lines.\n processed : int, array_like, optional\n the processed flag/s of the lines.\n text : string, array_like, optional\n the text/s of the lines.\n id : int, array_like, optional\n the id/s of the lines.\n \n Returns\n -------\n rows : int\n the number of affected rows.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Line'])\n query = self.table_line.delete()\n if image is None and (frame is not None or filename is not None):\n images = self.table_image.select(self.table_image.id)\n images = addFilter(images, frame, self.table_image.sort_index)\n images = addFilter(images, filename, self.table_image.filename)\n query = query.where(self.table_line.image.in_(images))\n else:\n query = addFilter(query, image, self.table_line.image)\n query = addFilter(query, id, self.table_line.id)\n query = addFilter(query, x1, self.table_line.x1)\n query = addFilter(query, y1, self.table_line.y1)\n query = addFilter(query, x2, self.table_line.x2)\n query = addFilter(query, y2, self.table_line.y2)\n query = addFilter(query, type, self.table_line.type)\n query = addFilter(query, processed, self.table_line.processed)\n query = addFilter(query, text, self.table_line.text)\n return query.execute()\n ", "context": "class DataFile():\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteLines", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_001567.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setRectangle", "tests": "import unittest\n\nclass Test_setRectangle(unittest.TestCase):\n def test_setRectangle(self):\n \"\"\" Test the setRectangle function \"\"\"\n Rectangle_type = self.db.setMarkerType(name='Test', color='#FF0000', mode=self.db.TYPE_Rect)\n image = self.db.setImage('test.jpg')\n Rectangle = self.db.setRectangle(image=image.id, x=123, y=0, width=10, height=10, type=Rectangle_type)\n self.assertEqual(Rectangle.x, 123, 'Setting Rectangle does not work properly.')\n Rectangle = self.db.setRectangle(filename='test.jpg', x=123, y=0, width=10, height=10, type='Test')\n self.assertEqual(Rectangle.x, 123, 'Setting Rectangle does not work properly.')\n Rectangle = self.db.setRectangle(frame=0, x=123, y=0, width=10, height=10, type=Rectangle_type)\n self.assertEqual(Rectangle.x, 123, 'Setting Rectangle does not work properly.')\n Rectangle = self.db.setRectangle(x=123, y=0, width=10, height=10, id=Rectangle)\n self.assertEqual(Rectangle.x, 123, 'Setting Rectangle does not work properly.')\n self.assertRaises(clickpoints.ImageDoesNotExist, self.db.setRectangle, frame=1, x=123, y=0, width=10, height=10, type=Rectangle_type)\n self.assertRaises(clickpoints.ImageDoesNotExist, self.db.setRectangle, filename='no.jpg', x=123, y=0, width=10, height=10, type=Rectangle_type)\n self.assertRaises(clickpoints.MarkerTypeDoesNotExist, self.db.setRectangle, image=1, x=123, y=0, width=10, height=10, type='NoType')\n self.assertRaises(AssertionError, self.db.setRectangle, x=123, y=0, width=10, height=10)\n self.assertRaises(AssertionError, self.db.setRectangle, x=123, y=0, width=10, height=10, type=Rectangle_type)\n", "method_code": " def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None):\n \"\"\"\n Insert or update an :py:class:`Rectangle` object in the database.\n \n See also: :py:meth:`~.DataFile.getRectangle`, :py:meth:`~.DataFile.getRectangles`,\n :py:meth:`~.DataFile.setRectangles`, :py:meth:`~.DataFile.deleteRectangles`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, optional\n the image of the rectangle.\n frame : int, optional\n the frame of the images of the rectangle.\n filename : string, optional\n the filename of the image of the rectangle.\n x : int, optional\n the x coordinate of the upper left corner of the rectangle.\n y : int, optional\n the y coordinate of the upper left corner of the rectangle.\n width : int, optional\n the width of the rectangle.\n height : int, optional\n the height of the rectangle.\n type : string, :py:class:`MarkerType`, optional\n the marker type (or name) of the rectangle.\n processed : int, optional\n the processed flag of the rectangle.\n text : string, optional\n the text of the rectangle.\n id : int, optional\n the id of the rectangle.\n layer : int, optional\n the id of the image of the rectangle\n \n Returns\n -------\n rectangle : :py:class:`Rectangle`\n the created or changed :py:class:`Rectangle` item.\n \"\"\"\n assert not (id is None and type is None), \"Rectangle must either have a type or be referenced by it's id.\"\n assert not (id is None and image is None and (frame is None) and (filename is None)), \"Rectangle must have an image, frame or filename given or be referenced by it's id.\"\n try:\n item = self.table_rectangle.get(id=id)\n except peewee.DoesNotExist:\n item = self.table_rectangle()\n type = self._processesTypeNameField(type, ['TYPE_Rect'])\n image = self._processImagesField(image, frame, filename, layer)\n setFields(item, dict(image=image, x=x, y=y, width=width, height=height, type=type, processed=processed, style=style, text=text))\n item.save()\n return item\n ", "context": "class DataFile():\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setRectangle", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001568.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getRectangle", "tests": "import unittest\n\nclass Test_getRectangle(unittest.TestCase):\n def test_getRectangle(self):\n \"\"\" Test the getRectangle function \"\"\"\n Rectangle_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Rect)\n image1 = self.db.setImage('test1.jpg')\n self.db.setRectangle(image=image1, x=456, y=0, width=10, height=10, type=Rectangle_type1)\n Rectangle = self.db.getRectangle(id=1)\n self.assertEqual(Rectangle.x, 456, 'Getting Rectangle does not work properly.')\n Rectangle = self.db.getRectangle(id=0)\n self.assertEqual(Rectangle, None, 'Getting Rectangle does not work properly.')\n", "method_code": " def getRectangle(self, id):\n \"\"\"\n Retrieve an :py:class:`Rectangle` object from the database.\n \n See also: :py:meth:`~.DataFile.getRectangles`, :py:meth:`~.DataFile.setRectangle`,\n :py:meth:`~.DataFile.setRectangles`, :py:meth:`~.DataFile.deleteRectangles`.\n \n Parameters\n ----------\n id: int\n the id of the rectangle.\n \n Returns\n -------\n rectangle : :py:class:`Rectangle`\n the :py:class:`Rectangle` with the desired id or None.\n \"\"\"\n try:\n return self.table_rectangle.get(id=id)\n except peewee.DoesNotExist:\n return None\n ", "context": "class DataFile():\n def getRectangle(self, id): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getRectangle", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001569.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getRectangles", "tests": "import unittest\n\nclass Test_getRectangles(unittest.TestCase):\n def test_getRectangles(self):\n \"\"\" Test the getRectangle function \"\"\"\n Rectangle_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Rect)\n Rectangle_type2 = self.db.setMarkerType(name='Test2', color='#00FF00', mode=self.db.TYPE_Rect)\n Rectangle_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Rect)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n self.db.setRectangles(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], width=[1, 2, 3, 4, 5], height=[1, 1, 1, 1, 1], type=Rectangle_type1)\n self.db.setRectangles(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], width=[1, 2, 3, 4, 5], height=[1, 1, 1, 1, 1], type=Rectangle_type2)\n self.db.setRectangles(image=image2, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], width=[1, 2, 3, 4, 5], height=[1, 1, 1, 1, 1], type=Rectangle_type1)\n Rectangles = self.db.getRectangles(image=[image1, image2])\n self.assertEqual(Rectangles.count(), 15, 'Getting Rectangles does not work properly.')\n Rectangles = self.db.getRectangles(image=image1)\n self.assertEqual(Rectangles.count(), 10, 'Getting Rectangles does not work properly.')\n Rectangles = self.db.getRectangles(frame=0)\n self.assertEqual(Rectangles.count(), 10, 'Getting Rectangles does not work properly.')\n Rectangles = self.db.getRectangles(filename=['test1.jpg', 'test2.jpg'])\n self.assertEqual(Rectangles.count(), 15, 'Getting Rectangles does not work properly.')\n Rectangles = self.db.getRectangles(x=[2, 3])\n self.assertEqual(Rectangles.count(), 6, 'Getting Rectangles does not work properly.')\n Rectangles = self.db.getRectangles(x=[2, 3], y=[0, 1, 2])\n self.assertEqual(Rectangles.count(), 6, 'Getting Rectangles does not work properly.')\n Rectangles = self.db.getRectangles(type=Rectangle_type1)\n self.assertEqual(Rectangles.count(), 10, 'Getting Rectangles does not work properly.')\n Rectangles = self.db.getRectangles(type=['Test1', 'Test2'])\n self.assertEqual(Rectangles.count(), 15, 'Getting Rectangles does not work properly.')\n self.assertRaises(clickpoints.MarkerTypeDoesNotExist, self.db.getRectangles, type=['NoType'])\n", "method_code": " def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None):\n \"\"\"\n Get all :py:class:`Rectangle` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getRectangle`, :py:meth:`~.DataFile.setRectangle`,\n :py:meth:`~.DataFile.setRectangles`, :py:meth:`~.DataFile.deleteRectangles`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the rectangles.\n frame : int, array_like, optional\n the frame/s of the images of the rectangles.\n filename : string, array_like, optional\n the filename/s of the images of the rectangles.\n x : int, array_like, optional\n the x coordinate/s of the upper left corner/s of the rectangles.\n y : int, array_like, optional\n the y coordinate/s of the upper left corner/s of the rectangles.\n width : int, array_like, optional\n the width/s of the rectangles.\n height : int, array_like, optional\n the height/s of the rectangles.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the rectangles.\n processed : int, array_like, optional\n the processed flag/s of the rectangles.\n text : string, array_like, optional\n the text/s of the rectangles.\n id : int, array_like, optional\n the id/s of the rectangles.\n layer : int, optional\n the id of the image of the rectangle\n \n Returns\n -------\n entries : array_like\n a query object which contains all :py:class:`Rectangle` entries.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Rect'])\n query = self.table_rectangle.select(self.table_rectangle, self.table_image).join(self.table_image)\n image = self._processImagesField(image, frame, filename, layer)\n query = addFilter(query, id, self.table_rectangle.id)\n query = addFilter(query, image, self.table_rectangle.image)\n query = addFilter(query, frame, self.table_image.sort_index)\n query = addFilter(query, filename, self.table_image.filename)\n query = addFilter(query, x, self.table_rectangle.x)\n query = addFilter(query, y, self.table_rectangle.y)\n query = addFilter(query, height, self.table_rectangle.height)\n query = addFilter(query, width, self.table_rectangle.width)\n query = addFilter(query, type, self.table_rectangle.type)\n query = addFilter(query, processed, self.table_rectangle.processed)\n query = addFilter(query, text, self.table_rectangle.text)\n return query\n ", "context": "class DataFile():\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getRectangles", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001570.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setRectangles", "tests": "import unittest\n\nclass Test_setRectangles(unittest.TestCase):\n def test_setRectangles(self):\n \"\"\" Test the setRectangles function \"\"\"\n Rectangle_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Rect)\n Rectangle_type2 = self.db.setMarkerType(name='Test2', color='#00FF00', mode=self.db.TYPE_Rect)\n Rectangle_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Track)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n track1 = self.db.setTrack(Rectangle_type3)\n track2 = self.db.setTrack(Rectangle_type3)\n self.db.setRectangles(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], width=[1, 2, 3, 4, 5], height=[0, 0, 0, 0, 0], type=Rectangle_type1)\n self.assertEqual(self.db.getRectangles().count(), 5, 'Setting Rectangles does not work properly.')\n self.db.deleteRectangles()\n self.db.setRectangles(image=[image1, image2], x=[1, 2], y=[0, 0], width=[1, 2], height=[0, 0], type=Rectangle_type1)\n self.assertEqual(self.db.getRectangles().count(), 2, 'Setting Rectangles does not work properly.')\n self.db.deleteRectangles()\n self.db.setRectangles(image=image1, x=1, y=0, width=10, height=20, type=[Rectangle_type1, Rectangle_type2])\n self.assertEqual(self.db.getRectangles().count(), 2, 'Setting Rectangles does not work properly.')\n self.db.deleteRectangles()\n self.db.setRectangles(image=image1, x=1, y=0, width=10, height=20, type=Rectangle_type1, text=['foo', 'bar', 'hu'], style='{}')\n self.assertEqual(self.db.getRectangles().count(), 3, 'Setting Rectangles does not work properly.')\n self.db.deleteRectangles()\n self.db.setRectangles(filename='test2.jpg', x=1, y=0, width=10, height=20, type=Rectangle_type2)\n self.assertEqual(self.db.getRectangles().count(), 1, 'Setting Rectangles does not work properly.')\n self.db.deleteRectangles()\n self.db.setRectangles(frame=[0, 1, 2], x=1, y=0, width=10, height=20, type=Rectangle_type2)\n self.assertEqual(self.db.getRectangles().count(), 3, 'Setting Rectangles does not work properly.')\n self.db.deleteRectangles()\n self.db.setRectangles(image=image1, x=[0, 1, 2], y=[0, 1, 2], width=0, height=0, type=Rectangle_type1)\n Rectangles = self.db.getRectangles()\n self.assertTrue(all((m.x < 10 for m in Rectangles)), 'Setting Rectangles does not work properly.')\n self.db.setRectangles(x=[10, 20, 30], y=[0, 1, 2], width=0, height=0, id=[m for m in Rectangles])\n Rectangles = self.db.getRectangles()\n self.assertTrue(all((m.x >= 10 for m in Rectangles)), 'Setting Rectangles does not work properly.')\n self.db.deleteRectangles()\n", "method_code": " def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None):\n \"\"\"\n Insert or update multiple :py:class:`Rectangle` objects in the database.\n \n See also: :py:meth:`~.DataFile.getRectangle`, :py:meth:`~.DataFile.getRectangles`,\n :py:meth:`~.DataFile.setRectangle`, :py:meth:`~.DataFile.deleteRectangles`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the rectangles.\n frame : int, array_like, optional\n the frame/s of the images of the rectangles.\n filename : string, array_like, optional\n the filename/s of the images of the rectangles.\n x : int, array_like, optional\n the x coordinate/s of the upper left corner/s of the rectangles.\n y : int, array_like, optional\n the y coordinate/s of the upper left corner/s of the rectangles.\n width : int, array_like, optional\n the width/s of the rectangles.\n height : int, array_like, optional\n the height/s of the rectangles.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the rectangles.\n processed : int, array_like, optional\n the processed flag/s of the rectangles.\n text : string, array_like, optional\n the text/s of the rectangles.\n id : int, array_like, optional\n the id/s of the rectangles.\n layer : int, optional\n the layer of the images of the rectangles\n \n Returns\n -------\n success : bool\n it the inserting was successful.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Rect'])\n image = self._processImagesField(image, frame, filename, layer)\n data = packToDictList(self.table_rectangle, id=id, image=image, x=x, y=y, width=width, height=height, processed=processed, type=type, style=style, text=text)\n return self.saveReplaceMany(self.table_rectangle, data)\n ", "context": "class DataFile():\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setRectangles", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001571.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteRectangles", "tests": "import unittest\n\nclass Test_deleteRectangles(unittest.TestCase):\n def test_deleteRectangles(self):\n \"\"\" Test the deleteRectangles function \"\"\"\n Rectangle_type1 = self.db.setMarkerType(name='Test1', color='#FF0000', mode=self.db.TYPE_Rect)\n Rectangle_type2 = self.db.setMarkerType(name='Test2', color='#00FF00', mode=self.db.TYPE_Rect)\n Rectangle_type3 = self.db.setMarkerType(name='Track', color='#00FF00', mode=self.db.TYPE_Track)\n image1 = self.db.setImage('test1.jpg')\n image2 = self.db.setImage('test2.jpg')\n image3 = self.db.setImage('test3.jpg')\n image4 = self.db.setImage('test4.jpg')\n\n def CreateRectangles():\n track1 = self.db.setTrack(Rectangle_type3)\n track2 = self.db.setTrack(Rectangle_type3)\n self.db.setRectangles(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], width=0, height=0, type=Rectangle_type1)\n self.db.setRectangles(image=image2, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], width=0, height=0, processed=True, text='foo', type=Rectangle_type1)\n self.db.setRectangles(image=image1, x=[1, 2, 3, 4, 5], y=[0, 0, 0, 0, 0], width=0, height=0, text='bar', type=Rectangle_type2)\n CreateRectangles()\n self.db.deleteRectangles(image=image1)\n self.assertEqual(self.db.getRectangles().count(), 5, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n CreateRectangles()\n self.db.deleteRectangles(image=[image1, image2])\n self.assertEqual(self.db.getRectangles().count(), 0, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n CreateRectangles()\n self.db.deleteRectangles(filename='test2.jpg')\n self.assertEqual(self.db.getRectangles().count(), 10, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n CreateRectangles()\n self.db.deleteRectangles(frame=1)\n self.assertEqual(self.db.getRectangles().count(), 10, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n CreateRectangles()\n self.db.deleteRectangles(x=slice(2, 4))\n self.assertEqual(self.db.getRectangles().count(), 6, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n CreateRectangles()\n self.db.deleteRectangles(processed=True)\n self.assertEqual(self.db.getRectangles().count(), 10, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n CreateRectangles()\n self.db.deleteRectangles(text='foo')\n self.assertEqual(self.db.getRectangles().count(), 10, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n CreateRectangles()\n ids = [m.id for m in self.db.getRectangles(text='foo')]\n self.db.deleteRectangles(id=ids)\n self.assertEqual(self.db.getRectangles().count(), 10, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n CreateRectangles()\n self.db.deleteRectangles(type='Test1')\n self.assertEqual(self.db.getRectangles().count(), 5, 'Deleting Rectangles does not work properly.')\n self.db.deleteRectangles()\n for rect in self.db.getRectangles():\n print(rect)\n rect.print_details()\n", "method_code": " def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None):\n \"\"\"\n Delete all :py:class:`Rectangle` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getRectangle`, :py:meth:`~.DataFile.getRectangles`,\n :py:meth:`~.DataFile.setRectangle`, :py:meth:`~.DataFile.setRectangles`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/s of the rectangles.\n frame : int, array_like, optional\n the frame/s of the images of the rectangles.\n filename : string, array_like, optional\n the filename/s of the images of the rectangles.\n x : int, array_like, optional\n the x coordinate/s of the upper left corner/s of the rectangles.\n y : int, array_like, optional\n the y coordinate/s of the upper left corner/s of the rectangles.\n width : int, array_like, optional\n the width/s of the rectangles.\n height : int, array_like, optional\n the height/s of the rectangles.\n type : string, :py:class:`MarkerType`, array_like, optional\n the marker type/s (or name/s) of the rectangles.\n processed : int, array_like, optional\n the processed flag/s of the rectangles.\n text : string, array_like, optional\n the text/s of the rectangles.\n id : int, array_like, optional\n the id/s of the rectangles.\n \n Returns\n -------\n rows : int\n the number of affected rows.\n \"\"\"\n type = self._processesTypeNameField(type, ['TYPE_Rect'])\n image = self._processImagesField(image, frame, filename, layer)\n query = self.table_rectangle.delete()\n if image is None and (frame is not None or filename is not None):\n images = self.table_image.select(self.table_image.id)\n images = addFilter(images, frame, self.table_image.sort_index)\n images = addFilter(images, filename, self.table_image.filename)\n query = query.where(self.table_rectangle.image.in_(images))\n else:\n query = addFilter(query, image, self.table_rectangle.image)\n query = addFilter(query, id, self.table_rectangle.id)\n query = addFilter(query, x, self.table_rectangle.x)\n query = addFilter(query, y, self.table_rectangle.y)\n query = addFilter(query, width, self.table_rectangle.width)\n query = addFilter(query, height, self.table_rectangle.height)\n query = addFilter(query, type, self.table_rectangle.type)\n query = addFilter(query, processed, self.table_rectangle.processed)\n query = addFilter(query, text, self.table_rectangle.text)\n return query.execute()\n ", "context": "class DataFile():\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteRectangles", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_001572.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getTag", "tests": "import unittest\n\nclass Test_getTag(unittest.TestCase):\n def test_setgetTag(self):\n tag1 = self.db.setTag(name='tag1')\n self.assertTrue(tag1.name == 'tag1', 'Failed setting Tag')\n self.assertRaises(AssertionError, self.db.setTag)\n tag1 = self.db.getTag(name='tag1')\n self.assertTrue(tag1.name == 'tag1', 'Failed retrieving single Tag by Name ')\n tag1 = self.db.getTag(id=1)\n self.assertTrue(tag1.name == 'tag1', 'Failed retrieving single Tag by ID ')\n self.assertRaises(AssertionError, self.db.getTag)\n tag1b = self.db.setTag(id=1, name='tag1b')\n tags = self.db.getTags()\n self.assertTrue(tags.count() == 1, 'Failed updating tag entry - nr tags')\n self.assertTrue(tags[0].name == 'tag1b', 'Failed updating tag entry - tag name')\n", "method_code": " def getTag(self, name=None, id=None):\n \"\"\"\n Get a specific :py:class:`Tag` entry by its name or database ID\n \n See also: :py:meth:`~.DataFile.getTags`, :py:meth:`~.DataFile.setTag`, :py:meth:`~.DataFile.deleteTags`.\n \n Parameters\n ----------\n name: str\n name of the tag\n id: int\n id of :py:class:`Tag` entry\n \n \n Returns\n -------\n entries : :py:class:`Tag`\n requested object of class :py:class:`Tag` or None\n \"\"\"\n assert any((e is not None for e in [id, name])), 'Name and ID may not be all None'\n try:\n return self.table_tag.get(**noNoneDict(name=name, id=id))\n except:\n return None\n ", "context": "class DataFile():\n def getTag(self, name=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setgetTag", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001573.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getTags", "tests": "import unittest\n\nclass Test_getTags(unittest.TestCase):\n def test_getTags(self):\n tag1 = self.db.setTag(name='tag1')\n tag2 = self.db.setTag(name='tag2')\n tag3 = self.db.setTag(name='tag3')\n tags = self.db.getTags()\n self.assertEqual(tags.count(), 3, 'Failed retrieving all tags')\n tags = self.db.getTags(name=['tag1', 'tag3'])\n self.assertEqual(tags.count(), 2, 'Failed retrieving tags by name list')\n tags = self.db.getTags(id=[1, 2])\n self.assertEqual(tags.count(), 2, 'Failed retrieving tags by ID list')\n for tag in tags:\n print(tag)\n tag.print_details()\n", "method_code": " def getTags(self, name=None, id=None):\n \"\"\"\n Get all :py:class:`Tag` entries from the database, which match the given criteria. If no criteria a given,\n return all.\n \n See also: :py:meth:`~.DataFile.getTag`, :py:meth:`~.DataFile.setTag`,\n :py:meth:`~.DataFile.deleteTags`.\n \n Parameters\n ----------\n name : string, array_like, optional\n the name/names of the :py:class:`Tag`.\n id : int, array_like, optional\n the id/ids of the :py:class:`Tag`.\n \n Returns\n -------\n entries : array_like\n a query object containing all the matching :py:class:`Tag` entries in the database file.\n \"\"\"\n query = self.table_tag.select()\n query = addFilter(query, name, self.table_tag.name)\n query = addFilter(query, id, self.table_tag.id)\n return query\n ", "context": "class DataFile():\n def getTags(self, name=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getTags", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_001574.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteTags", "tests": "import unittest\n\nclass Test_deleteTags(unittest.TestCase):\n def test_deleteTags(self):\n tag1 = self.db.setTag(name='tag1')\n tag2 = self.db.setTag(name='tag2')\n tag3 = self.db.setTag(name='tag3')\n count = self.db.deleteTags()\n self.assertEqual(count, 3, 'Failed delete all tags')\n tag1 = self.db.setTag(name='tag1')\n tag2 = self.db.setTag(name='tag2')\n tag3 = self.db.setTag(name='tag3')\n count = self.db.deleteTags(name=['tag1', 'tag3'])\n self.assertEqual(count, 2, 'Failed delete tags by name list')\n", "method_code": " def deleteTags(self, name=None, id=None):\n \"\"\"\n Delete all :py:class:`Tag` entries from the database, which match the given criteria. If no criteria a given,\n delete all.\n \n See also: :py:meth:`~.DataFile.getTag`, :py:meth:`~.DataFile.getTags`, :py:meth:`~.DataFile.setTag`.\n \n Parameters\n ----------\n name : string, array_like, optional\n the name/names of the :py:class:`Tag`.\n id : int, array_like, optional\n the id/ids of the :py:class:`Tag`.\n \n Returns\n -------\n rows : int\n number of rows deleted\n \"\"\"\n query = self.table_tag.delete()\n query = addFilter(query, name, self.table_tag.name)\n query = addFilter(query, id, self.table_tag.id)\n return query.execute()\n ", "context": "class DataFile():\n def deleteTags(self, name=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteTags", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001575.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getAnnotation", "tests": "import unittest\n\nclass Test_getAnnotation(unittest.TestCase):\n def test_getAnnotation(self):\n im = self.db.setImage('test.jpg')\n self.db.setAnnotation(im, comment='foo')\n annotation = self.db.getAnnotation(image=im)\n self.assertEqual(annotation.comment, 'foo', 'Failed to get annotation by image.')\n annotation = self.db.getAnnotation(frame=0)\n self.assertEqual(annotation.comment, 'foo', 'Failed to get annotation by frame.')\n annotation = self.db.getAnnotation(filename='test.jpg')\n self.assertEqual(annotation.comment, 'foo', 'Failed to get annotation by filename.')\n annotation = self.db.getAnnotation(id=1)\n self.assertEqual(annotation.comment, 'foo', 'Failed to get annotation by id.')\n annotation = self.db.getAnnotation(filename='test2.jpg')\n self.assertEqual(annotation, None, 'Failed to get non existent annotation.')\n", "method_code": " def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False):\n \"\"\"\n Get the :py:class:`Annotation` entry for the given image frame number or filename.\n \n See also: :py:meth:`~.DataFile.getAnnotations`, :py:meth:`~.DataFile.setAnnotation`, :py:meth:`~.DataFile.deleteAnnotations`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, optional\n the image for which the annotation should be retrieved. If omitted, frame number or filename should be specified instead.\n frame : int, optional\n frame number of the image, which annotation should be returned. If omitted, image or filename should be specified instead.\n filename : string, optional\n filename of the image, which annotation should be returned. If omitted, image or frame number should be specified instead.\n id : int, optional\n id of the annotation entry.\n create : bool, optional\n whether the annotation should be created if it does not exist. (default: False)\n \n Returns\n -------\n annotation : :py:class:`Annotation`\n the desired :py:class:`Annotation` entry.\n \"\"\"\n assert sum((e is not None for e in [id, image, frame, filename])) == 1, \"Exactly one of image, frame or filename should be specified or should be referenced by it's id.\"\n query = self.table_annotation.select(self.table_annotation, self.table_image).join(self.table_image)\n query = addFilter(query, id, self.table_annotation.id)\n query = addFilter(query, image, self.table_annotation.image)\n query = addFilter(query, frame, self.table_image.sort_index)\n query = addFilter(query, filename, self.table_image.filename)\n query.limit(1)\n try:\n return query[0]\n except IndexError:\n if create is True:\n if not image:\n image = self.getImage(frame, filename)\n if not image:\n raise ImageDoesNotExist('No parent image found ')\n annotation = self.table_annotation(image=image, timestamp=image.timestamp, comment='', rating=None)\n annotation.save()\n return annotation\n return None\n ", "context": "class DataFile():\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getAnnotation", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001576.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "getAnnotations", "tests": "import unittest\n\nclass Test_getAnnotations(unittest.TestCase):\n def test_getAnnotations(self):\n im1 = self.db.setImage('test1.jpg')\n self.db.setAnnotation(im1, comment='foo', rating=1)\n im2 = self.db.setImage('test2.jpg')\n self.db.setAnnotation(im2, comment='bar', rating=3)\n im3 = self.db.setImage('test3.jpg')\n self.db.setAnnotation(im3, comment='foo')\n im4 = self.db.setImage('test4.jpg')\n annotations = self.db.getAnnotations(image=[im1, im2, im4])\n self.assertEqual(annotations.count(), 2, 'Failed to get annotations by images.')\n annotations = self.db.getAnnotations(filename='test2.jpg')\n self.assertEqual(annotations.count(), 1, 'Failed to get annotation by filename.')\n annotations = self.db.getAnnotations(comment='foo')\n self.assertEqual(annotations.count(), 2, 'Failed to get annotation by comment.')\n annotations = self.db.getAnnotations(rating=1)\n self.assertEqual(annotations.count(), 1, 'Failed to get annotation by rating.')\n annotations = self.db.getAnnotations()\n self.assertEqual(annotations.count(), 3, 'Failed to get annotation without filter.')\n", "method_code": " def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None):\n \"\"\"\n Get all :py:class:`Annotation` entries from the database, which match the given criteria. If no criteria a given, return all masks.\n \n See also: :py:meth:`~.DataFile.getAnnotation`, :py:meth:`~.DataFile.setAnnotation`, :py:meth:`~.DataFile.deleteAnnotations`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/images for which the annotations should be retrieved. If omitted, frame numbers or filenames should be specified instead.\n frame: int, array_like, optional\n frame number/numbers of the images, which annotations should be returned. If omitted, images or filenames should be specified instead.\n filename: string, array_like, optional\n filename of the image/images, which annotations should be returned. If omitted, images or frame numbers should be specified instead.\n timestamp : datetime, array_like, optional\n timestamp/s of the annotations.\n tag : string, array_like, optional\n the tag/s of the annotations to load.\n comment : string, array_like, optional\n the comment/s of the annotations.\n rating : int, array_like, optional\n the rating/s of the annotations.\n id : int, array_like, optional\n id/ids of the annotations.\n \n Returns\n -------\n entries : :py:class:`Annotation`\n a query object containing all the matching :py:class:`Annotation` entries in the database file.\n \"\"\"\n assert sum((e is not None for e in [image, frame, filename])) <= 1, 'Exactly one of images, frames or filenames should be specified'\n query = self.table_annotation.select(self.table_annotation, self.table_image).join(self.table_image)\n if tag is not None:\n query = query.switch(self.table_annotation).join(self.table_tagassociation).join(self.table_tag)\n query = addFilter(query, id, self.table_annotation.id)\n query = addFilter(query, image, self.table_annotation.image)\n query = addFilter(query, frame, self.table_image.sort_index)\n query = addFilter(query, filename, self.table_image.filename)\n query = addFilter(query, timestamp, self.table_annotation.timestamp)\n query = addFilter(query, comment, self.table_annotation.comment)\n query = addFilter(query, rating, self.table_annotation.rating)\n if tag:\n query = addFilter(query, tag, self.table_tag.name)\n query = query.group_by(self.table_annotation.id)\n return query\n ", "context": "class DataFile():\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_getAnnotations", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001577.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "setAnnotation", "tests": "import unittest\n\nclass Test_setAnnotation(unittest.TestCase):\n def test_setAnnotation(self):\n im1 = self.db.setImage('test1.jpg')\n im2 = self.db.setImage('test2.jpg')\n im3 = self.db.setImage('test3.jpg')\n im4 = self.db.setImage('test4.jpg')\n self.db.setAnnotation(image=im1, comment='foo')\n self.assertEqual(self.db.getAnnotation(image=im1).comment, 'foo', 'Failed to set annotation.')\n self.db.setAnnotation(image=im1, rating=2)\n self.assertEqual(self.db.getAnnotation(image=im1).rating, 2, 'Failed to set annotation.')\n self.db.setAnnotation(id=1, rating=3)\n self.assertEqual(self.db.getAnnotation(image=im1).rating, 3, 'Failed to set annotation.')\n self.assertRaises(AssertionError, self.db.setAnnotation, comment='', rating=2)\n", "method_code": " def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None):\n \"\"\"\n Insert or update an :py:class:`Annotation` object in the database.\n \n See also: :py:meth:`~.DataFile.getAnnotation`, :py:meth:`~.DataFile.getAnnotations`, :py:meth:`~.DataFile.deleteAnnotations`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, optional\n the image of the annotation.\n frame : int, optional\n the frame of the images of the annotation.\n filename : string, optional\n the filename of the image of the annotation.\n timestamp : datetime, optional\n the timestamp of the annotation.\n comment : string, optional\n the text of the annotation.\n rating : int, optional\n the rating of the annotation.\n id : int, optional\n the id of the annotation.\n \n Returns\n -------\n annotation : :py:class:`Annotation`\n the created or changed :py:class:`Annotation` item.\n \"\"\"\n assert not (id is None and image is None and (frame is None) and (filename is None)), \"Annotations must have an image, frame or filename given or be referenced by it's id.\"\n image = self._processImagesField(image, frame, filename, layer)\n try:\n item = self.table_annotation.get(**noNoneDict(id=id, image=image))\n except peewee.DoesNotExist:\n item = self.table_annotation()\n setFields(item, dict(image=image, timestamp=timestamp, comment=comment, rating=rating))\n item.save()\n return item\n ", "context": "class DataFile():\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_setAnnotation", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001578.py"} {"focal_file": "clickpoints/DataFile.py", "focal_class": null, "focal_method": "deleteAnnotations", "tests": "import unittest\n\nclass Test_deleteAnnotations(unittest.TestCase):\n def test_deleteAnnotations(self):\n im1 = self.db.setImage('test1.jpg')\n im2 = self.db.setImage('test2.jpg')\n im3 = self.db.setImage('test3.jpg')\n im4 = self.db.setImage('test4.jpg')\n\n def CreateAnnotations():\n self.db.deleteAnnotations()\n self.db.setAnnotation(im1, comment='foo', rating=1)\n self.db.setAnnotation(im2, comment='bar', rating=3)\n self.db.setAnnotation(im3, comment='foo')\n CreateAnnotations()\n self.db.deleteAnnotations()\n self.assertEqual(self.db.getAnnotations().count(), 0, 'Failed to delete all annotation.')\n CreateAnnotations()\n self.db.deleteAnnotations(rating=[1, 3])\n self.assertEqual(self.db.getAnnotations().count(), 1, 'Failed to delete all annotation.')\n CreateAnnotations()\n self.db.deleteAnnotations(comment='bar')\n self.assertEqual(self.db.getAnnotations().count(), 2, 'Failed to delete all annotation.')\n CreateAnnotations()\n self.db.deleteAnnotations(image=[im1, im4])\n self.assertEqual(self.db.getAnnotations().count(), 2, 'Failed to delete all annotation.')\n CreateAnnotations()\n self.db.deleteAnnotations(filename='test3.jpg')\n anns = self.db.getAnnotations()\n for an in anns:\n print(an)\n an.print_details()\n print(self.db.getAnnotations().count())\n self.assertEqual(self.db.getAnnotations().count(), 2, 'Failed to delete all annotation.')\n", "method_code": " def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None):\n \"\"\"\n Delete all :py:class:`Annotation` entries with the given criteria.\n \n See also: :py:meth:`~.DataFile.getAnnotation`, :py:meth:`~.DataFile.getAnnotations`, :py:meth:`~.DataFile.setAnnotation`.\n \n Parameters\n ----------\n image : int, :py:class:`Image`, array_like, optional\n the image/images for which the annotations should be retrieved. If omitted, frame numbers or filenames should be specified instead.\n frame: int, array_like, optional\n frame number/numbers of the images, which annotations should be returned. If omitted, images or filenames should be specified instead.\n filename: string, array_like, optional\n filename of the image/images, which annotations should be returned. If omitted, images or frame numbers should be specified instead.\n timestamp : datetime, array_like, optional\n timestamp/s of the annotations.\n comment : string, array_like, optional\n the comment/s of the annotations.\n rating : int, array_like, optional\n the rating/s of the annotations.\n id : int, array_like, optional\n id/ids of the annotations.\n \n Returns\n -------\n rows : int\n the number of affected rows.\n \"\"\"\n query = self.table_annotation.delete()\n if image is None and (frame is not None or filename is not None):\n images = self.table_image.select(self.table_image.id)\n images = addFilter(images, frame, self.table_image.sort_index)\n images = addFilter(images, filename, self.table_image.filename)\n query = query.where(self.table_annotation.image.in_(images))\n else:\n query = addFilter(query, image, self.table_annotation.image)\n query = addFilter(query, id, self.table_annotation.id)\n query = addFilter(query, image, self.table_annotation.image)\n query = addFilter(query, timestamp, self.table_annotation.timestamp)\n query = addFilter(query, comment, self.table_annotation.comment)\n query = addFilter(query, rating, self.table_annotation.rating)\n return query.execute()\n ", "context": "class DataFile():\n def deleteAnnotations(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None): ...\n def max_sql_variables(self): ...\n def saveReplaceMany(self, table, data): ...\n def saveInsertMany(self, table, data, fields=None): ...\n def __init__(self, database_filename=None, mode='r'): ...\n def __del__(self): ...\n def _InitOptions(self): ...\n def _AddOption(self, **kwargs): ...\n def _stringToList(self, value): ...\n def setOption(self, key, value): ...\n def getOption(self, key): ...\n def getOptionAccess(self): ...\n def _CheckVersion(self): ...\n def _migrateDBFrom(self, version): ...\n def _SetVersion(self, nr_new_version): ...\n def _migrateDBFrom2(self, nr_version): ...\n def _CreateTables(self): ...\n def _checkTrackField(self, tracks): ...\n def _processesTypeNameField(self, types, modes): ...\n def _processLayerNameField(self, layers): ...\n def _processPathNameField(self, paths): ...\n def _processImagesField(self, images, frames, filenames, layer): ...\n def getDbVersion(self): ...\n def getPath(self, path_string=None, id=None, create=False, absolute=False): ...\n def getPaths(self, path_string=None, base_path=None, id=None): ...\n def setPath(self, path_string=None, id=None): ...\n def deletePaths(self, path_string=None, base_path=None, id=None): ...\n def getLayer(self, layer_name=None, base_layer=None, id=None, create=False): ...\n def getLayers(self, layer_name=None, base_layer=None, id=None): ...\n def setLayer(self, layer_name=None, base_layer=None, id=None): ...\n def deleteLayers(self, layer_name=None, base_layer=None, id=None): ...\n def getImageCount(self): ...\n def getImage(self, frame=None, filename=None, id=None, layer=None): ...\n def getImages(self, frame=None, filename=None, ext=None, external_id=None, timestamp=None, width=None, height=None, path=None, layer=None, order_by='sort_index'): ...\n def getImageIterator(self, start_frame=0, end_frame=None, skip=1, layer=1): ...\n def setImage(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer='default', sort_index=None): ...\n def deleteImages(self, filename=None, path=None, frame=None, external_id=None, timestamp=None, width=None, height=None, id=None, layer=None): ...\n def getTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getTrack(self, id): ...\n def setTrack(self, type, style=None, text=None, hidden=None, id=None, uid=None): ...\n def deleteTracks(self, type=None, text=None, hidden=None, id=None): ...\n def getMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMarkerType(self, name=None, id=None): ...\n def setMarkerType(self, name=None, color=None, mode=None, style=None, text=None, hidden=None, id=None): ...\n def deleteMarkerTypes(self, name=None, color=None, mode=None, text=None, hidden=None, id=None): ...\n def getMaskType(self, name=None, color=None, index=None, id=None): ...\n def getMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def setMaskType(self, name=None, color=None, index=None, id=None): ...\n def deleteMaskTypes(self, name=None, color=None, index=None, id=None): ...\n def getMask(self, image=None, frame=None, filename=None, id=None, layer=None, create=False): ...\n def getMasks(self, image=None, frame=None, filename=None, id=None, layer=None, order_by='sort_index'): ...\n def setMask(self, image=None, frame=None, filename=None, data=None, id=None, layer=None, checkShape=False): ...\n def deleteMasks(self, image=None, frame=None, filename=None, id=None, layer=None): ...\n def getMarker(self, id): ...\n def getMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def setMarker(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def setMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, style=None, text=None, id=None, layer=None): ...\n def deleteMarkers(self, image=None, frame=None, filename=None, x=None, y=None, type=None, processed=None, track=None, text=None, id=None, layer=None): ...\n def getLine(self, id): ...\n def getLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def setLine(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteLines(self, image=None, frame=None, filename=None, x1=None, y1=None, x2=None, y2=None, type=None, processed=None, text=None, id=None): ...\n def getRectangle(self, id): ...\n def getRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setRectangle(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteRectangles(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getEllipse(self, id): ...\n def getEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setEllipse(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deleteEllipses(self, image=None, frame=None, filename=None, x=None, y=None, width=None, height=None, angle=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def getPolygon(self, id): ...\n def getPolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setPolygon(self, image=None, frame=None, filename=None, points=None, type=None, closed=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def setPolygons(self, image=None, frame=None, filename=None, points=None, type=None, processed=None, style=None, text=None, id=None, layer=None): ...\n def deletePolygons(self, image=None, frame=None, filename=None, type=None, processed=None, text=None, id=None, layer=None): ...\n def setOffset(self, image, x, y): ...\n def deleteOffsets(self, image=None): ...\n def setTag(self, name=None, id=None): ...\n def getTag(self, name=None, id=None): ...\n def getTags(self, name=None, id=None): ...\n def deleteTags(self, name=None, id=None): ...\n def getAnnotation(self, image=None, frame=None, filename=None, id=None, create=False): ...\n def getAnnotations(self, image=None, frame=None, filename=None, timestamp=None, tag=None, comment=None, rating=None, id=None): ...\n def setAnnotation(self, image=None, frame=None, filename=None, timestamp=None, comment=None, rating=None, id=None, layer=None): ...\n def mergeWith(self, other_db): ...\n def getTracksNanPadded(self, type=None, id=None, start_frame=None, end_frame=None, skip=None, layer=None, apply_offset=False): ...\n def setTracksNanPadded(self, nan_padded, track_type, layer=None, start_frame=0, clear_tracks_before=True): ...\n def __enter__(self): ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n def __call__(self, *args, **kwargs): ...\n\n self._database_filename = database_filename\n self.base_model = BaseModel\n self.table_meta = Meta\n self.table_path = Path\n self.table_layer = Layer\n self.table_image = Image\n self.table_option = Option\n self._tables = [Meta, Path, Layer, Image, Option]\n self.table_offset = Offset\n self.table_marker = Marker\n self.table_line = Line\n self.table_rectangle = Rectangle\n self.table_ellipse = Ellipse\n self.table_polygon = Polygon\n self.table_polygon_point = PolygonPoint\n self.table_track = Track\n self.table_markertype = MarkerType\n self.table_mask = Mask\n self.table_masktype = MaskType\n self.table_annotation = Annotation\n self.table_tag = Tag\n self.table_tagassociation = TagAssociation\n\n db = None\n _reader = None\n _current_version = '22'\n _database_filename = None\n _next_sort_index = 0\n _SQLITE_MAX_VARIABLE_NUMBER = None\n _config = None\n _buffer = None\n TYPE_Normal = 0\n TYPE_Marker = 0\n TYPE_Rect = 1\n TYPE_Line = 2\n TYPE_Track = 4\n TYPE_Ellipse = 8\n TYPE_Polygon = 16\n", "repository": "fabrylab/clickpoints", "test_name": "test_deleteAnnotations", "smells": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_001579.py"} {"focal_file": "pytz/__init__.py", "focal_class": null, "focal_method": "timezone", "tests": "import unittest\n\nclass Test_timezone(unittest.TestCase):\n def test_zones(self):\n \"\"\"Check that the models do what we expect\"\"\"\n from pytz import NDB_NAMESPACE, Zoneinfo\n from google.appengine.ext import ndb\n est = pytz.timezone('Canada/Eastern')\n logging.error(est)\n EXPECT_ZONES = 589\n zones = Zoneinfo.query(namespace=NDB_NAMESPACE).count()\n self.assertEqual(zones, EXPECT_ZONES)\n", "method_code": "def timezone(zone):\n \"\"\" Return a datetime.tzinfo implementation for the given timezone \n\n >>> from datetime import datetime, timedelta\n >>> utc = timezone('UTC')\n >>> eastern = timezone('US/Eastern')\n >>> eastern.zone\n 'US/Eastern'\n >>> timezone(unicode('US/Eastern')) is eastern\n True\n >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)\n >>> loc_dt = utc_dt.astimezone(eastern)\n >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'\n >>> loc_dt.strftime(fmt)\n '2002-10-27 01:00:00 EST (-0500)'\n >>> (loc_dt - timedelta(minutes=10)).strftime(fmt)\n '2002-10-27 00:50:00 EST (-0500)'\n >>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt)\n '2002-10-27 01:50:00 EDT (-0400)'\n >>> (loc_dt + timedelta(minutes=10)).strftime(fmt)\n '2002-10-27 01:10:00 EST (-0500)'\n\n Raises UnknownTimeZoneError if passed an unknown zone.\n\n >>> try:\n ... timezone('Asia/Shangri-La')\n ... except UnknownTimeZoneError:\n ... print('Unknown')\n Unknown\n\n >>> try:\n ... timezone(unicode('\\\\N{TRADE MARK SIGN}'))\n ... except UnknownTimeZoneError:\n ... print('Unknown')\n Unknown\n\n \"\"\"\n if zone.upper() == 'UTC':\n return utc\n try:\n zone = ascii(zone)\n except UnicodeEncodeError:\n raise UnknownTimeZoneError(zone)\n zone = _unmunge_zone(zone)\n if zone not in _tzinfo_cache:\n if zone in all_timezones_set:\n fp = open_resource(zone)\n try:\n _tzinfo_cache[zone] = build_tzinfo(zone, fp)\n finally:\n fp.close()\n else:\n raise UnknownTimeZoneError(zone)\n return _tzinfo_cache[zone]", "context": "def timezone(zone): ...\ndef init_zoneinfo(): ...\ndef open_resource(name): ...\ndef resource_exists(name): ...\ndef setup_module(): ...\ndef teardown_module(): ...\ndef __open_resource(name): ...\ndef __resource_exists(name): ...\ndef timezone(zone): ...\ndef _unmunge_zone(zone): ...\ndef _UTC(): ...\ndef _p(*args): ...\ndef FixedOffset(offset, _tzinfos={}): ...\ndef _test(): ...\n", "repository": "sahuguet/govlab-intranet", "test_name": "test_zones", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001580.py"} {"focal_file": "pytz/tzinfo.py", "focal_class": null, "focal_method": "localize", "tests": "import unittest\n\nclass Test_localize(unittest.TestCase):\n def testLocalize(self):\n loc_tz = pytz.timezone('Europe/Amsterdam')\n loc_time = loc_tz.localize(datetime(1930, 5, 10, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'AMT+0020')\n loc_time = loc_tz.localize(datetime(1930, 5, 20, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'NST+0120')\n loc_time = loc_tz.localize(datetime(1940, 5, 10, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'NET+0020')\n loc_time = loc_tz.localize(datetime(1940, 5, 20, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CEST+0200')\n loc_time = loc_tz.localize(datetime(2004, 2, 1, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CET+0100')\n loc_time = loc_tz.localize(datetime(2004, 4, 1, 0, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CEST+0200')\n tz = pytz.timezone('Europe/Amsterdam')\n loc_time = loc_tz.localize(datetime(1943, 3, 29, 1, 59, 59))\n self.assertEqual(loc_time.strftime('%Z%z'), 'CET+0100')\n loc_tz = pytz.timezone('US/Eastern')\n loc_time = loc_tz.localize(datetime(1918, 10, 27, 1, 59, 59), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EDT-0400')\n loc_time = loc_tz.localize(datetime(1918, 10, 27, 1, 59, 59), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n self.assertRaises(pytz.AmbiguousTimeError, loc_tz.localize, datetime(1918, 10, 27, 1, 59, 59), is_dst=None)\n loc_time = loc_tz.localize(datetime(1918, 3, 31, 2, 0, 0), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n loc_time = loc_tz.localize(datetime(1918, 3, 31, 2, 0, 0), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EDT-0400')\n self.assertRaises(pytz.NonExistentTimeError, loc_tz.localize, datetime(1918, 3, 31, 2, 0, 0), is_dst=None)\n loc_time = loc_tz.localize(datetime(1942, 2, 9, 3, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'EWT-0400')\n loc_time = loc_tz.localize(datetime(1945, 8, 14, 19, 0, 0))\n self.assertEqual(loc_time.strftime('%Z%z'), 'EPT-0400')\n loc_time = loc_tz.localize(datetime(1945, 9, 30, 1, 0, 0), is_dst=1)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EPT-0400')\n loc_time = loc_tz.localize(datetime(1945, 9, 30, 1, 0, 0), is_dst=0)\n self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')\n", "method_code": " def localize(self, dt, is_dst=False):\n \"\"\"Convert naive time to local time\"\"\"\n if dt.tzinfo is not None:\n raise ValueError('Not naive datetime (tzinfo is already set)')\n return dt.replace(tzinfo=self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def localize(self, dt, is_dst=False): ...\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "sahuguet/govlab-intranet", "test_name": "testLocalize", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001581.py"} {"focal_file": "pytz/tzinfo.py", "focal_class": null, "focal_method": "normalize", "tests": "import unittest\n\nclass Test_normalize(unittest.TestCase):\n def testNormalize(self):\n tz = pytz.timezone('US/Eastern')\n dt = datetime(2004, 4, 4, 7, 0, 0, tzinfo=UTC).astimezone(tz)\n dt2 = dt - timedelta(minutes=10)\n self.assertEqual(dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'), '2004-04-04 02:50:00 EDT-0400')\n dt2 = tz.normalize(dt2)\n self.assertEqual(dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'), '2004-04-04 01:50:00 EST-0500')\n\n def test_normalize(self):\n other_tz = pytz.timezone('Europe/Paris')\n self.assertTrue(self.tz is not other_tz)\n dt = datetime(2012, 3, 26, 12, 0)\n other_dt = other_tz.localize(dt)\n local_dt = self.tz.normalize(other_dt)\n self.assertTrue(local_dt.tzinfo is not other_dt.tzinfo)\n self.assertNotEqual(local_dt.replace(tzinfo=None), other_dt.replace(tzinfo=None))\n", "method_code": " def normalize(self, dt, is_dst=False):\n \"\"\"Correct the timezone information on the given datetime.\n \n This is normally a no-op, as StaticTzInfo timezones never have\n ambiguous cases to correct:\n \n >>> from pytz import timezone\n >>> gmt = timezone('GMT')\n >>> isinstance(gmt, StaticTzInfo)\n True\n >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt)\n >>> gmt.normalize(dt) is dt\n True\n \n The supported method of converting between timezones is to use\n datetime.astimezone(). Currently normalize() also works:\n \n >>> la = timezone('America/Los_Angeles')\n >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3))\n >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'\n >>> gmt.normalize(dt).strftime(fmt)\n '2011-05-07 08:02:03 GMT (+0000)'\n \"\"\"\n if dt.tzinfo is self:\n return dt\n if dt.tzinfo is None:\n raise ValueError('Naive time - no tzinfo set')\n return dt.astimezone(self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def normalize(self, dt, is_dst=False): ...\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def localize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "sahuguet/govlab-intranet", "test_name": "testNormalize", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001582.py"} {"focal_file": "pytz/tzinfo.py", "focal_class": null, "focal_method": "fromutc", "tests": "import unittest\n\nclass Test_fromutc(unittest.TestCase):\n def test_fromutc(self):\n dt1 = datetime(2011, 10, 31)\n dt2 = self.tz.localize(dt1)\n for dt in [dt1, dt2]:\n loc_dt = self.tz.fromutc(dt)\n loc_dt2 = pytz.utc.localize(dt1).astimezone(self.tz)\n self.assertEqual(loc_dt, loc_dt2)\n new_tz = pytz.timezone('Europe/Paris')\n self.assertTrue(self.tz is not new_tz)\n dt3 = new_tz.localize(dt1)\n self.assertRaises(ValueError, self.tz.fromutc, dt3)\n", "method_code": " def fromutc(self, dt):\n \"\"\"See datetime.tzinfo.fromutc\"\"\"\n if dt.tzinfo is not None and dt.tzinfo is not self:\n raise ValueError('fromutc: dt.tzinfo is not self')\n return (dt + self._utcoffset).replace(tzinfo=self)\n ", "context": "class StaticTzInfo(BaseTzInfo):\n def fromutc(self, dt): ...\n def utcoffset(self, dt, is_dst=None): ...\n def dst(self, dt, is_dst=None): ...\n def tzname(self, dt, is_dst=None): ...\n def localize(self, dt, is_dst=False): ...\n def normalize(self, dt, is_dst=False): ...\n def __repr__(self): ...\n def __reduce__(self): ...\n", "repository": "sahuguet/govlab-intranet", "test_name": "test_fromutc", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001583.py"} {"focal_file": "acme/acme/challenges.py", "focal_class": null, "focal_method": "uri", "tests": "import unittest\n\nclass Test_uri(unittest.TestCase):\n def test_uri(self):\n self.assertEqual('http://example.com/.well-known/acme-challenge/6tbIMBC5Anhl5bOlWT5ZFA', self.msg_http.uri('example.com'))\n self.assertEqual('https://example.com/.well-known/acme-challenge/6tbIMBC5Anhl5bOlWT5ZFA', self.msg_https.uri('example.com'))\n", "method_code": " def uri(self, domain):\n \"\"\"Create an URI to the provisioned resource.\n \n Forms an URI to the HTTPS server provisioned resource\n (containing :attr:`~SimpleHTTP.token`).\n \n :param unicode domain: Domain name being verified.\n \n \"\"\"\n return self._URI_TEMPLATE.format(scheme=self.scheme, domain=domain, path=self.path)\n ", "context": "class SimpleHTTPResponse(ChallengeResponse):\n def uri(self, domain): ...\n def good_path(self): ...\n def scheme(self): ...\n def port(self): ...\n def simple_verify(self, chall, domain, port=None): ...\n\n typ = 'simpleHttp'\n path = jose.Field('path')\n tls = jose.Field('tls', default=True, omitempty=True)\n URI_ROOT_PATH = '.well-known/acme-challenge'\n _URI_TEMPLATE = '{scheme}://{domain}/' + URI_ROOT_PATH + '/{path}'\n MAX_PATH_LEN = 25\n CONTENT_TYPE = 'text/plain'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_uri", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001584.py"} {"focal_file": "acme/acme/challenges.py", "focal_class": null, "focal_method": "simple_verify", "tests": "import unittest\n\nclass Test_simple_verify(unittest.TestCase):\n @mock.patch('acme.challenges.requests.get')\n def test_simple_verify_good_token(self, mock_get):\n for resp in (self.resp_http, self.resp_https):\n mock_get.reset_mock()\n mock_get.return_value = mock.MagicMock(text=self.chall.token, headers=self.good_headers)\n self.assertTrue(resp.simple_verify(self.chall, 'local'))\n mock_get.assert_called_once_with(resp.uri('local'), verify=False)\n\n @mock.patch('acme.challenges.requests.get')\n def test_simple_verify_bad_token(self, mock_get):\n mock_get.return_value = mock.MagicMock(text=self.chall.token + '!', headers=self.good_headers)\n self.assertFalse(self.resp_http.simple_verify(self.chall, 'local'))\n\n @mock.patch('acme.challenges.requests.get')\n def test_simple_verify_bad_content_type(self, mock_get):\n mock_get().text = self.chall.token\n self.assertFalse(self.resp_http.simple_verify(self.chall, 'local'))\n\n @mock.patch('acme.challenges.requests.get')\n def test_simple_verify_connection_error(self, mock_get):\n mock_get.side_effect = requests.exceptions.RequestException\n self.assertFalse(self.resp_http.simple_verify(self.chall, 'local'))\n\n @mock.patch('acme.challenges.requests.get')\n def test_simple_verify_port(self, mock_get):\n self.resp_http.simple_verify(self.chall, 'local', 4430)\n self.assertEqual('local:4430', urllib_parse.urlparse(mock_get.mock_calls[0][1][0]).netloc)\n\n @mock.patch('acme.challenges.DVSNIResponse.verify_cert')\n def test_simple_verify(self, mock_verify_cert):\n chall = mock.Mock()\n chall.probe_cert.return_value = mock.sentinel.cert\n mock_verify_cert.return_value = 'x'\n self.assertEqual('x', self.msg.simple_verify(chall, mock.sentinel.domain, mock.sentinel.key))\n chall.probe_cert.assert_called_once_with(domain=mock.sentinel.domain)\n self.msg.verify_cert.assert_called_once_with(chall, mock.sentinel.domain, mock.sentinel.key, mock.sentinel.cert)\n", "method_code": " def simple_verify(self, chall, domain, port=None):\n \"\"\"Simple verify.\n \n According to the ACME specification, \"the ACME server MUST\n ignore the certificate provided by the HTTPS server\", so\n ``requests.get`` is called with ``verify=False``.\n \n :param .SimpleHTTP chall: Corresponding challenge.\n :param unicode domain: Domain name being verified.\n :param int port: Port used in the validation.\n \n :returns: ``True`` iff validation is successful, ``False``\n otherwise.\n :rtype: bool\n \n \"\"\"\n if port is not None and port != self.port:\n logger.warn('Using non-standard port for SimpleHTTP verification: %s', port)\n domain += ':{0}'.format(port)\n uri = self.uri(domain)\n logger.debug('Verifying %s at %s...', chall.typ, uri)\n try:\n http_response = requests.get(uri, verify=False)\n except requests.exceptions.RequestException as error:\n logger.error('Unable to reach %s: %s', uri, error)\n return False\n logger.debug('Received %s. Headers: %s', http_response, http_response.headers)\n good_token = http_response.text == chall.token\n if not good_token:\n logger.error('Unable to verify %s! Expected: %r, returned: %r.', uri, chall.token, http_response.text)\n good_ct = self.CONTENT_TYPE == http_response.headers.get('Content-Type', self.CONTENT_TYPE)\n return self.good_path and good_ct and good_token\n ", "context": "class SimpleHTTPResponse(ChallengeResponse):\n def simple_verify(self, chall, domain, port=None): ...\n def good_path(self): ...\n def scheme(self): ...\n def port(self): ...\n def uri(self, domain): ...\n\n typ = 'simpleHttp'\n path = jose.Field('path')\n tls = jose.Field('tls', default=True, omitempty=True)\n URI_ROOT_PATH = '.well-known/acme-challenge'\n _URI_TEMPLATE = '{scheme}://{domain}/' + URI_ROOT_PATH + '/{path}'\n MAX_PATH_LEN = 25\n CONTENT_TYPE = 'text/plain'\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001585.py"} {"focal_file": "acme/acme/challenges.py", "focal_class": null, "focal_method": "probe_cert", "tests": "import unittest\n\nclass Test_probe_cert(unittest.TestCase):\n @mock.patch('acme.challenges.socket.gethostbyname')\n @mock.patch('acme.challenges.crypto_util._probe_sni')\n def test_probe_cert(self, mock_probe_sni, mock_gethostbyname):\n mock_gethostbyname.return_value = '127.0.0.1'\n self.msg.probe_cert('foo.com')\n mock_gethostbyname.assert_called_once_with('foo.com')\n mock_probe_sni.assert_called_once_with(host='127.0.0.1', port=self.msg.PORT, name=b'a82d5ff8ef740d12881f6d3c2277ab2e.acme.invalid')\n self.msg.probe_cert('foo.com', host='8.8.8.8')\n mock_probe_sni.assert_called_with(host='8.8.8.8', port=mock.ANY, name=mock.ANY)\n self.msg.probe_cert('foo.com', port=1234)\n mock_probe_sni.assert_called_with(host=mock.ANY, port=1234, name=mock.ANY)\n self.msg.probe_cert('foo.com', bar='baz')\n mock_probe_sni.assert_called_with(host=mock.ANY, port=mock.ANY, name=mock.ANY, bar='baz')\n self.msg.probe_cert('foo.com', name=b'xxx')\n mock_probe_sni.assert_called_with(host=mock.ANY, port=mock.ANY, name=b'a82d5ff8ef740d12881f6d3c2277ab2e.acme.invalid')\n", "method_code": " def probe_cert(self, domain, **kwargs):\n \"\"\"Probe DVSNI challenge certificate.\"\"\"\n host = socket.gethostbyname(domain)\n logging.debug('%s resolved to %s', domain, host)\n kwargs.setdefault('host', host)\n kwargs.setdefault('port', self.PORT)\n kwargs['name'] = self.nonce_domain\n return crypto_util._probe_sni(**kwargs)\n ", "context": "class DVSNI(DVChallenge):\n def probe_cert(self, domain, **kwargs): ...\n def nonce_domain(self): ...\n\n typ = 'dvsni'\n DOMAIN_SUFFIX = b'.acme.invalid'\n R_SIZE = 32\n NONCE_SIZE = 16\n PORT = 443\n r = jose.Field('r', encoder=jose.encode_b64jose, decoder=functools.partial(jose.decode_b64jose, size=R_SIZE))\n nonce = jose.Field('nonce', encoder=jose.encode_hex16, decoder=functools.partial(functools.partial(jose.decode_hex16, size=NONCE_SIZE)))\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001586.py"} {"focal_file": "acme/acme/challenges.py", "focal_class": null, "focal_method": "z_domain", "tests": "import unittest\n\nclass Test_z_domain(unittest.TestCase):\n def test_z_and_domain(self):\n self.assertEqual(self.z, self.msg.z(self.chall))\n self.assertEqual(self.z + b'.acme.invalid', self.msg.z_domain(self.chall))\n", "method_code": " def z_domain(self, chall):\n \"\"\"Domain name for certificate subjectAltName.\n \n :rtype bytes:\n \n \"\"\"\n return self.z(chall) + self.DOMAIN_SUFFIX\n ", "context": "class DVSNIResponse(ChallengeResponse):\n def z_domain(self, chall): ...\n def __init__(self, s=None, *args, **kwargs): ...\n def z(self, chall): ...\n def gen_cert(self, chall, domain, key): ...\n def simple_verify(self, chall, domain, public_key, **kwargs): ...\n def verify_cert(self, chall, domain, public_key, cert): ...\n\n typ = 'dvsni'\n DOMAIN_SUFFIX = DVSNI.DOMAIN_SUFFIX\n S_SIZE = 32\n s = jose.Field('s', encoder=jose.encode_b64jose, decoder=functools.partial(jose.decode_b64jose, size=S_SIZE))\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_z_and_domain", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001587.py"} {"focal_file": "acme/acme/challenges.py", "focal_class": null, "focal_method": "verify_cert", "tests": "import unittest\n\nclass Test_verify_cert(unittest.TestCase):\n def test_gen_verify_cert_postive_no_key(self):\n cert = self.msg.gen_cert(self.chall, self.domain, self.key)\n self.assertTrue(self.msg.verify_cert(self.chall, self.domain, public_key=None, cert=cert))\n\n def test_gen_verify_cert_negative(self):\n cert = self.msg.gen_cert(self.chall, self.domain + 'x', self.key)\n self.assertFalse(self.msg.verify_cert(self.chall, self.domain, public_key=None, cert=cert))\n", "method_code": " def verify_cert(self, chall, domain, public_key, cert):\n \"\"\"Verify DVSNI certificate.\n \n :param .challenges.DVSNI chall: Corresponding challenge.\n :param str domain: Domain name being validated.\n :param public_key: Public key for the key pair\n being authorized. If ``None`` key verification is not\n performed!\n :type public_key:\n `~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`\n or\n `~cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey`\n or\n `~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey`\n wrapped in `.ComparableKey\n :param OpenSSL.crypto.X509 cert:\n \n :returns: ``True`` iff client's control of the domain has been\n verified, ``False`` otherwise.\n :rtype: bool\n \n \"\"\"\n sans = crypto_util._pyopenssl_cert_or_req_san(cert)\n logging.debug('Certificate %s. SANs: %s', cert.digest('sha1'), sans)\n cert = x509.load_der_x509_certificate(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, cert), default_backend())\n if public_key is None:\n logging.warn('No key verification is performed')\n elif public_key != jose.ComparableKey(cert.public_key()):\n return False\n return domain in sans and self.z_domain(chall).decode() in sans\n ", "context": "class DVSNIResponse(ChallengeResponse):\n def verify_cert(self, chall, domain, public_key, cert): ...\n def __init__(self, s=None, *args, **kwargs): ...\n def z(self, chall): ...\n def z_domain(self, chall): ...\n def gen_cert(self, chall, domain, key): ...\n def simple_verify(self, chall, domain, public_key, **kwargs): ...\n\n typ = 'dvsni'\n DOMAIN_SUFFIX = DVSNI.DOMAIN_SUFFIX\n S_SIZE = 32\n s = jose.Field('s', encoder=jose.encode_b64jose, decoder=functools.partial(jose.decode_b64jose, size=S_SIZE))\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_gen_verify_cert_postive_no_key", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001588.py"} {"focal_file": "acme/acme/challenges.py", "focal_class": null, "focal_method": "verify", "tests": "import unittest\n\nclass Test_verify(unittest.TestCase):\n def test_verify(self):\n self.assertTrue(self.msg.verify())\n", "method_code": " def verify(self):\n \"\"\"Verify the challenge.\"\"\"\n return self.signature.verify(self.nonce)\n \n typ = 'proofOfPossession'\n NONCE_SIZE = ProofOfPossession.NONCE_SIZE\n nonce = jose.Field('nonce', encoder=jose.encode_b64jose, decoder=functools.partial(jose.decode_b64jose, size=NONCE_SIZE))\n signature = jose.Field('signature', decoder=other.Signature.from_json)\n", "context": "class ProofOfPossessionResponse(ChallengeResponse):\n def verify(self): ...", "repository": "stewnorriss/letsencrypt", "test_name": "test_verify", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001589.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "register", "tests": "import unittest\n\nclass Test_register(unittest.TestCase):\n def test_register(self):\n self.response.status_code = http_client.CREATED\n self.response.json.return_value = self.regr.body.to_json()\n self.response.headers['Location'] = self.regr.uri\n self.response.links.update({'next': {'url': self.regr.new_authzr_uri}, 'terms-of-service': {'url': self.regr.terms_of_service}})\n self.assertEqual(self.regr, self.client.register(self.new_reg))\n reg_wrong_key = self.regr.body.update(key=KEY2.public_key())\n self.response.json.return_value = reg_wrong_key.to_json()\n self.assertRaises(errors.UnexpectedUpdate, self.client.register, self.new_reg)\n", "method_code": " def register(self, new_reg=None):\n \"\"\"Register.\n \n :param .NewRegistration new_reg:\n \n :returns: Registration Resource.\n :rtype: `.RegistrationResource`\n \n :raises .UnexpectedUpdate:\n \n \"\"\"\n new_reg = messages.NewRegistration() if new_reg is None else new_reg\n assert isinstance(new_reg, messages.NewRegistration)\n response = self.net.post(self.new_reg_uri, new_reg)\n assert response.status_code == http_client.CREATED\n regr = self._regr_from_response(response)\n if regr.body.key != self.key.public_key() or regr.body.contact != new_reg.contact:\n raise errors.UnexpectedUpdate(regr)\n return regr\n ", "context": "class Client(object):\n def register(self, new_reg=None): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_register", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001590.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "update_registration", "tests": "import unittest\n\nclass Test_update_registration(unittest.TestCase):\n def test_update_registration(self):\n self.response.headers['Location'] = self.regr.uri\n self.response.json.return_value = self.regr.body.to_json()\n self.assertEqual(self.regr, self.client.update_registration(self.regr))\n self.response.json.return_value = self.regr.body.update(contact=()).to_json()\n self.assertRaises(errors.UnexpectedUpdate, self.client.update_registration, self.regr)\n", "method_code": " def update_registration(self, regr):\n \"\"\"Update registration.\n \n :pram regr: Registration Resource.\n :type regr: `.RegistrationResource`\n \n :returns: Updated Registration Resource.\n :rtype: `.RegistrationResource`\n \n \"\"\"\n response = self.net.post(regr.uri, messages.UpdateRegistration(**dict(regr.body)))\n updated_regr = self._regr_from_response(response, uri=regr.uri, new_authzr_uri=regr.new_authzr_uri, terms_of_service=regr.terms_of_service)\n if updated_regr != regr:\n raise errors.UnexpectedUpdate(regr)\n return updated_regr\n ", "context": "class Client(object):\n def update_registration(self, regr): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_update_registration", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001591.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "agree_to_tos", "tests": "import unittest\n\nclass Test_agree_to_tos(unittest.TestCase):\n def test_agree_to_tos(self):\n self.client.update_registration = mock.Mock()\n self.client.agree_to_tos(self.regr)\n regr = self.client.update_registration.call_args[0][0]\n self.assertEqual(self.regr.terms_of_service, regr.body.agreement)\n", "method_code": " def agree_to_tos(self, regr):\n \"\"\"Agree to the terms-of-service.\n \n Agree to the terms-of-service in a Registration Resource.\n \n :param regr: Registration Resource.\n :type regr: `.RegistrationResource`\n \n :returns: Updated Registration Resource.\n :rtype: `.RegistrationResource`\n \n \"\"\"\n return self.update_registration(regr.update(body=regr.body.update(agreement=regr.terms_of_service)))\n ", "context": "class Client(object):\n def agree_to_tos(self, regr): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_agree_to_tos", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001592.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "request_challenges", "tests": "import unittest\n\nclass Test_request_challenges(unittest.TestCase):\n def test_request_challenges(self):\n self.response.status_code = http_client.CREATED\n self.response.headers['Location'] = self.authzr.uri\n self.response.json.return_value = self.authz.to_json()\n self.response.links = {'next': {'url': self.authzr.new_cert_uri}}\n self.client.request_challenges(self.identifier, self.authzr.uri)\n self.response.json.return_value = self.authz.update(identifier=self.identifier.update(value='foo')).to_json()\n self.assertRaises(errors.UnexpectedUpdate, self.client.request_challenges, self.identifier, self.authzr.uri)\n", "method_code": " def request_challenges(self, identifier, new_authzr_uri):\n \"\"\"Request challenges.\n \n :param identifier: Identifier to be challenged.\n :type identifier: `.messages.Identifier`\n \n :param str new_authzr_uri: new-authorization URI\n \n :returns: Authorization Resource.\n :rtype: `.AuthorizationResource`\n \n \"\"\"\n new_authz = messages.NewAuthorization(identifier=identifier)\n response = self.net.post(new_authzr_uri, new_authz)\n assert response.status_code == http_client.CREATED\n return self._authzr_from_response(response, identifier)\n ", "context": "class Client(object):\n def request_challenges(self, identifier, new_authzr_uri): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_request_challenges", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001593.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "request_domain_challenges", "tests": "import unittest\n\nclass Test_request_domain_challenges(unittest.TestCase):\n def test_request_domain_challenges(self):\n self.client.request_challenges = mock.MagicMock()\n self.assertEqual(self.client.request_challenges(self.identifier), self.client.request_domain_challenges('example.com', self.regr))\n", "method_code": " def request_domain_challenges(self, domain, new_authz_uri):\n \"\"\"Request challenges for domain names.\n \n This is simply a convenience function that wraps around\n `request_challenges`, but works with domain names instead of\n generic identifiers.\n \n :param str domain: Domain name to be challenged.\n :param str new_authzr_uri: new-authorization URI\n \n :returns: Authorization Resource.\n :rtype: `.AuthorizationResource`\n \n \"\"\"\n return self.request_challenges(messages.Identifier(typ=messages.IDENTIFIER_FQDN, value=domain), new_authz_uri)\n ", "context": "class Client(object):\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_request_domain_challenges", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001594.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "answer_challenge", "tests": "import unittest\n\nclass Test_answer_challenge(unittest.TestCase):\n def test_answer_challenge(self):\n self.response.links['up'] = {'url': self.challr.authzr_uri}\n self.response.json.return_value = self.challr.body.to_json()\n chall_response = challenges.DNSResponse()\n self.client.answer_challenge(self.challr.body, chall_response)\n self.assertRaises(errors.UnexpectedUpdate, self.client.answer_challenge, self.challr.body.update(uri='foo'), chall_response)\n", "method_code": " def answer_challenge(self, challb, response):\n \"\"\"Answer challenge.\n \n :param challb: Challenge Resource body.\n :type challb: `.ChallengeBody`\n \n :param response: Corresponding Challenge response\n :type response: `.challenges.ChallengeResponse`\n \n :returns: Challenge Resource with updated body.\n :rtype: `.ChallengeResource`\n \n :raises .UnexpectedUpdate:\n \n \"\"\"\n response = self.net.post(challb.uri, response)\n try:\n authzr_uri = response.links['up']['url']\n except KeyError:\n raise errors.ClientError('\"up\" Link header missing')\n challr = messages.ChallengeResource(authzr_uri=authzr_uri, body=messages.ChallengeBody.from_json(response.json()))\n if challr.uri != challb.uri:\n raise errors.UnexpectedUpdate(challr.uri)\n return challr\n ", "context": "class Client(object):\n def answer_challenge(self, challb, response): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_answer_challenge", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001595.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "retry_after", "tests": "import unittest\n\nclass Test_retry_after(unittest.TestCase):\n def test_retry_after_date(self):\n self.response.headers['Retry-After'] = 'Fri, 31 Dec 1999 23:59:59 GMT'\n self.assertEqual(datetime.datetime(1999, 12, 31, 23, 59, 59), self.client.retry_after(response=self.response, default=10))\n\n @mock.patch('acme.client.datetime')\n def test_retry_after_invalid(self, dt_mock):\n dt_mock.datetime.now.return_value = datetime.datetime(2015, 3, 27)\n dt_mock.timedelta = datetime.timedelta\n self.response.headers['Retry-After'] = 'foooo'\n self.assertEqual(datetime.datetime(2015, 3, 27, 0, 0, 10), self.client.retry_after(response=self.response, default=10))\n\n @mock.patch('acme.client.datetime')\n def test_retry_after_seconds(self, dt_mock):\n dt_mock.datetime.now.return_value = datetime.datetime(2015, 3, 27)\n dt_mock.timedelta = datetime.timedelta\n self.response.headers['Retry-After'] = '50'\n self.assertEqual(datetime.datetime(2015, 3, 27, 0, 0, 50), self.client.retry_after(response=self.response, default=10))\n\n @mock.patch('acme.client.datetime')\n def test_retry_after_missing(self, dt_mock):\n dt_mock.datetime.now.return_value = datetime.datetime(2015, 3, 27)\n dt_mock.timedelta = datetime.timedelta\n self.assertEqual(datetime.datetime(2015, 3, 27, 0, 0, 10), self.client.retry_after(response=self.response, default=10))\n", "method_code": " def retry_after(cls, response, default):\n \"\"\"Compute next `poll` time based on response ``Retry-After`` header.\n \n :param response: Response from `poll`.\n :type response: `requests.Response`\n \n :param int default: Default value (in seconds), used when\n ``Retry-After`` header is not present or invalid.\n \n :returns: Time point when next `poll` should be performed.\n :rtype: `datetime.datetime`\n \n \"\"\"\n retry_after = response.headers.get('Retry-After', str(default))\n try:\n seconds = int(retry_after)\n except ValueError:\n decoded = werkzeug.parse_date(retry_after)\n if decoded is None:\n seconds = default\n else:\n return decoded\n return datetime.datetime.now() + datetime.timedelta(seconds=seconds)\n ", "context": "class Client(object):\n @classmethod\n def retry_after(cls, response, default): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_retry_after_date", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001596.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "poll", "tests": "import unittest\n\nclass Test_poll(unittest.TestCase):\n def test_poll(self):\n self.response.json.return_value = self.authzr.body.to_json()\n self.assertEqual((self.authzr, self.response), self.client.poll(self.authzr))\n self.response.json.return_value = self.authz.update(identifier=self.identifier.update(value='foo')).to_json()\n self.assertRaises(errors.UnexpectedUpdate, self.client.poll, self.authzr)\n", "method_code": " def poll(self, authzr):\n \"\"\"Poll Authorization Resource for status.\n \n :param authzr: Authorization Resource\n :type authzr: `.AuthorizationResource`\n \n :returns: Updated Authorization Resource and HTTP response.\n \n :rtype: (`.AuthorizationResource`, `requests.Response`)\n \n \"\"\"\n response = self.net.get(authzr.uri)\n updated_authzr = self._authzr_from_response(response, authzr.body.identifier, authzr.uri, authzr.new_cert_uri)\n return (updated_authzr, response)\n ", "context": "class Client(object):\n def poll(self, authzr): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_poll", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001597.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "request_issuance", "tests": "import unittest\n\nclass Test_request_issuance(unittest.TestCase):\n def test_request_issuance(self):\n self.response.content = CERT_DER\n self.response.headers['Location'] = self.certr.uri\n self.response.links['up'] = {'url': self.certr.cert_chain_uri}\n self.assertEqual(self.certr, self.client.request_issuance(messages_test.CSR, (self.authzr,)))\n\n def test_request_issuance_missing_up(self):\n self.response.content = CERT_DER\n self.response.headers['Location'] = self.certr.uri\n self.assertEqual(self.certr.update(cert_chain_uri=None), self.client.request_issuance(messages_test.CSR, (self.authzr,)))\n", "method_code": " def request_issuance(self, csr, authzrs):\n \"\"\"Request issuance.\n \n :param csr: CSR\n :type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`\n \n :param authzrs: `list` of `.AuthorizationResource`\n \n :returns: Issued certificate\n :rtype: `.messages.CertificateResource`\n \n \"\"\"\n assert authzrs, 'Authorizations list is empty'\n logger.debug('Requesting issuance...')\n req = messages.CertificateRequest(csr=csr, authorizations=tuple((authzr.uri for authzr in authzrs)))\n content_type = self.DER_CONTENT_TYPE\n response = self.net.post(authzrs[0].new_cert_uri, req, content_type=content_type, headers={'Accept': content_type})\n cert_chain_uri = response.links.get('up', {}).get('url')\n try:\n uri = response.headers['Location']\n except KeyError:\n raise errors.ClientError('\"Location\" Header missing')\n return messages.CertificateResource(uri=uri, authzrs=authzrs, cert_chain_uri=cert_chain_uri, body=jose.ComparableX509(OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, response.content)))\n ", "context": "class Client(object):\n def request_issuance(self, csr, authzrs): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_request_issuance", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001598.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "poll_and_request_issuance", "tests": "import unittest\n\nclass Test_poll_and_request_issuance(unittest.TestCase):\n @mock.patch('acme.client.datetime')\n @mock.patch('acme.client.time')\n def test_poll_and_request_issuance(self, time_mock, dt_mock):\n clock = mock.MagicMock(dt=datetime.datetime(2015, 3, 27))\n\n def sleep(seconds):\n \"\"\"increment clock\"\"\"\n clock.dt += datetime.timedelta(seconds=seconds)\n time_mock.sleep.side_effect = sleep\n\n def now():\n \"\"\"return current clock value\"\"\"\n return clock.dt\n dt_mock.datetime.now.side_effect = now\n dt_mock.timedelta = datetime.timedelta\n\n def poll(authzr):\n authzr.times.append(clock.dt)\n clock.dt += datetime.timedelta(seconds=2)\n if not authzr.retries:\n done = mock.MagicMock(uri=authzr.uri, times=authzr.times)\n done.body.status = messages.STATUS_VALID\n return (done, [])\n return (mock.MagicMock(retries=authzr.retries[1:], uri=authzr.uri + '.', times=authzr.times), authzr.retries[0])\n self.client.poll = mock.MagicMock(side_effect=poll)\n mintime = 7\n\n def retry_after(response, default):\n self.assertEqual(default, mintime)\n return clock.dt + datetime.timedelta(seconds=response)\n self.client.retry_after = mock.MagicMock(side_effect=retry_after)\n\n def request_issuance(csr, authzrs):\n return (csr, authzrs)\n self.client.request_issuance = mock.MagicMock(side_effect=request_issuance)\n csr = mock.MagicMock()\n authzrs = (mock.MagicMock(uri='a', times=[], retries=(8, 20, 30)), mock.MagicMock(uri='b', times=[], retries=(5,)))\n cert, updated_authzrs = self.client.poll_and_request_issuance(csr, authzrs, mintime=mintime)\n self.assertTrue(cert[0] is csr)\n self.assertTrue(cert[1] is updated_authzrs)\n self.assertEqual(updated_authzrs[0].uri, 'a...')\n self.assertEqual(updated_authzrs[1].uri, 'b.')\n self.assertEqual(updated_authzrs[0].times, [datetime.datetime(2015, 3, 27), datetime.datetime(2015, 3, 27, 0, 0, 11), datetime.datetime(2015, 3, 27, 0, 0, 33), datetime.datetime(2015, 3, 27, 0, 1, 5)])\n self.assertEqual(updated_authzrs[1].times, [datetime.datetime(2015, 3, 27, 0, 0, 2), datetime.datetime(2015, 3, 27, 0, 0, 9)])\n self.assertEqual(clock.dt, datetime.datetime(2015, 3, 27, 0, 1, 7))\n", "method_code": " def poll_and_request_issuance(self, csr, authzrs, mintime=5):\n \"\"\"Poll and request issuance.\n \n This function polls all provided Authorization Resource URIs\n until all challenges are valid, respecting ``Retry-After`` HTTP\n headers, and then calls `request_issuance`.\n \n .. todo:: add `max_attempts` or `timeout`\n \n :param csr: CSR.\n :type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`\n \n :param authzrs: `list` of `.AuthorizationResource`\n \n :param int mintime: Minimum time before next attempt, used if\n ``Retry-After`` is not present in the response.\n \n :returns: ``(cert, updated_authzrs)`` `tuple` where ``cert`` is\n the issued certificate (`.messages.CertificateResource.),\n and ``updated_authzrs`` is a `tuple` consisting of updated\n Authorization Resources (`.AuthorizationResource`) as\n present in the responses from server, and in the same order\n as the input ``authzrs``.\n :rtype: `tuple`\n \n \"\"\"\n waiting = [(datetime.datetime.now(), authzr) for authzr in authzrs]\n updated = dict(((authzr, authzr) for authzr in authzrs))\n while waiting:\n when, authzr = heapq.heappop(waiting)\n now = datetime.datetime.now()\n if when > now:\n seconds = (when - now).seconds\n logger.debug('Sleeping for %d seconds', seconds)\n time.sleep(seconds)\n updated_authzr, response = self.poll(updated[authzr])\n updated[authzr] = updated_authzr\n if updated_authzr.body.status != messages.STATUS_VALID:\n heapq.heappush(waiting, (self.retry_after(response, default=mintime), authzr))\n updated_authzrs = tuple((updated[authzr] for authzr in authzrs))\n return (self.request_issuance(csr, updated_authzrs), updated_authzrs)\n ", "context": "class Client(object):\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001599.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "check_cert", "tests": "import unittest\n\nclass Test_check_cert(unittest.TestCase):\n def test_check_cert(self):\n self.response.headers['Location'] = self.certr.uri\n self.response.content = CERT_DER\n self.assertEqual(self.certr.update(body=messages_test.CERT), self.client.check_cert(self.certr))\n self.response.headers['Location'] = 'foo'\n self.assertRaises(errors.UnexpectedUpdate, self.client.check_cert, self.certr)\n", "method_code": " def check_cert(self, certr):\n \"\"\"Check for new cert.\n \n :param certr: Certificate Resource\n :type certr: `.CertificateResource`\n \n :returns: Updated Certificate Resource.\n :rtype: `.CertificateResource`\n \n \"\"\"\n response, cert = self._get_cert(certr.uri)\n if 'Location' not in response.headers:\n raise errors.ClientError('Location header missing')\n if response.headers['Location'] != certr.uri:\n raise errors.UnexpectedUpdate(response.text)\n return certr.update(body=cert)\n ", "context": "class Client(object):\n def check_cert(self, certr): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_check_cert", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001600.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "refresh", "tests": "import unittest\n\nclass Test_refresh(unittest.TestCase):\n def test_refresh(self):\n self.client.check_cert = mock.MagicMock()\n self.assertEqual(self.client.check_cert(self.certr), self.client.refresh(self.certr))\n", "method_code": " def refresh(self, certr):\n \"\"\"Refresh certificate.\n \n :param certr: Certificate Resource\n :type certr: `.CertificateResource`\n \n :returns: Updated Certificate Resource.\n :rtype: `.CertificateResource`\n \n \"\"\"\n return self.check_cert(certr)\n ", "context": "class Client(object):\n def refresh(self, certr): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def fetch_chain(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_refresh", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001601.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "fetch_chain", "tests": "import unittest\n\nclass Test_fetch_chain(unittest.TestCase):\n def test_fetch_chain(self):\n self.client._get_cert = mock.MagicMock()\n self.client._get_cert.return_value = ('response', 'certificate')\n self.assertEqual(self.client._get_cert(self.certr.cert_chain_uri)[1], self.client.fetch_chain(self.certr))\n\n def test_fetch_chain_no_up_link(self):\n self.assertTrue(self.client.fetch_chain(self.certr.update(cert_chain_uri=None)) is None)\n", "method_code": " def fetch_chain(self, certr):\n \"\"\"Fetch chain for certificate.\n \n :param certr: Certificate Resource\n :type certr: `.CertificateResource`\n \n :returns: Certificate chain, or `None` if no \"up\" Link was provided.\n :rtype: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`\n \n \"\"\"\n if certr.cert_chain_uri is not None:\n return self._get_cert(certr.cert_chain_uri)[1]\n else:\n return None\n ", "context": "class Client(object):\n def fetch_chain(self, certr): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def revoke(self, cert): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_fetch_chain", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001602.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "revoke", "tests": "import unittest\n\nclass Test_revoke(unittest.TestCase):\n def test_revoke(self):\n self.client.revoke(self.certr.body)\n self.net.post.assert_called_once_with(messages.Revocation.url(self.client.new_reg_uri), mock.ANY)\n", "method_code": " def revoke(self, cert):\n \"\"\"Revoke certificate.\n \n :param .ComparableX509 cert: `OpenSSL.crypto.X509` wrapped in\n `.ComparableX509`\n \n :raises .ClientError: If revocation is unsuccessful.\n \n \"\"\"\n response = self.net.post(messages.Revocation.url(self.new_reg_uri), messages.Revocation(certificate=cert))\n if response.status_code != http_client.OK:\n raise errors.ClientError('Successful revocation must return HTTP OK status')\n ", "context": "class Client(object):\n def revoke(self, cert): ...\n def __init__(self, new_reg_uri, key, alg=jose.RS256, verify_ssl=True, net=None): ...\n def _regr_from_response(cls, response, uri=None, new_authzr_uri=None, terms_of_service=None): ...\n def register(self, new_reg=None): ...\n def update_registration(self, regr): ...\n def agree_to_tos(self, regr): ...\n def _authzr_from_response(self, response, identifier, uri=None, new_cert_uri=None): ...\n def request_challenges(self, identifier, new_authzr_uri): ...\n def request_domain_challenges(self, domain, new_authz_uri): ...\n def answer_challenge(self, challb, response): ...\n def retry_after(cls, response, default): ...\n def poll(self, authzr): ...\n def request_issuance(self, csr, authzrs): ...\n def poll_and_request_issuance(self, csr, authzrs, mintime=5): ...\n def _get_cert(self, uri): ...\n def check_cert(self, certr): ...\n def refresh(self, certr): ...\n def fetch_chain(self, certr): ...\n\n self.new_reg_uri = new_reg_uri\n self.key = key\n self.net = ClientNetwork(key, alg, verify_ssl) if net is None else net\n\n DER_CONTENT_TYPE = 'application/pkix-cert'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_revoke", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001603.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "_wrap_in_jws", "tests": "import unittest\n\nclass Test_wrap_in_jws(unittest.TestCase):\n def test_wrap_in_jws(self):\n\n class MockJSONDeSerializable(jose.JSONDeSerializable):\n\n def __init__(self, value):\n self.value = value\n\n def to_partial_json(self):\n return {'foo': self.value}\n\n @classmethod\n def from_json(cls, value):\n pass\n jws_dump = self.net._wrap_in_jws(MockJSONDeSerializable('foo'), nonce=b'Tg')\n jws = acme_jws.JWS.json_loads(jws_dump)\n self.assertEqual(json.loads(jws.payload.decode()), {'foo': 'foo'})\n self.assertEqual(jws.signature.combined.nonce, b'Tg')\n", "method_code": " def _wrap_in_jws(self, obj, nonce):\n \"\"\"Wrap `JSONDeSerializable` object in JWS.\n \n .. todo:: Implement ``acmePath``.\n \n :param .JSONDeSerializable obj:\n :param bytes nonce:\n :rtype: `.JWS`\n \n \"\"\"\n jobj = obj.json_dumps().encode()\n logger.debug('Serialized JSON: %s', jobj)\n return jws.JWS.sign(payload=jobj, key=self.key, alg=self.alg, nonce=nonce).json_dumps()\n ", "context": "class ClientNetwork(object):\n def _wrap_in_jws(self, obj, nonce): ...\n def __init__(self, key, alg=jose.RS256, verify_ssl=True): ...\n def _check_response(cls, response, content_type=None): ...\n def _send_request(self, method, url, *args, **kwargs): ...\n def head(self, *args, **kwargs): ...\n def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n def _add_nonce(self, response): ...\n def _get_nonce(self, url): ...\n def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n\n self.key = key\n self.alg = alg\n self.verify_ssl = verify_ssl\n self._nonces = set()\n\n JSON_CONTENT_TYPE = 'application/json'\n JSON_ERROR_CONTENT_TYPE = 'application/problem+json'\n REPLAY_NONCE_HEADER = 'Replay-Nonce'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_wrap_in_jws", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001604.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "_check_response", "tests": "import unittest\n\nclass Test_check_response(unittest.TestCase):\n def test_check_response_ok_no_jobj_no_ct(self):\n self.response.json.side_effect = ValueError\n for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:\n self.response.headers['Content-Type'] = response_ct\n self.assertEqual(self.response, self.net._check_response(self.response))\n\n def test_check_response_jobj(self):\n self.response.json.return_value = {}\n for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:\n self.response.headers['Content-Type'] = response_ct\n self.assertEqual(self.response, self.net._check_response(self.response))\n", "method_code": " def _check_response(cls, response, content_type=None):\n \"\"\"Check response content and its type.\n \n .. note::\n Checking is not strict: wrong server response ``Content-Type``\n HTTP header is ignored if response is an expected JSON object\n (c.f. Boulder #56).\n \n :param str content_type: Expected Content-Type response header.\n If JSON is expected and not present in server response, this\n function will raise an error. Otherwise, wrong Content-Type\n is ignored, but logged.\n \n :raises .messages.Error: If server response body\n carries HTTP Problem (draft-ietf-appsawg-http-problem-00).\n :raises .ClientError: In case of other networking errors.\n \n \"\"\"\n logger.debug('Received response %s (headers: %s): %r', response, response.headers, response.content)\n response_ct = response.headers.get('Content-Type')\n try:\n jobj = response.json()\n except ValueError as error:\n jobj = None\n if not response.ok:\n if jobj is not None:\n if response_ct != cls.JSON_ERROR_CONTENT_TYPE:\n logger.debug('Ignoring wrong Content-Type (%r) for JSON Error', response_ct)\n try:\n raise messages.Error.from_json(jobj)\n except jose.DeserializationError as error:\n raise errors.ClientError((response, error))\n else:\n raise errors.ClientError(response)\n else:\n if jobj is not None and response_ct != cls.JSON_CONTENT_TYPE:\n logger.debug('Ignoring wrong Content-Type (%r) for JSON decodable response', response_ct)\n if content_type == cls.JSON_CONTENT_TYPE and jobj is None:\n raise errors.ClientError('Unexpected response Content-Type: {0}'.format(response_ct))\n return response\n ", "context": "class ClientNetwork(object):\n @classmethod\n def _check_response(cls, response, content_type=None): ...\n def __init__(self, key, alg=jose.RS256, verify_ssl=True): ...\n def _wrap_in_jws(self, obj, nonce): ...\n def _send_request(self, method, url, *args, **kwargs): ...\n def head(self, *args, **kwargs): ...\n def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n def _add_nonce(self, response): ...\n def _get_nonce(self, url): ...\n def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n\n self.key = key\n self.alg = alg\n self.verify_ssl = verify_ssl\n self._nonces = set()\n\n JSON_CONTENT_TYPE = 'application/json'\n JSON_ERROR_CONTENT_TYPE = 'application/problem+json'\n REPLAY_NONCE_HEADER = 'Replay-Nonce'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_check_response_ok_no_jobj_no_ct", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001605.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "_send_request", "tests": "import unittest\n\nclass Test_send_request(unittest.TestCase):\n @mock.patch('acme.client.requests')\n def test_send_request(self, mock_requests):\n mock_requests.request.return_value = self.response\n self.assertEqual(self.response, self.net._send_request('HEAD', 'url', 'foo', bar='baz'))\n mock_requests.request.assert_called_once_with('HEAD', 'url', 'foo', verify=mock.ANY, bar='baz')\n\n @mock.patch('acme.client.requests')\n def test_send_request_verify_ssl(self, mock_requests):\n for verify in (True, False):\n mock_requests.request.reset_mock()\n mock_requests.request.return_value = self.response\n self.net.verify_ssl = verify\n self.assertEqual(self.response, self.net._send_request('GET', 'url'))\n mock_requests.request.assert_called_once_with('GET', 'url', verify=verify)\n", "method_code": " def _send_request(self, method, url, *args, **kwargs):\n \"\"\"Send HTTP request.\n \n Makes sure that `verify_ssl` is respected. Logs request and\n response (with headers). For allowed parameters please see\n `requests.request`.\n \n :param str method: method for the new `requests.Request` object\n :param str url: URL for the new `requests.Request` object\n \n :raises requests.exceptions.RequestException: in case of any problems\n \n :returns: HTTP Response\n :rtype: `requests.Response`\n \n \n \"\"\"\n logging.debug('Sending %s request to %s', method, url)\n kwargs['verify'] = self.verify_ssl\n response = requests.request(method, url, *args, **kwargs)\n logging.debug('Received %s. Headers: %s. Content: %r', response, response.headers, response.content)\n return response\n ", "context": "class ClientNetwork(object):\n def _send_request(self, method, url, *args, **kwargs): ...\n def __init__(self, key, alg=jose.RS256, verify_ssl=True): ...\n def _wrap_in_jws(self, obj, nonce): ...\n def _check_response(cls, response, content_type=None): ...\n def head(self, *args, **kwargs): ...\n def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n def _add_nonce(self, response): ...\n def _get_nonce(self, url): ...\n def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n\n self.key = key\n self.alg = alg\n self.verify_ssl = verify_ssl\n self._nonces = set()\n\n JSON_CONTENT_TYPE = 'application/json'\n JSON_ERROR_CONTENT_TYPE = 'application/problem+json'\n REPLAY_NONCE_HEADER = 'Replay-Nonce'\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001606.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "head", "tests": "import unittest\n\nclass Test_head(unittest.TestCase):\n def test_head(self):\n self.assertEqual(self.response, self.net.head('url', 'foo', bar='baz'))\n self.send_request.assert_called_once_with('HEAD', 'url', 'foo', bar='baz')\n", "method_code": " def head(self, *args, **kwargs):\n \"\"\"Send HEAD request without checking the response.\n \n Note, that `_check_response` is not called, as it is expected\n that status code other than successfuly 2xx will be returned, or\n messages2.Error will be raised by the server.\n \n \"\"\"\n return self._send_request('HEAD', *args, **kwargs)\n ", "context": "class ClientNetwork(object):\n def head(self, *args, **kwargs): ...\n def __init__(self, key, alg=jose.RS256, verify_ssl=True): ...\n def _wrap_in_jws(self, obj, nonce): ...\n def _check_response(cls, response, content_type=None): ...\n def _send_request(self, method, url, *args, **kwargs): ...\n def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n def _add_nonce(self, response): ...\n def _get_nonce(self, url): ...\n def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n\n self.key = key\n self.alg = alg\n self.verify_ssl = verify_ssl\n self._nonces = set()\n\n JSON_CONTENT_TYPE = 'application/json'\n JSON_ERROR_CONTENT_TYPE = 'application/problem+json'\n REPLAY_NONCE_HEADER = 'Replay-Nonce'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_head", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001607.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_get(self):\n self.assertEqual(self.checked_response, self.net.get('url', content_type=self.content_type, bar='baz'))\n self.send_request.assert_called_once_with('GET', 'url', bar='baz')\n", "method_code": " def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs):\n \"\"\"Send GET request and check response.\"\"\"\n return self._check_response(self._send_request('GET', url, **kwargs), content_type=content_type)\n ", "context": "class ClientNetwork(object):\n def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n def __init__(self, key, alg=jose.RS256, verify_ssl=True): ...\n def _wrap_in_jws(self, obj, nonce): ...\n def _check_response(cls, response, content_type=None): ...\n def _send_request(self, method, url, *args, **kwargs): ...\n def head(self, *args, **kwargs): ...\n def _add_nonce(self, response): ...\n def _get_nonce(self, url): ...\n def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n\n self.key = key\n self.alg = alg\n self.verify_ssl = verify_ssl\n self._nonces = set()\n\n JSON_CONTENT_TYPE = 'application/json'\n JSON_ERROR_CONTENT_TYPE = 'application/problem+json'\n REPLAY_NONCE_HEADER = 'Replay-Nonce'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_get", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001608.py"} {"focal_file": "acme/acme/client.py", "focal_class": null, "focal_method": "post", "tests": "import unittest\n\nclass Test_post(unittest.TestCase):\n def test_post(self):\n self.assertEqual(self.checked_response, self.net.post('uri', self.obj, content_type=self.content_type))\n self.net._wrap_in_jws.assert_called_once_with(self.obj, jose.b64decode(self.all_nonces.pop()))\n assert not self.available_nonces\n self.assertRaises(errors.MissingNonce, self.net.post, 'uri', self.obj, content_type=self.content_type)\n self.net._wrap_in_jws.assert_called_with(self.obj, jose.b64decode(self.all_nonces.pop()))\n", "method_code": " def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs):\n \"\"\"POST object wrapped in `.JWS` and check response.\"\"\"\n data = self._wrap_in_jws(obj, self._get_nonce(url))\n response = self._send_request('POST', url, data=data, **kwargs)\n self._add_nonce(response)\n return self._check_response(response, content_type=content_type)\n ", "context": "class ClientNetwork(object):\n def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n def __init__(self, key, alg=jose.RS256, verify_ssl=True): ...\n def _wrap_in_jws(self, obj, nonce): ...\n def _check_response(cls, response, content_type=None): ...\n def _send_request(self, method, url, *args, **kwargs): ...\n def head(self, *args, **kwargs): ...\n def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): ...\n def _add_nonce(self, response): ...\n def _get_nonce(self, url): ...\n\n self.key = key\n self.alg = alg\n self.verify_ssl = verify_ssl\n self._nonces = set()\n\n JSON_CONTENT_TYPE = 'application/json'\n JSON_ERROR_CONTENT_TYPE = 'application/problem+json'\n REPLAY_NONCE_HEADER = 'Replay-Nonce'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_post", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001609.py"} {"focal_file": "acme/acme/fields.py", "focal_class": null, "focal_method": "default_encoder", "tests": "import unittest\n\nclass Test_default_encoder(unittest.TestCase):\n def test_default_encoder(self):\n from acme.fields import RFC3339Field\n self.assertEqual(self.encoded, RFC3339Field.default_encoder(self.decoded))\n", "method_code": " def default_encoder(cls, value):\n return pyrfc3339.generate(value)\n ", "context": "class RFC3339Field(jose.Field):\n @classmethod\n def default_encoder(cls, value): ...\n def default_decoder(cls, value): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_default_encoder", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001610.py"} {"focal_file": "acme/acme/fields.py", "focal_class": null, "focal_method": "default_decoder", "tests": "import unittest\n\nclass Test_default_decoder(unittest.TestCase):\n def test_default_decoder(self):\n from acme.fields import RFC3339Field\n self.assertEqual(self.decoded, RFC3339Field.default_decoder(self.encoded))\n", "method_code": " def default_decoder(cls, value):\n try:\n return pyrfc3339.parse(value)\n except ValueError as error:\n raise jose.DeserializationError(error)\n ", "context": "class RFC3339Field(jose.Field):\n @classmethod\n def default_decoder(cls, value): ...\n def default_encoder(cls, value): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_default_decoder", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001611.py"} {"focal_file": "acme/acme/messages.py", "focal_class": null, "focal_method": "to_partial_json", "tests": "import unittest\n\nclass Test_to_partial_json(unittest.TestCase):\n def test_to_partial_json(self):\n self.assertEqual(self.jobj_to, self.challb.to_partial_json())\n", "method_code": " def to_partial_json(self):\n return self.name\n ", "context": "class _Constant(jose.JSONDeSerializablecollections.Hashable):\n def to_partial_json(self): ...\n def __init__(self, name): ...\n def from_json(cls, value): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __hash__(self): ...\n def __ne__(self, other): ...\n\n self.POSSIBLE_NAMES[name] = self\n self.name = name\n\n __slots__ = ('name',)\n POSSIBLE_NAMES = NotImplemented\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_to_partial_json", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001612.py"} {"focal_file": "acme/acme/messages.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n from acme.messages import Authorization\n Authorization.from_json(self.jobj_from)\n\n def test_from_json_hashable(self):\n from acme.messages import Revocation\n hash(Revocation.from_json(self.rev.to_json()))\n", "method_code": " def from_json(cls, value):\n if value not in cls.POSSIBLE_NAMES:\n raise jose.DeserializationError('{0} not recognized'.format(cls.__name__))\n return cls.POSSIBLE_NAMES[value]\n ", "context": "class _Constant(jose.JSONDeSerializablecollections.Hashable):\n @classmethod\n def from_json(cls, value): ...\n def __init__(self, name): ...\n def to_partial_json(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __hash__(self): ...\n def __ne__(self, other): ...\n\n self.POSSIBLE_NAMES[name] = self\n self.name = name\n\n __slots__ = ('name',)\n POSSIBLE_NAMES = NotImplemented\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_from_json", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001613.py"} {"focal_file": "acme/acme/messages.py", "focal_class": null, "focal_method": "from_data", "tests": "import unittest\n\nclass Test_from_data(unittest.TestCase):\n def test_from_data(self):\n from acme.messages import Registration\n reg = Registration.from_data(phone='1234', email='admin@foo.com')\n self.assertEqual(reg.contact, ('tel:1234', 'mailto:admin@foo.com'))\n", "method_code": " def from_data(cls, phone=None, email=None, **kwargs):\n \"\"\"Create registration resource from contact details.\"\"\"\n details = list(kwargs.pop('contact', ()))\n if phone is not None:\n details.append(cls.phone_prefix + phone)\n if email is not None:\n details.append(cls.email_prefix + email)\n kwargs['contact'] = tuple(details)\n return cls(**kwargs)\n ", "context": "class Registration(ResourceBody):\n @classmethod\n def from_data(cls, phone=None, email=None, **kwargs): ...\n def _filter_contact(self, prefix): ...\n def phones(self): ...\n def emails(self): ...\n\n key = jose.Field('key', omitempty=True, decoder=jose.JWK.from_json)\n contact = jose.Field('contact', omitempty=True, default=())\n recovery_token = jose.Field('recoveryToken', omitempty=True)\n agreement = jose.Field('agreement', omitempty=True)\n phone_prefix = 'tel:'\n email_prefix = 'mailto:'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_from_data", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001614.py"} {"focal_file": "acme/acme/messages.py", "focal_class": null, "focal_method": "url", "tests": "import unittest\n\nclass Test_url(unittest.TestCase):\n def test_url(self):\n from acme.messages import Revocation\n url = 'https://letsencrypt-demo.org/acme/revoke-cert'\n self.assertEqual(url, Revocation.url('https://letsencrypt-demo.org'))\n self.assertEqual(url, Revocation.url('https://letsencrypt-demo.org/acme/new-reg'))\n", "method_code": " def url(cls, base):\n \"\"\"Get revocation URL.\n \n :param str base: New Registration Resource or server (root) URL.\n \n \"\"\"\n return urllib_parse.urljoin(base, cls.PATH)\n \n resource_type = 'revoke-cert'\n resource = fields.Resource(resource_type)\n certificate = jose.Field('certificate', decoder=jose.decode_cert, encoder=jose.encode_cert)\n PATH = '/acme/revoke-cert'\n", "context": "class Revocation(jose.JSONObjectWithFields):\n @classmethod\n def url(cls, base): ...", "repository": "stewnorriss/letsencrypt", "test_name": "test_url", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001615.py"} {"focal_file": "acme/acme/jose/interfaces.py", "focal_class": null, "focal_method": "to_json", "tests": "import unittest\n\nclass Test_to_json(unittest.TestCase):\n def test_to_json_nested(self):\n self.assertEqual(self.nested.to_json(), [['foo1']])\n\n def test_to_json(self):\n self.assertEqual(self.tuple.to_json(), ('foo',))\n", "method_code": " def to_json(self):\n \"\"\"Fully serialize.\n \n Again, following the example from before, **full serialization**\n means the following::\n \n assert Bar().to_json() == ['foo', 'foo']\n \n :raises acme.jose.errors.SerializationError:\n in case of any serialization error.\n :returns: Fully serialized object.\n \n \"\"\"\n \n def _serialize(obj):\n if isinstance(obj, JSONDeSerializable):\n return _serialize(obj.to_partial_json())\n if isinstance(obj, six.string_types):\n return obj\n elif isinstance(obj, list):\n return [_serialize(subobj) for subobj in obj]\n elif isinstance(obj, collections.Sequence):\n return tuple((_serialize(subobj) for subobj in obj))\n elif isinstance(obj, collections.Mapping):\n return dict(((_serialize(key), _serialize(value)) for key, value in six.iteritems(obj)))\n else:\n return obj\n return _serialize(self)\n ", "context": "class JSONDeSerializable(object):\n def to_json(self): ...\n def to_partial_json(self): ...\n def from_json(cls, jobj): ...\n def json_loads(cls, json_string): ...\n def json_dumps(self, **kwargs): ...\n def json_dumps_pretty(self): ...\n def json_dump_default(cls, python_object): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_to_json_nested", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001616.py"} {"focal_file": "acme/acme/jose/interfaces.py", "focal_class": null, "focal_method": "json_loads", "tests": "import unittest\n\nclass Test_json_loads(unittest.TestCase):\n def test_json_loads(self):\n seq = self.Sequence.json_loads('[\"foo1\", \"foo2\"]')\n self.assertTrue(isinstance(seq, self.Sequence))\n self.assertTrue(isinstance(seq.x, self.Basic))\n self.assertTrue(isinstance(seq.y, self.Basic))\n self.assertEqual(seq.x.v, 'foo1')\n self.assertEqual(seq.y.v, 'foo2')\n", "method_code": " def json_loads(cls, json_string):\n \"\"\"Deserialize from JSON document string.\"\"\"\n return cls.from_json(json.loads(json_string))\n ", "context": "class JSONDeSerializable(object):\n @classmethod\n def json_loads(cls, json_string): ...\n def to_partial_json(self): ...\n def to_json(self): ...\n def from_json(cls, jobj): ...\n def json_dumps(self, **kwargs): ...\n def json_dumps_pretty(self): ...\n def json_dump_default(cls, python_object): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_json_loads", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001617.py"} {"focal_file": "acme/acme/jose/interfaces.py", "focal_class": null, "focal_method": "json_dumps", "tests": "import unittest\n\nclass Test_json_dumps(unittest.TestCase):\n def test_json_dumps(self):\n self.assertEqual('[\"foo1\", \"foo2\"]', self.seq.json_dumps())\n", "method_code": " def json_dumps(self, **kwargs):\n \"\"\"Dump to JSON string using proper serializer.\n \n :returns: JSON document string.\n :rtype: str\n \n \"\"\"\n return json.dumps(self, default=self.json_dump_default, **kwargs)\n ", "context": "class JSONDeSerializable(object):\n def json_dumps(self, **kwargs): ...\n def to_partial_json(self): ...\n def to_json(self): ...\n def from_json(cls, jobj): ...\n def json_loads(cls, json_string): ...\n def json_dumps_pretty(self): ...\n def json_dump_default(cls, python_object): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_json_dumps", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001618.py"} {"focal_file": "acme/acme/jose/interfaces.py", "focal_class": null, "focal_method": "json_dumps_pretty", "tests": "import unittest\n\nclass Test_json_dumps_pretty(unittest.TestCase):\n def test_json_dumps_pretty(self):\n self.assertEqual(self.seq.json_dumps_pretty(), '[\\n \"foo1\",\\n \"foo2\"\\n]')\n", "method_code": " def json_dumps_pretty(self):\n \"\"\"Dump the object to pretty JSON document string.\n \n :rtype: str\n \n \"\"\"\n return self.json_dumps(sort_keys=True, indent=4, separators=(',', ': '))\n ", "context": "class JSONDeSerializable(object):\n def json_dumps_pretty(self): ...\n def to_partial_json(self): ...\n def to_json(self): ...\n def from_json(cls, jobj): ...\n def json_loads(cls, json_string): ...\n def json_dumps(self, **kwargs): ...\n def json_dump_default(cls, python_object): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_json_dumps_pretty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001619.py"} {"focal_file": "acme/acme/jose/interfaces.py", "focal_class": null, "focal_method": "json_dump_default", "tests": "import unittest\n\nclass Test_json_dump_default(unittest.TestCase):\n def test_json_dump_default(self):\n from acme.jose.interfaces import JSONDeSerializable\n self.assertEqual('foo1', JSONDeSerializable.json_dump_default(self.basic1))\n jobj = JSONDeSerializable.json_dump_default(self.seq)\n self.assertEqual(len(jobj), 2)\n self.assertTrue(jobj[0] is self.basic1)\n self.assertTrue(jobj[1] is self.basic2)\n", "method_code": " def json_dump_default(cls, python_object):\n \"\"\"Serialize Python object.\n \n This function is meant to be passed as ``default`` to\n :func:`json.dump` or :func:`json.dumps`. They call\n ``default(python_object)`` only for non-basic Python types, so\n this function necessarily raises :class:`TypeError` if\n ``python_object`` is not an instance of\n :class:`IJSONSerializable`.\n \n Please read the class docstring for more information.\n \n \"\"\"\n if isinstance(python_object, JSONDeSerializable):\n return python_object.to_partial_json()\n else:\n raise TypeError(repr(python_object) + ' is not JSON serializable')\n ", "context": "class JSONDeSerializable(object):\n @classmethod\n def json_dump_default(cls, python_object): ...\n def to_partial_json(self): ...\n def to_json(self): ...\n def from_json(cls, jobj): ...\n def json_loads(cls, json_string): ...\n def json_dumps(self, **kwargs): ...\n def json_dumps_pretty(self): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_json_dump_default", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001620.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "default_encoder", "tests": "import unittest\n\nclass Test_default_encoder(unittest.TestCase):\n def test_default_encoder_is_partial(self):\n\n class MockField(interfaces.JSONDeSerializable):\n\n def to_partial_json(self):\n return 'foo'\n\n @classmethod\n def from_json(cls, jobj):\n pass\n mock_field = MockField()\n from acme.jose.json_util import Field\n self.assertTrue(Field.default_encoder(mock_field) is mock_field)\n self.assertNotEqual('foo', Field.default_encoder(mock_field))\n\n def test_default_encoder_passthrough(self):\n mock_value = mock.MagicMock()\n from acme.jose.json_util import Field\n self.assertTrue(Field.default_encoder(mock_value) is mock_value)\n", "method_code": " def default_encoder(cls, value):\n \"\"\"Default (passthrough) encoder.\"\"\"\n return value\n ", "context": "class Field(object):\n @classmethod\n def default_encoder(cls, value): ...\n def __init__(self, json_name, default=None, omitempty=False, decoder=None, encoder=None): ...\n def _empty(cls, value): ...\n def omit(self, value): ...\n def _update_params(self, **kwargs): ...\n def decoder(self, fdec): ...\n def encoder(self, fenc): ...\n def decode(self, value): ...\n def encode(self, value): ...\n def default_decoder(cls, value): ...\n\n self.json_name = json_name\n self.default = default\n self.omitempty = omitempty\n self.fdec = self.default_decoder if decoder is None else decoder\n self.fenc = self.default_encoder if encoder is None else encoder\n\n __slots__ = ('json_name', 'default', 'omitempty', 'fdec', 'fenc')\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_default_encoder_is_partial", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001621.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "default_decoder", "tests": "import unittest\n\nclass Test_default_decoder(unittest.TestCase):\n def test_default_decoder_list_to_tuple(self):\n from acme.jose.json_util import Field\n self.assertEqual((1, 2, 3), Field.default_decoder([1, 2, 3]))\n\n def test_default_decoder_passthrough(self):\n mock_value = mock.MagicMock()\n from acme.jose.json_util import Field\n self.assertTrue(Field.default_decoder(mock_value) is mock_value)\n", "method_code": " def default_decoder(cls, value):\n \"\"\"Default decoder.\n \n Recursively deserialize into immutable types (\n :class:`acme.jose.util.frozendict` instead of\n :func:`dict`, :func:`tuple` instead of :func:`list`).\n \n \"\"\"\n if isinstance(value, list):\n return tuple((cls.default_decoder(subvalue) for subvalue in value))\n elif isinstance(value, dict):\n return util.frozendict(dict(((cls.default_decoder(key), cls.default_decoder(value)) for key, value in six.iteritems(value))))\n else:\n return value\n ", "context": "class Field(object):\n @classmethod\n def default_decoder(cls, value): ...\n def __init__(self, json_name, default=None, omitempty=False, decoder=None, encoder=None): ...\n def _empty(cls, value): ...\n def omit(self, value): ...\n def _update_params(self, **kwargs): ...\n def decoder(self, fdec): ...\n def encoder(self, fenc): ...\n def decode(self, value): ...\n def encode(self, value): ...\n def default_encoder(cls, value): ...\n\n self.json_name = json_name\n self.default = default\n self.omitempty = omitempty\n self.fdec = self.default_decoder if decoder is None else decoder\n self.fenc = self.default_encoder if encoder is None else encoder\n\n __slots__ = ('json_name', 'default', 'omitempty', 'fdec', 'fenc')\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_default_decoder_list_to_tuple", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001622.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "fields_to_partial_json", "tests": "import unittest\n\nclass Test_fields_to_partial_json(unittest.TestCase):\n def test_fields_to_partial_json_omits_empty(self):\n self.assertEqual(self.mock.fields_to_partial_json(), {'y': 2, 'Z': 3})\n", "method_code": " def fields_to_partial_json(self):\n \"\"\"Serialize fields to JSON.\"\"\"\n jobj = {}\n omitted = set()\n for slot, field in six.iteritems(self._fields):\n value = getattr(self, slot)\n if field.omit(value):\n omitted.add((slot, value))\n else:\n try:\n jobj[field.json_name] = field.encode(value)\n except errors.SerializationError as error:\n raise errors.SerializationError('Could not encode {0} ({1}): {2}'.format(slot, value, error))\n if omitted:\n logger.debug('Omitted empty fields: %s', ', '.join(('{0!s}={1!r}'.format(*field) for field in omitted)))\n return jobj\n ", "context": "class JSONObjectWithFields(util.ImmutableMapinterfaces.JSONDeSerializable):\n def fields_to_partial_json(self): ...\n def _defaults(cls): ...\n def __init__(self, **kwargs): ...\n def to_partial_json(self): ...\n def _check_required(cls, jobj): ...\n def fields_from_json(cls, jobj): ...\n def from_json(cls, jobj): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_fields_to_partial_json_omits_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001623.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "fields_from_json", "tests": "import unittest\n\nclass Test_fields_from_json(unittest.TestCase):\n def test_fields_from_json_decoder(self):\n self.assertEqual({'x': 2, 'y': 2, 'z': 3}, self.MockJSONObjectWithFields.fields_from_json({'x': 4, 'y': 2, 'Z': 3}))\n", "method_code": " def fields_from_json(cls, jobj):\n \"\"\"Deserialize fields from JSON.\"\"\"\n cls._check_required(jobj)\n fields = {}\n for slot, field in six.iteritems(cls._fields):\n if field.json_name not in jobj and field.omitempty:\n fields[slot] = field.default\n else:\n value = jobj[field.json_name]\n try:\n fields[slot] = field.decode(value)\n except errors.DeserializationError as error:\n raise errors.DeserializationError('Could not decode {0!r} ({1!r}): {2}'.format(slot, value, error))\n return fields\n ", "context": "class JSONObjectWithFields(util.ImmutableMapinterfaces.JSONDeSerializable):\n @classmethod\n def fields_from_json(cls, jobj): ...\n def _defaults(cls): ...\n def __init__(self, **kwargs): ...\n def fields_to_partial_json(self): ...\n def to_partial_json(self): ...\n def _check_required(cls, jobj): ...\n def from_json(cls, jobj): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_fields_from_json_decoder", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001624.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "encode_b64jose", "tests": "import unittest\n\nclass Test_encode_b64jose(unittest.TestCase):\n def test_encode_b64jose(self):\n from acme.jose.json_util import encode_b64jose\n encoded = encode_b64jose(b'x')\n self.assertTrue(isinstance(encoded, six.string_types))\n self.assertEqual(u'eA', encoded)\n", "method_code": "def encode_b64jose(data):\n \"\"\"Encode JOSE Base-64 field.\n\n :param bytes data:\n :rtype: `unicode`\n\n \"\"\"\n return b64.b64encode(data).decode('ascii')", "context": "def encode_b64jose(data): ...\ndef encode_b64jose(data): ...\ndef decode_b64jose(data, size=None, minimum=False): ...\ndef encode_hex16(value): ...\ndef decode_hex16(value, size=None, minimum=False): ...\ndef encode_cert(cert): ...\ndef decode_cert(b64der): ...\ndef encode_csr(csr): ...\ndef decode_csr(b64der): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_encode_b64jose", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001625.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "decode_b64jose", "tests": "import unittest\n\nclass Test_decode_b64jose(unittest.TestCase):\n def test_decode_b64jose(self):\n from acme.jose.json_util import decode_b64jose\n decoded = decode_b64jose(u'eA')\n self.assertTrue(isinstance(decoded, six.binary_type))\n self.assertEqual(b'x', decoded)\n\n def test_decode_b64jose_size(self):\n from acme.jose.json_util import decode_b64jose\n self.assertEqual(b'foo', decode_b64jose(u'Zm9v', size=3))\n self.assertRaises(errors.DeserializationError, decode_b64jose, u'Zm9v', size=2)\n self.assertRaises(errors.DeserializationError, decode_b64jose, u'Zm9v', size=4)\n\n def test_decode_b64jose_minimum_size(self):\n from acme.jose.json_util import decode_b64jose\n self.assertEqual(b'foo', decode_b64jose(u'Zm9v', size=3, minimum=True))\n self.assertEqual(b'foo', decode_b64jose(u'Zm9v', size=2, minimum=True))\n self.assertRaises(errors.DeserializationError, decode_b64jose, u'Zm9v', size=4, minimum=True)\n", "method_code": "def decode_b64jose(data, size=None, minimum=False):\n \"\"\"Decode JOSE Base-64 field.\n\n :param unicode data:\n :param int size: Required length (after decoding).\n :param bool minimum: If ``True``, then `size` will be treated as\n minimum required length, as opposed to exact equality.\n\n :rtype: bytes\n\n \"\"\"\n error_cls = TypeError if six.PY2 else binascii.Error\n try:\n decoded = b64.b64decode(data.encode())\n except error_cls as error:\n raise errors.DeserializationError(error)\n if size is not None and (not minimum and len(decoded) != size or (minimum and len(decoded) < size)):\n raise errors.DeserializationError()\n return decoded", "context": "def decode_b64jose(data, size=None, minimum=False): ...\ndef encode_b64jose(data): ...\ndef decode_b64jose(data, size=None, minimum=False): ...\ndef encode_hex16(value): ...\ndef decode_hex16(value, size=None, minimum=False): ...\ndef encode_cert(cert): ...\ndef decode_cert(b64der): ...\ndef encode_csr(csr): ...\ndef decode_csr(b64der): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_decode_b64jose", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001626.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "encode_hex16", "tests": "import unittest\n\nclass Test_encode_hex16(unittest.TestCase):\n def test_encode_hex16(self):\n from acme.jose.json_util import encode_hex16\n encoded = encode_hex16(b'foo')\n self.assertEqual(u'666f6f', encoded)\n self.assertTrue(isinstance(encoded, six.string_types))\n", "method_code": "def encode_hex16(value):\n \"\"\"Hexlify.\n\n :param bytes value:\n :rtype: unicode\n\n \"\"\"\n return binascii.hexlify(value).decode()", "context": "def encode_hex16(value): ...\ndef encode_b64jose(data): ...\ndef decode_b64jose(data, size=None, minimum=False): ...\ndef encode_hex16(value): ...\ndef decode_hex16(value, size=None, minimum=False): ...\ndef encode_cert(cert): ...\ndef decode_cert(b64der): ...\ndef encode_csr(csr): ...\ndef decode_csr(b64der): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_encode_hex16", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001627.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "decode_hex16", "tests": "import unittest\n\nclass Test_decode_hex16(unittest.TestCase):\n def test_decode_hex16(self):\n from acme.jose.json_util import decode_hex16\n decoded = decode_hex16(u'666f6f')\n self.assertEqual(b'foo', decoded)\n self.assertTrue(isinstance(decoded, six.binary_type))\n\n def test_decode_hex16_minimum_size(self):\n from acme.jose.json_util import decode_hex16\n self.assertEqual(b'foo', decode_hex16(u'666f6f', size=3, minimum=True))\n self.assertEqual(b'foo', decode_hex16(u'666f6f', size=2, minimum=True))\n self.assertRaises(errors.DeserializationError, decode_hex16, u'666f6f', size=4, minimum=True)\n", "method_code": "def decode_hex16(value, size=None, minimum=False):\n \"\"\"Decode hexlified field.\n\n :param unicode value:\n :param int size: Required length (after decoding).\n :param bool minimum: If ``True``, then `size` will be treated as\n minimum required length, as opposed to exact equality.\n\n :rtype: bytes\n\n \"\"\"\n value = value.encode()\n if size is not None and (not minimum and len(value) != size * 2 or (minimum and len(value) < size * 2)):\n raise errors.DeserializationError()\n error_cls = TypeError if six.PY2 else binascii.Error\n try:\n return binascii.unhexlify(value)\n except error_cls as error:\n raise errors.DeserializationError(error)", "context": "def decode_hex16(value, size=None, minimum=False): ...\ndef encode_b64jose(data): ...\ndef decode_b64jose(data, size=None, minimum=False): ...\ndef encode_hex16(value): ...\ndef decode_hex16(value, size=None, minimum=False): ...\ndef encode_cert(cert): ...\ndef decode_cert(b64der): ...\ndef encode_csr(csr): ...\ndef decode_csr(b64der): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_decode_hex16", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001628.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "encode_cert", "tests": "import unittest\n\nclass Test_encode_cert(unittest.TestCase):\n def test_encode_cert(self):\n from acme.jose.json_util import encode_cert\n self.assertEqual(self.b64_cert, encode_cert(CERT))\n", "method_code": "def encode_cert(cert):\n \"\"\"Encode certificate as JOSE Base-64 DER.\n\n :type cert: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`\n :rtype: unicode\n\n \"\"\"\n return encode_b64jose(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, cert))", "context": "def encode_cert(cert): ...\ndef encode_b64jose(data): ...\ndef decode_b64jose(data, size=None, minimum=False): ...\ndef encode_hex16(value): ...\ndef decode_hex16(value, size=None, minimum=False): ...\ndef encode_cert(cert): ...\ndef decode_cert(b64der): ...\ndef encode_csr(csr): ...\ndef decode_csr(b64der): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_encode_cert", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001629.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "decode_cert", "tests": "import unittest\n\nclass Test_decode_cert(unittest.TestCase):\n def test_decode_cert(self):\n from acme.jose.json_util import decode_cert\n cert = decode_cert(self.b64_cert)\n self.assertTrue(isinstance(cert, util.ComparableX509))\n self.assertEqual(cert, CERT)\n self.assertRaises(errors.DeserializationError, decode_cert, u'')\n", "method_code": "def decode_cert(b64der):\n \"\"\"Decode JOSE Base-64 DER-encoded certificate.\n\n :param unicode b64der:\n :rtype: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`\n\n \"\"\"\n try:\n return util.ComparableX509(OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, decode_b64jose(b64der)))\n except OpenSSL.crypto.Error as error:\n raise errors.DeserializationError(error)", "context": "def decode_cert(b64der): ...\ndef encode_b64jose(data): ...\ndef decode_b64jose(data, size=None, minimum=False): ...\ndef encode_hex16(value): ...\ndef decode_hex16(value, size=None, minimum=False): ...\ndef encode_cert(cert): ...\ndef decode_cert(b64der): ...\ndef encode_csr(csr): ...\ndef decode_csr(b64der): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_decode_cert", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001630.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "encode_csr", "tests": "import unittest\n\nclass Test_encode_csr(unittest.TestCase):\n def test_encode_csr(self):\n from acme.jose.json_util import encode_csr\n self.assertEqual(self.b64_csr, encode_csr(CSR))\n", "method_code": "def encode_csr(csr):\n \"\"\"Encode CSR as JOSE Base-64 DER.\n\n :type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`\n :rtype: unicode\n\n \"\"\"\n return encode_b64jose(OpenSSL.crypto.dump_certificate_request(OpenSSL.crypto.FILETYPE_ASN1, csr))", "context": "def encode_csr(csr): ...\ndef encode_b64jose(data): ...\ndef decode_b64jose(data, size=None, minimum=False): ...\ndef encode_hex16(value): ...\ndef decode_hex16(value, size=None, minimum=False): ...\ndef encode_cert(cert): ...\ndef decode_cert(b64der): ...\ndef encode_csr(csr): ...\ndef decode_csr(b64der): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_encode_csr", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001631.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "decode_csr", "tests": "import unittest\n\nclass Test_decode_csr(unittest.TestCase):\n def test_decode_csr(self):\n from acme.jose.json_util import decode_csr\n csr = decode_csr(self.b64_csr)\n self.assertTrue(isinstance(csr, util.ComparableX509))\n self.assertEqual(csr, CSR)\n self.assertRaises(errors.DeserializationError, decode_csr, u'')\n", "method_code": "def decode_csr(b64der):\n \"\"\"Decode JOSE Base-64 DER-encoded CSR.\n\n :param unicode b64der:\n :rtype: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`\n\n \"\"\"\n try:\n return util.ComparableX509(OpenSSL.crypto.load_certificate_request(OpenSSL.crypto.FILETYPE_ASN1, decode_b64jose(b64der)))\n except OpenSSL.crypto.Error as error:\n raise errors.DeserializationError(error)", "context": "def decode_csr(b64der): ...\ndef encode_b64jose(data): ...\ndef decode_b64jose(data, size=None, minimum=False): ...\ndef encode_hex16(value): ...\ndef decode_hex16(value, size=None, minimum=False): ...\ndef encode_cert(cert): ...\ndef decode_cert(b64der): ...\ndef encode_csr(csr): ...\ndef decode_csr(b64der): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_decode_csr", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001632.py"} {"focal_file": "acme/acme/jose/json_util.py", "focal_class": null, "focal_method": "to_partial_json", "tests": "import unittest\n\nclass Test_to_partial_json(unittest.TestCase):\n def test_to_partial_json(self):\n self.assertEqual(self.msg.to_partial_json(), {'type': 'test', 'foo': 'bar'})\n", "method_code": " def to_partial_json(self):\n return self.fields_to_partial_json()\n ", "context": "class JSONObjectWithFields(util.ImmutableMapinterfaces.JSONDeSerializable):\n def to_partial_json(self): ...\n def _defaults(cls): ...\n def __init__(self, **kwargs): ...\n def fields_to_partial_json(self): ...\n def _check_required(cls, jobj): ...\n def fields_from_json(cls, jobj): ...\n def from_json(cls, jobj): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_to_partial_json", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001633.py"} {"focal_file": "acme/acme/jose/jwa.py", "focal_class": null, "focal_method": "to_partial_json", "tests": "import unittest\n\nclass Test_to_partial_json(unittest.TestCase):\n def test_to_partial_json(self):\n self.assertEqual(self.Sig1.to_partial_json(), 'Sig1')\n self.assertEqual(self.Sig2.to_partial_json(), 'Sig2')\n", "method_code": " def to_partial_json(self):\n return self.name\n ", "context": "class JWASignature(JWAcollections.Hashable):\n def to_partial_json(self): ...\n def __init__(self, name): ...\n def __eq__(self, other): ...\n def __hash__(self): ...\n def __ne__(self, other): ...\n def register(cls, signature_cls): ...\n def from_json(cls, jobj): ...\n def sign(self, key, msg): ...\n def verify(self, key, msg, sig): ...\n def __repr__(self): ...\n\n self.name = name\n\n SIGNATURES = {}\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_to_partial_json", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001634.py"} {"focal_file": "acme/acme/jose/jwa.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n from acme.jose.jwa import JWASignature\n from acme.jose.jwa import RS256\n self.assertTrue(JWASignature.from_json('RS256') is RS256)\n", "method_code": " def from_json(cls, jobj):\n return cls.SIGNATURES[jobj]\n ", "context": "class JWASignature(JWAcollections.Hashable):\n @classmethod\n def from_json(cls, jobj): ...\n def __init__(self, name): ...\n def __eq__(self, other): ...\n def __hash__(self): ...\n def __ne__(self, other): ...\n def register(cls, signature_cls): ...\n def to_partial_json(self): ...\n def sign(self, key, msg): ...\n def verify(self, key, msg, sig): ...\n def __repr__(self): ...\n\n self.name = name\n\n SIGNATURES = {}\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_from_json", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001635.py"} {"focal_file": "acme/acme/jose/jwk.py", "focal_class": null, "focal_method": "load", "tests": "import unittest\n\nclass Test_load(unittest.TestCase):\n def test_load(self):\n from acme.jose.jwk import JWKRSA\n self.assertEqual(self.private, JWKRSA.load(test_util.load_vector('rsa256_key.pem')))\n", "method_code": " def load(cls, data, password=None, backend=None):\n \"\"\"Load serialized key as JWK.\n \n :param str data: Public or private key serialized as PEM or DER.\n :param str password: Optional password.\n :param backend: A `.PEMSerializationBackend` and\n `.DERSerializationBackend` provider.\n \n :raises errors.Error: if unable to deserialize, or unsupported\n JWK algorithm\n \n :returns: JWK of an appropriate type.\n :rtype: `JWK`\n \n \"\"\"\n try:\n key = cls._load_cryptography_key(data, password, backend)\n except errors.Error as error:\n logger.debug('Loading symmetric key, assymentric failed: %s', error)\n return JWKOct(key=data)\n if cls.typ is not NotImplemented and (not isinstance(key, cls.cryptography_key_types)):\n raise errors.Error('Unable to deserialize {0} into {1}'.format(key.__class__, cls.__class__))\n for jwk_cls in six.itervalues(cls.TYPES):\n if isinstance(key, jwk_cls.cryptography_key_types):\n return jwk_cls(key=key)\n raise errors.Error('Unsupported algorithm: {0}'.format(key.__class__))\n ", "context": "class JWK(json_util.TypedJSONObjectWithFields):\n @classmethod\n def load(cls, data, password=None, backend=None): ...\n def public_key(self): ...\n def _load_cryptography_key(cls, data, password=None, backend=None): ...\n\n type_field_name = 'kty'\n TYPES = {}\n cryptography_key_types = ()\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_load", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001636.py"} {"focal_file": "acme/acme/jose/jwk.py", "focal_class": null, "focal_method": "public_key", "tests": "import unittest\n\nclass Test_public_key(unittest.TestCase):\n def test_public_key(self):\n self.assertEqual(self.jwk256, self.private.public_key())\n", "method_code": " def public_key(self):\n \"\"\"Generate JWK with public key.\n \n For symmetric cryptosystems, this would return ``self``.\n \n \"\"\"\n raise NotImplementedError()\n ", "context": "class JWK(json_util.TypedJSONObjectWithFields):\n @abc.abstractmethod\n def public_key(self): ...\n def _load_cryptography_key(cls, data, password=None, backend=None): ...\n def load(cls, data, password=None, backend=None): ...\n\n type_field_name = 'kty'\n TYPES = {}\n cryptography_key_types = ()\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_public_key", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001637.py"} {"focal_file": "acme/acme/jose/jwk.py", "focal_class": null, "focal_method": "_encode_param", "tests": "import unittest\n\nclass Test_encode_param(unittest.TestCase):\n def test_encode_param_zero(self):\n from acme.jose.jwk import JWKRSA\n self.assertEqual('AA', JWKRSA._encode_param(0))\n", "method_code": " def _encode_param(cls, data):\n \"\"\"Encode Base64urlUInt.\n \n :type data: long\n :rtype: unicode\n \n \"\"\"\n \n def _leading_zeros(arg):\n if len(arg) % 2:\n return '0' + arg\n return arg\n return json_util.encode_b64jose(binascii.unhexlify(_leading_zeros(hex(data)[2:].rstrip('L'))))\n ", "context": "class JWKRSA(JWK):\n @classmethod\n def _encode_param(cls, data): ...\n def __init__(self, *args, **kwargs): ...\n def _decode_param(cls, data): ...\n def public_key(self): ...\n def fields_from_json(cls, jobj): ...\n def fields_to_partial_json(self): ...\n\n typ = 'RSA'\n cryptography_key_types = (rsa.RSAPublicKey, rsa.RSAPrivateKey)\n __slots__ = ('key',)\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_encode_param_zero", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001638.py"} {"focal_file": "acme/acme/jose/jws.py", "focal_class": null, "focal_method": "decode", "tests": "import unittest\n\nclass Test_decode(unittest.TestCase):\n def test_decode(self):\n from acme.jose.jws import MediaType\n self.assertEqual('application/app', MediaType.decode('application/app'))\n self.assertEqual('application/app', MediaType.decode('app'))\n self.assertRaises(errors.DeserializationError, MediaType.decode, 'app;foo')\n", "method_code": " def decode(cls, value):\n \"\"\"Decoder.\"\"\"\n if '/' not in value:\n if ';' in value:\n raise errors.DeserializationError('Unexpected semi-colon')\n return cls.PREFIX + value\n return value\n ", "context": "class MediaType(object):\n @classmethod\n def decode(cls, value): ...\n def encode(cls, value): ...\n\n PREFIX = 'application/'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_decode", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001639.py"} {"focal_file": "acme/acme/jose/jws.py", "focal_class": null, "focal_method": "encode", "tests": "import unittest\n\nclass Test_encode(unittest.TestCase):\n def test_encode(self):\n from acme.jose.jws import MediaType\n self.assertEqual('app', MediaType.encode('application/app'))\n self.assertEqual('application/app;foo', MediaType.encode('application/app;foo'))\n", "method_code": " def encode(cls, value):\n \"\"\"Encoder.\"\"\"\n if ';' not in value:\n assert value.startswith(cls.PREFIX)\n return value[len(cls.PREFIX):]\n return value\n ", "context": "class MediaType(object):\n @classmethod\n def encode(cls, value): ...\n def decode(cls, value): ...\n\n PREFIX = 'application/'\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_encode", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001640.py"} {"focal_file": "acme/acme/jose/jws.py", "focal_class": null, "focal_method": "find_key", "tests": "import unittest\n\nclass Test_find_key(unittest.TestCase):\n def test_find_key(self):\n self.assertEqual('foo', self.header1.find_key())\n self.assertEqual('bar', self.header2.find_key())\n self.assertRaises(errors.Error, self.crit.find_key)\n", "method_code": " def find_key(self):\n \"\"\"Find key based on header.\n \n .. todo:: Supports only \"jwk\" header parameter lookup.\n \n :returns: (Public) key found in the header.\n :rtype: :class:`acme.jose.jwk.JWK`\n \n :raises acme.jose.errors.Error: if key could not be found\n \n \"\"\"\n if self.jwk is None:\n raise errors.Error('No key found')\n return self.jwk\n ", "context": "class Header(json_util.JSONObjectWithFields):\n def find_key(self): ...\n def not_omitted(self): ...\n def __add__(self, other): ...\n def crit(unused_value): ...\n def x5c(value): ...\n def x5c(value): ...\n\n alg = json_util.Field('alg', decoder=jwa.JWASignature.from_json, omitempty=True)\n jku = json_util.Field('jku', omitempty=True)\n jwk = json_util.Field('jwk', decoder=jwk.JWK.from_json, omitempty=True)\n kid = json_util.Field('kid', omitempty=True)\n x5u = json_util.Field('x5u', omitempty=True)\n x5c = json_util.Field('x5c', omitempty=True, default=())\n x5t = json_util.Field('x5t', decoder=json_util.decode_b64jose, omitempty=True)\n x5tS256 = json_util.Field('x5t#S256', decoder=json_util.decode_b64jose, omitempty=True)\n typ = json_util.Field('typ', encoder=MediaType.encode, decoder=MediaType.decode, omitempty=True)\n cty = json_util.Field('cty', encoder=MediaType.encode, decoder=MediaType.decode, omitempty=True)\n crit = json_util.Field('crit', omitempty=True, default=())\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_find_key", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001641.py"} {"focal_file": "acme/acme/jose/jws.py", "focal_class": null, "focal_method": "from_json", "tests": "import unittest\n\nclass Test_from_json(unittest.TestCase):\n def test_from_json(self):\n from acme.jose.jws import Header\n from acme.jose.jws import Signature\n self.assertEqual(Signature(signature=b'foo', header=Header(alg=jwa.RS256)), Signature.from_json({'signature': 'Zm9v', 'header': {'alg': 'RS256'}}))\n", "method_code": " def from_json(cls, jobj):\n if 'signature' in jobj and 'signatures' in jobj:\n raise errors.DeserializationError('Flat mixed with non-flat')\n elif 'signature' in jobj:\n return cls(payload=json_util.decode_b64jose(jobj.pop('payload')), signatures=(cls.signature_cls.from_json(jobj),))\n else:\n return cls(payload=json_util.decode_b64jose(jobj['payload']), signatures=tuple((cls.signature_cls.from_json(sig) for sig in jobj['signatures'])))\n ", "context": "class JWS(json_util.JSONObjectWithFields):\n @classmethod\n def from_json(cls, jobj): ...\n def verify(self, key=None): ...\n def sign(cls, payload, **kwargs): ...\n def signature(self): ...\n def to_compact(self): ...\n def from_compact(cls, compact): ...\n def to_partial_json(self, flat=True): ...\n\n __slots__ = ('payload', 'signatures')\n signature_cls = Signature\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_from_json", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001642.py"} {"focal_file": "acme/acme/jose/jws.py", "focal_class": null, "focal_method": "verify", "tests": "import unittest\n\nclass Test_verify(unittest.TestCase):\n def test_sign_unprotected(self):\n self.assertTrue(self.unprotected.verify())\n", "method_code": " def verify(self, payload, key=None):\n \"\"\"Verify.\n \n :param key: Key used for verification.\n :type key: :class:`acme.jose.jwk.JWK`\n \n \"\"\"\n key = self.combined.find_key() if key is None else key\n return self.combined.alg.verify(key=key.key, sig=self.signature, msg=self._msg(self.protected, payload))\n ", "context": "class Signature(json_util.JSONObjectWithFields):\n def verify(self, payload, key=None): ...\n def protected(value): ...\n def protected(value): ...\n def __init__(self, **kwargs): ...\n def _with_combined(cls, kwargs): ...\n def _msg(cls, protected, payload): ...\n def sign(cls, payload, key, alg, include_jwk=True, protect=frozenset(), **kwargs): ...\n def fields_to_partial_json(self): ...\n def fields_from_json(cls, jobj): ...\n\n header_cls = Header\n __slots__ = ('combined',)\n protected = json_util.Field('protected', omitempty=True, default='')\n header = json_util.Field('header', omitempty=True, default=header_cls(), decoder=header_cls.from_json)\n signature = json_util.Field('signature', decoder=json_util.decode_b64jose, encoder=json_util.encode_b64jose)\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_sign_unprotected", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001643.py"} {"focal_file": "acme/acme/jose/util.py", "focal_class": null, "focal_method": "public_key", "tests": "import unittest\n\nclass Test_public_key(unittest.TestCase):\n def test_public_key(self):\n from acme.jose.util import ComparableRSAKey\n self.assertTrue(isinstance(self.key.public_key(), ComparableRSAKey))\n", "method_code": " def public_key(self):\n \"\"\"Get wrapped public key.\"\"\"\n return self.__class__(self._wrapped.public_key())\n ", "context": "class ComparableKey(object):\n def public_key(self): ...\n def __init__(self, wrapped): ...\n def __getattr__(self, name): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __repr__(self): ...\n\n self._wrapped = wrapped\n\n __hash__ = NotImplemented\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_public_key", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001644.py"} {"focal_file": "acme/acme/jose/util.py", "focal_class": null, "focal_method": "update", "tests": "import unittest\n\nclass Test_update(unittest.TestCase):\n def test_update(self):\n self.assertEqual(self.A(x=2, y=2), self.a1.update(x=2))\n self.assertEqual(self.a2, self.a1.update(x=3, y=4))\n", "method_code": " def update(self, **kwargs):\n \"\"\"Return updated map.\"\"\"\n items = dict(self)\n items.update(kwargs)\n return type(self)(**items)\n ", "context": "class ImmutableMap(collections.Mappingcollections.Hashable):\n def update(self, **kwargs): ...\n def __init__(self, **kwargs): ...\n def __getitem__(self, key): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __hash__(self): ...\n def __setattr__(self, name, value): ...\n def __repr__(self): ...\n\n __slots__ = ()\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_update", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001645.py"} {"focal_file": "letsencrypt/plugins/common.py", "focal_class": null, "focal_method": "option_namespace", "tests": "import unittest\n\nclass Test_option_namespace(unittest.TestCase):\n def test_option_namespace(self):\n from letsencrypt.plugins.common import option_namespace\n self.assertEqual('foo-', option_namespace('foo'))\n", "method_code": "def option_namespace(name):\n \"\"\"ArgumentParser options namespace (prefix of all options).\"\"\"\n return name + '-'", "context": "def option_namespace(name): ...\ndef option_namespace(name): ...\ndef dest_namespace(name): ...\ndef setup_ssl_options(config_dir, src, dest): ...\ndef dir_setup(test_dir, pkg): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_option_namespace", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001646.py"} {"focal_file": "letsencrypt/plugins/common.py", "focal_class": null, "focal_method": "dest_namespace", "tests": "import unittest\n\nclass Test_dest_namespace(unittest.TestCase):\n def test_dest_namespace(self):\n from letsencrypt.plugins.common import dest_namespace\n self.assertEqual('foo_', dest_namespace('foo'))\n", "method_code": "def dest_namespace(name):\n \"\"\"ArgumentParser dest namespace (prefix of all destinations).\"\"\"\n return name + '_'", "context": "def dest_namespace(name): ...\ndef option_namespace(name): ...\ndef dest_namespace(name): ...\ndef setup_ssl_options(config_dir, src, dest): ...\ndef dir_setup(test_dir, pkg): ...\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_dest_namespace", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001647.py"} {"focal_file": "letsencrypt/plugins/common.py", "focal_class": null, "focal_method": "dest", "tests": "import unittest\n\nclass Test_dest(unittest.TestCase):\n def test_dest(self):\n self.assertEqual('mock_foo_bar', self.plugin.dest('foo-bar'))\n self.assertEqual('mock_foo_bar', self.plugin.dest('foo_bar'))\n", "method_code": " def dest(self, var):\n \"\"\"Find a destination for given variable ``var``.\"\"\"\n return self.dest_namespace + var.replace('-', '_')\n ", "context": "class Plugin(object):\n def dest(self, var): ...\n def __init__(self, config, name): ...\n def option_namespace(self): ...\n def dest_namespace(self): ...\n def conf(self, var): ...\n def inject_parser_options(cls, parser, name): ...\n def add_parser_arguments(cls, add): ...\n\n self.config = config\n self.name = name\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_dest", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001648.py"} {"focal_file": "letsencrypt/plugins/common.py", "focal_class": null, "focal_method": "conf", "tests": "import unittest\n\nclass Test_conf(unittest.TestCase):\n def test_conf(self):\n self.assertEqual(self.config.mock_foo_bar, self.plugin.conf('foo-bar'))\n", "method_code": " def conf(self, var):\n \"\"\"Find a configuration value for variable ``var``.\"\"\"\n return getattr(self.config, self.dest(var))\n ", "context": "class Plugin(object):\n def conf(self, var): ...\n def __init__(self, config, name): ...\n def option_namespace(self): ...\n def dest_namespace(self): ...\n def dest(self, var): ...\n def inject_parser_options(cls, parser, name): ...\n def add_parser_arguments(cls, add): ...\n\n self.config = config\n self.name = name\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_conf", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001649.py"} {"focal_file": "letsencrypt/plugins/common.py", "focal_class": null, "focal_method": "inject_parser_options", "tests": "import unittest\n\nclass Test_inject_parser_options(unittest.TestCase):\n def test_inject_parser_options(self):\n parser = mock.MagicMock()\n self.plugin_cls.inject_parser_options(parser, 'mock')\n parser.add_argument.assert_called_once_with('--mock-foo-bar', dest='different_to_foo_bar', x=1, y=None)\n", "method_code": " def inject_parser_options(cls, parser, name):\n \"\"\"Inject parser options.\n \n See `~.IPlugin.inject_parser_options` for docs.\n \n \"\"\"\n \n def add(arg_name_no_prefix, *args, **kwargs):\n return parser.add_argument('--{0}{1}'.format(option_namespace(name), arg_name_no_prefix), *args, **kwargs)\n return cls.add_parser_arguments(add)\n ", "context": "class Plugin(object):\n @classmethod\n def inject_parser_options(cls, parser, name): ...\n def __init__(self, config, name): ...\n def option_namespace(self): ...\n def dest_namespace(self): ...\n def dest(self, var): ...\n def conf(self, var): ...\n def add_parser_arguments(cls, add): ...\n\n self.config = config\n self.name = name\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_inject_parser_options", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001650.py"} {"focal_file": "letsencrypt/plugins/common.py", "focal_class": null, "focal_method": "get_addr_obj", "tests": "import unittest\n\nclass Test_get_addr_obj(unittest.TestCase):\n def test_get_addr_obj(self):\n self.assertEqual(str(self.addr1.get_addr_obj('443')), '192.168.1.1:443')\n self.assertEqual(str(self.addr2.get_addr_obj('')), '192.168.1.1')\n self.assertEqual(str(self.addr1.get_addr_obj('*')), '192.168.1.1:*')\n", "method_code": " def get_addr_obj(self, port):\n \"\"\"Return new address object with same addr and new port.\"\"\"\n return self.__class__((self.tup[0], port))\n ", "context": "class Addr(object):\n def get_addr_obj(self, port): ...\n def __init__(self, tup): ...\n def fromstring(cls, str_addr): ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __hash__(self): ...\n def get_addr(self): ...\n def get_port(self): ...\n\n self.tup = tup\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_get_addr_obj", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001651.py"} {"focal_file": "letsencrypt/plugins/common.py", "focal_class": null, "focal_method": "add_chall", "tests": "import unittest\n\nclass Test_add_chall(unittest.TestCase):\n def test_add_chall(self):\n self.sni.add_chall(self.achalls[0], 0)\n self.assertEqual(1, len(self.sni.achalls))\n self.assertEqual([0], self.sni.indices)\n", "method_code": " def add_chall(self, achall, idx=None):\n \"\"\"Add challenge to DVSNI object to perform at once.\n \n :param achall: Annotated DVSNI challenge.\n :type achall: :class:`letsencrypt.achallenges.DVSNI`\n \n :param int idx: index to challenge in a larger array\n \n \"\"\"\n self.achalls.append(achall)\n if idx is not None:\n self.indices.append(idx)\n ", "context": "class Dvsni(object):\n def add_chall(self, achall, idx=None): ...\n def __init__(self, configurator): ...\n def get_cert_path(self, achall): ...\n def get_key_path(self, achall): ...\n def _setup_challenge_cert(self, achall, s=None): ...\n\n self.configurator = configurator\n self.achalls = []\n self.indices = []\n self.challenge_conf = os.path.join(configurator.config.config_dir, 'le_dvsni_cert_challenge.conf')\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_add_chall", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001652.py"} {"focal_file": "letsencrypt/plugins/common.py", "focal_class": null, "focal_method": "_setup_challenge_cert", "tests": "import unittest\n\nclass Test_setup_challenge_cert(unittest.TestCase):\n def test_setup_challenge_cert(self):\n mock_open, mock_safe_open = (mock.mock_open(), mock.mock_open())\n response = challenges.DVSNIResponse(s='randomS1')\n achall = mock.MagicMock(nonce=self.achalls[0].nonce, nonce_domain=self.achalls[0].nonce_domain)\n achall.gen_cert_and_response.return_value = ('pem', response)\n with mock.patch('letsencrypt.plugins.common.open', mock_open, create=True):\n with mock.patch('letsencrypt.plugins.common.le_util.safe_open', mock_safe_open):\n self.assertEqual(response, self.sni._setup_challenge_cert(achall, 'randomS1'))\n mock_open.assert_called_once_with(self.sni.get_cert_path(achall), 'wb')\n mock_open.return_value.write.assert_called_once_with('pem')\n mock_safe_open.assert_called_once_with(self.sni.get_key_path(achall), 'wb', chmod=256)\n mock_safe_open.return_value.write.assert_called_once_with(achall.key.key.private_bytes())\n", "method_code": " def _setup_challenge_cert(self, achall, s=None):\n \"\"\"Generate and write out challenge certificate.\"\"\"\n cert_path = self.get_cert_path(achall)\n key_path = self.get_key_path(achall)\n self.configurator.reverter.register_file_creation(True, key_path)\n self.configurator.reverter.register_file_creation(True, cert_path)\n cert_pem, response = achall.gen_cert_and_response(s)\n with open(cert_path, 'wb') as cert_chall_fd:\n cert_chall_fd.write(cert_pem)\n key_pem = achall.key.key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())\n with le_util.safe_open(key_path, 'wb', chmod=256) as key_file:\n key_file.write(key_pem)\n return response\n ", "context": "class Dvsni(object):\n def _setup_challenge_cert(self, achall, s=None): ...\n def __init__(self, configurator): ...\n def add_chall(self, achall, idx=None): ...\n def get_cert_path(self, achall): ...\n def get_key_path(self, achall): ...\n\n self.configurator = configurator\n self.achalls = []\n self.indices = []\n self.challenge_conf = os.path.join(configurator.config.config_dir, 'le_dvsni_cert_challenge.conf')\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_setup_challenge_cert", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001653.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "entry_point_to_plugin_name", "tests": "import unittest\n\nclass Test_entry_point_to_plugin_name(unittest.TestCase):\n def test_entry_point_to_plugin_name(self):\n from letsencrypt.plugins.disco import PluginEntryPoint\n names = {self.ep1: 'p1:ep1', self.ep1prim: 'p2:ep1', self.ep2: 'p2:ep2', self.ep3: 'p3:ep3', EP_SA: 'sa'}\n for entry_point, name in names.iteritems():\n self.assertEqual(name, PluginEntryPoint.entry_point_to_plugin_name(entry_point))\n", "method_code": " def entry_point_to_plugin_name(cls, entry_point):\n \"\"\"Unique plugin name for an ``entry_point``\"\"\"\n if entry_point.dist.key in cls.PREFIX_FREE_DISTRIBUTIONS:\n return entry_point.name\n return entry_point.dist.key + ':' + entry_point.name\n ", "context": "class PluginEntryPoint(object):\n @classmethod\n def entry_point_to_plugin_name(cls, entry_point): ...\n def __init__(self, entry_point): ...\n def description(self): ...\n def description_with_name(self): ...\n def ifaces(self, *ifaces_groups): ...\n def initialized(self): ...\n def init(self, config=None): ...\n def verify(self, ifaces): ...\n def prepared(self): ...\n def prepare(self): ...\n def misconfigured(self): ...\n def available(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self.name = self.entry_point_to_plugin_name(entry_point)\n self.plugin_cls = entry_point.load()\n self.entry_point = entry_point\n self._initialized = None\n self._prepared = None\n\n PREFIX_FREE_DISTRIBUTIONS = ['letsencrypt', 'letsencrypt-apache', 'letsencrypt-nginx']\n __hash__ = None\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_entry_point_to_plugin_name", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001654.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "ifaces", "tests": "import unittest\n\nclass Test_ifaces(unittest.TestCase):\n def test_ifaces(self):\n self.plugin_ep.ifaces.return_value = True\n self.assertEqual(self.plugins, self.reg.ifaces()._plugins)\n self.plugin_ep.ifaces.return_value = False\n self.assertEqual({}, self.reg.ifaces()._plugins)\n", "method_code": " def ifaces(self, *ifaces_groups):\n \"\"\"Does plugin implements specified interface groups?\"\"\"\n return not ifaces_groups or any((all((iface.implementedBy(self.plugin_cls) for iface in ifaces)) for ifaces in ifaces_groups))\n ", "context": "class PluginEntryPoint(object):\n def ifaces(self, *ifaces_groups): ...\n def __init__(self, entry_point): ...\n def entry_point_to_plugin_name(cls, entry_point): ...\n def description(self): ...\n def description_with_name(self): ...\n def initialized(self): ...\n def init(self, config=None): ...\n def verify(self, ifaces): ...\n def prepared(self): ...\n def prepare(self): ...\n def misconfigured(self): ...\n def available(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self.name = self.entry_point_to_plugin_name(entry_point)\n self.plugin_cls = entry_point.load()\n self.entry_point = entry_point\n self._initialized = None\n self._prepared = None\n\n PREFIX_FREE_DISTRIBUTIONS = ['letsencrypt', 'letsencrypt-apache', 'letsencrypt-nginx']\n __hash__ = None\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_ifaces", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001655.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "init", "tests": "import unittest\n\nclass Test_init(unittest.TestCase):\n def test_init(self):\n self.plugin_ep.init.return_value = 'baz'\n self.assertEqual(['baz'], self.reg.init('bar'))\n self.plugin_ep.init.assert_called_once_with('bar')\n", "method_code": " def init(self, config=None):\n \"\"\"Memoized plugin inititialization.\"\"\"\n if not self.initialized:\n self.entry_point.require()\n self._initialized = self.plugin_cls(config, self.name)\n return self._initialized\n ", "context": "class PluginEntryPoint(object):\n def init(self, config=None): ...\n def __init__(self, entry_point): ...\n def entry_point_to_plugin_name(cls, entry_point): ...\n def description(self): ...\n def description_with_name(self): ...\n def ifaces(self, *ifaces_groups): ...\n def initialized(self): ...\n def verify(self, ifaces): ...\n def prepared(self): ...\n def prepare(self): ...\n def misconfigured(self): ...\n def available(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self.name = self.entry_point_to_plugin_name(entry_point)\n self.plugin_cls = entry_point.load()\n self.entry_point = entry_point\n self._initialized = None\n self._prepared = None\n\n PREFIX_FREE_DISTRIBUTIONS = ['letsencrypt', 'letsencrypt-apache', 'letsencrypt-nginx']\n __hash__ = None\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_init", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001656.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "verify", "tests": "import unittest\n\nclass Test_verify(unittest.TestCase):\n def test_verify(self):\n self.plugin_ep.verify.return_value = True\n self.assertEqual(self.plugins, self.reg.verify(mock.MagicMock())._plugins)\n self.plugin_ep.verify.return_value = False\n self.assertEqual({}, self.reg.verify(mock.MagicMock())._plugins)\n", "method_code": " def verify(self, ifaces):\n \"\"\"Verify that the plugin conforms to the specified interfaces.\"\"\"\n assert self.initialized\n for iface in ifaces:\n try:\n zope.interface.verify.verifyObject(iface, self.init())\n except zope.interface.exceptions.BrokenImplementation as error:\n if iface.implementedBy(self.plugin_cls):\n logger.debug('%s implements %s but object does not verify: %s', self.plugin_cls, iface.__name__, error, exc_info=True)\n return False\n return True\n ", "context": "class PluginEntryPoint(object):\n def verify(self, ifaces): ...\n def __init__(self, entry_point): ...\n def entry_point_to_plugin_name(cls, entry_point): ...\n def description(self): ...\n def description_with_name(self): ...\n def ifaces(self, *ifaces_groups): ...\n def initialized(self): ...\n def init(self, config=None): ...\n def prepared(self): ...\n def prepare(self): ...\n def misconfigured(self): ...\n def available(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self.name = self.entry_point_to_plugin_name(entry_point)\n self.plugin_cls = entry_point.load()\n self.entry_point = entry_point\n self._initialized = None\n self._prepared = None\n\n PREFIX_FREE_DISTRIBUTIONS = ['letsencrypt', 'letsencrypt-apache', 'letsencrypt-nginx']\n __hash__ = None\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_verify", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001657.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "prepare", "tests": "import unittest\n\nclass Test_prepare(unittest.TestCase):\n def test_prepare(self):\n self.plugin_ep.prepare.return_value = 'baz'\n self.assertEqual(['baz'], self.reg.prepare())\n self.plugin_ep.prepare.assert_called_once_with()\n", "method_code": " def prepare(self):\n \"\"\"Memoized plugin preparation.\"\"\"\n assert self.initialized\n if self._prepared is None:\n try:\n self._initialized.prepare()\n except errors.MisconfigurationError as error:\n logger.debug('Misconfigured %r: %s', self, error, exc_info=True)\n self._prepared = error\n except errors.NoInstallationError as error:\n logger.debug('No installation (%r): %s', self, error, exc_info=True)\n self._prepared = error\n except errors.PluginError as error:\n logger.debug('Other error:(%r): %s', self, error, exc_info=True)\n self._prepared = error\n else:\n self._prepared = True\n return self._prepared\n ", "context": "class PluginEntryPoint(object):\n def prepare(self): ...\n def __init__(self, entry_point): ...\n def entry_point_to_plugin_name(cls, entry_point): ...\n def description(self): ...\n def description_with_name(self): ...\n def ifaces(self, *ifaces_groups): ...\n def initialized(self): ...\n def init(self, config=None): ...\n def verify(self, ifaces): ...\n def prepared(self): ...\n def misconfigured(self): ...\n def available(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self.name = self.entry_point_to_plugin_name(entry_point)\n self.plugin_cls = entry_point.load()\n self.entry_point = entry_point\n self._initialized = None\n self._prepared = None\n\n PREFIX_FREE_DISTRIBUTIONS = ['letsencrypt', 'letsencrypt-apache', 'letsencrypt-nginx']\n __hash__ = None\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_prepare", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001658.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "find_all", "tests": "import unittest\n\nclass Test_find_all(unittest.TestCase):\n def test_find_all(self):\n from letsencrypt.plugins.disco import PluginsRegistry\n with mock.patch('letsencrypt.plugins.disco.pkg_resources') as mock_pkg:\n mock_pkg.iter_entry_points.return_value = iter([EP_SA])\n plugins = PluginsRegistry.find_all()\n self.assertTrue(plugins['sa'].plugin_cls is authenticator.StandaloneAuthenticator)\n self.assertTrue(plugins['sa'].entry_point is EP_SA)\n", "method_code": " def find_all(cls):\n \"\"\"Find plugins using setuptools entry points.\"\"\"\n plugins = {}\n for entry_point in pkg_resources.iter_entry_points(constants.SETUPTOOLS_PLUGINS_ENTRY_POINT):\n plugin_ep = PluginEntryPoint(entry_point)\n assert plugin_ep.name not in plugins, 'PREFIX_FREE_DISTRIBUTIONS messed up'\n if interfaces.IPluginFactory.providedBy(plugin_ep.plugin_cls):\n plugins[plugin_ep.name] = plugin_ep\n else:\n logger.warning('%r does not provide IPluginFactory, skipping', plugin_ep)\n return cls(plugins)\n ", "context": "class PluginsRegistry(collections.Mapping):\n @classmethod\n def find_all(cls): ...\n def __init__(self, plugins): ...\n def __getitem__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def init(self, config): ...\n def filter(self, pred): ...\n def ifaces(self, *ifaces_groups): ...\n def verify(self, ifaces): ...\n def prepare(self): ...\n def available(self): ...\n def find_init(self, plugin): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self._plugins = plugins\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_find_all", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001659.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "filter", "tests": "import unittest\n\nclass Test_filter(unittest.TestCase):\n def test_filter(self):\n self.plugins.update({'foo': 'bar', 'bar': 'foo', 'baz': 'boo'})\n self.assertEqual({'foo': 'bar', 'baz': 'boo'}, self.reg.filter(lambda p_ep: str(p_ep).startswith('b')))\n", "method_code": " def filter(self, pred):\n \"\"\"Filter plugins based on predicate.\"\"\"\n return type(self)(dict(((name, plugin_ep) for name, plugin_ep in self._plugins.iteritems() if pred(plugin_ep))))\n ", "context": "class PluginsRegistry(collections.Mapping):\n def filter(self, pred): ...\n def __init__(self, plugins): ...\n def find_all(cls): ...\n def __getitem__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def init(self, config): ...\n def ifaces(self, *ifaces_groups): ...\n def verify(self, ifaces): ...\n def prepare(self): ...\n def available(self): ...\n def find_init(self, plugin): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self._plugins = plugins\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_filter", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001660.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "available", "tests": "import unittest\n\nclass Test_available(unittest.TestCase):\n def test_available(self):\n self.plugin_ep.available = True\n self.assertEqual(self.plugins, self.reg.available()._plugins)\n self.plugin_ep.available = False\n self.assertEqual({}, self.reg.available()._plugins)\n", "method_code": " def available(self):\n \"\"\"Is plugin available, i.e. prepared or misconfigured?\"\"\"\n return self._prepared is True or self.misconfigured\n ", "context": "class PluginEntryPoint(object):\n @property\n def available(self): ...\n def __init__(self, entry_point): ...\n def entry_point_to_plugin_name(cls, entry_point): ...\n def description(self): ...\n def description_with_name(self): ...\n def ifaces(self, *ifaces_groups): ...\n def initialized(self): ...\n def init(self, config=None): ...\n def verify(self, ifaces): ...\n def prepared(self): ...\n def prepare(self): ...\n def misconfigured(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self.name = self.entry_point_to_plugin_name(entry_point)\n self.plugin_cls = entry_point.load()\n self.entry_point = entry_point\n self._initialized = None\n self._prepared = None\n\n PREFIX_FREE_DISTRIBUTIONS = ['letsencrypt', 'letsencrypt-apache', 'letsencrypt-nginx']\n __hash__ = None\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_available", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001661.py"} {"focal_file": "letsencrypt/plugins/disco.py", "focal_class": null, "focal_method": "find_init", "tests": "import unittest\n\nclass Test_find_init(unittest.TestCase):\n def test_find_init(self):\n self.assertTrue(self.reg.find_init(mock.Mock()) is None)\n self.plugin_ep.initalized = True\n self.assertTrue(self.reg.find_init(self.plugin_ep.init()) is self.plugin_ep)\n", "method_code": " def find_init(self, plugin):\n \"\"\"Find an initialized plugin.\n \n This is particularly useful for finding a name for the plugin\n (although `.IPluginFactory.__call__` takes ``name`` as one of\n the arguments, ``IPlugin.name`` is not part of the interface)::\n \n # plugin is an instance providing IPlugin, initialized\n # somewhere else in the code\n plugin_registry.find_init(plugin).name\n \n Returns ``None`` if ``plugin`` is not found in the registry.\n \n \"\"\"\n candidates = [plugin_ep for plugin_ep in self._plugins.itervalues() if plugin_ep.initialized and plugin_ep.init() is plugin]\n assert len(candidates) <= 1\n if candidates:\n return candidates[0]\n else:\n return None\n ", "context": "class PluginsRegistry(collections.Mapping):\n def find_init(self, plugin): ...\n def __init__(self, plugins): ...\n def find_all(cls): ...\n def __getitem__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def init(self, config): ...\n def filter(self, pred): ...\n def ifaces(self, *ifaces_groups): ...\n def verify(self, ifaces): ...\n def prepare(self): ...\n def available(self): ...\n def __repr__(self): ...\n def __str__(self): ...\n\n self._plugins = plugins\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_find_init", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001662.py"} {"focal_file": "letsencrypt/plugins/manual.py", "focal_class": null, "focal_method": "more_info", "tests": "import unittest\n\nclass Test_more_info(unittest.TestCase):\n def test_more_info(self):\n self.assertTrue(isinstance(self.auth.more_info(), str))\n", "method_code": " def more_info(self):\n return \"This plugin requires user's manual intervention in setting up a HTTP\\nserver for solving SimpleHTTP challenges and thus does not need to be\\nrun as a privilidged process. Alternatively shows instructions on how\\nto use Python's built-in HTTP server and, in case of HTTPS, openssl\\nbinary for temporary key/certificate generation.\".replace('\\n', '')\n ", "context": "class ManualAuthenticator(common.Plugin):\n def more_info(self): ...\n def __init__(self, *args, **kwargs): ...\n def prepare(self): ...\n def get_chall_pref(self, domain): ...\n def perform(self, achalls): ...\n def _perform_single(self, achall): ...\n def _notify_and_wait(self, message): ...\n def cleanup(self, achalls): ...\n\n self.template = self.HTTP_TEMPLATE if self.config.no_simple_http_tls else self.HTTPS_TEMPLATE\n\n description = 'Manual Authenticator'\n MESSAGE_TEMPLATE = \"Make sure your web server displays the following content at\\n{uri} before continuing:\\n\\n{achall.token}\\n\\nContent-Type header MUST be set to {ct}.\\n\\nIf you don't have HTTP server configured, you can run the following\\ncommand on the target server (as root):\\n\\n{command}\\n\"\n HTTP_TEMPLATE = 'mkdir -p /tmp/letsencrypt/public_html/{response.URI_ROOT_PATH}\\ncd /tmp/letsencrypt/public_html\\necho -n {achall.token} > {response.URI_ROOT_PATH}/{response.path}\\n# run only once per server:\\npython -c \"import BaseHTTPServer, SimpleHTTPServer; \\\\\\nSimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map = {{\\'\\': \\'{ct}\\'}}; \\\\\\ns = BaseHTTPServer.HTTPServer((\\'\\', {port}), SimpleHTTPServer.SimpleHTTPRequestHandler); \\\\\\ns.serve_forever()\" '\n HTTPS_TEMPLATE = 'mkdir -p /tmp/letsencrypt/public_html/{response.URI_ROOT_PATH}\\ncd /tmp/letsencrypt/public_html\\necho -n {achall.token} > {response.URI_ROOT_PATH}/{response.path}\\n# run only once per server:\\nopenssl req -new -newkey rsa:4096 -subj \"/\" -days 1 -nodes -x509 -keyout ../key.pem -out ../cert.pem\\npython -c \"import BaseHTTPServer, SimpleHTTPServer, ssl; \\\\\\nSimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map = {{\\'\\': \\'{ct}\\'}}; \\\\\\ns = BaseHTTPServer.HTTPServer((\\'\\', {port}), SimpleHTTPServer.SimpleHTTPRequestHandler); \\\\\\ns.socket = ssl.wrap_socket(s.socket, keyfile=\\'../key.pem\\', certfile=\\'../cert.pem\\'); \\\\\\ns.serve_forever()\" '\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_more_info", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001663.py"} {"focal_file": "letsencrypt/plugins/manual.py", "focal_class": null, "focal_method": "get_chall_pref", "tests": "import unittest\n\nclass Test_get_chall_pref(unittest.TestCase):\n def test_get_chall_pref(self):\n self.assertTrue(all((issubclass(pref, challenges.Challenge) for pref in self.auth.get_chall_pref('foo.com'))))\n", "method_code": " def get_chall_pref(self, domain):\n return [challenges.SimpleHTTP]\n ", "context": "class ManualAuthenticator(common.Plugin):\n def get_chall_pref(self, domain): ...\n def __init__(self, *args, **kwargs): ...\n def prepare(self): ...\n def more_info(self): ...\n def perform(self, achalls): ...\n def _perform_single(self, achall): ...\n def _notify_and_wait(self, message): ...\n def cleanup(self, achalls): ...\n\n self.template = self.HTTP_TEMPLATE if self.config.no_simple_http_tls else self.HTTPS_TEMPLATE\n\n description = 'Manual Authenticator'\n MESSAGE_TEMPLATE = \"Make sure your web server displays the following content at\\n{uri} before continuing:\\n\\n{achall.token}\\n\\nContent-Type header MUST be set to {ct}.\\n\\nIf you don't have HTTP server configured, you can run the following\\ncommand on the target server (as root):\\n\\n{command}\\n\"\n HTTP_TEMPLATE = 'mkdir -p /tmp/letsencrypt/public_html/{response.URI_ROOT_PATH}\\ncd /tmp/letsencrypt/public_html\\necho -n {achall.token} > {response.URI_ROOT_PATH}/{response.path}\\n# run only once per server:\\npython -c \"import BaseHTTPServer, SimpleHTTPServer; \\\\\\nSimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map = {{\\'\\': \\'{ct}\\'}}; \\\\\\ns = BaseHTTPServer.HTTPServer((\\'\\', {port}), SimpleHTTPServer.SimpleHTTPRequestHandler); \\\\\\ns.serve_forever()\" '\n HTTPS_TEMPLATE = 'mkdir -p /tmp/letsencrypt/public_html/{response.URI_ROOT_PATH}\\ncd /tmp/letsencrypt/public_html\\necho -n {achall.token} > {response.URI_ROOT_PATH}/{response.path}\\n# run only once per server:\\nopenssl req -new -newkey rsa:4096 -subj \"/\" -days 1 -nodes -x509 -keyout ../key.pem -out ../cert.pem\\npython -c \"import BaseHTTPServer, SimpleHTTPServer, ssl; \\\\\\nSimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map = {{\\'\\': \\'{ct}\\'}}; \\\\\\ns = BaseHTTPServer.HTTPServer((\\'\\', {port}), SimpleHTTPServer.SimpleHTTPRequestHandler); \\\\\\ns.socket = ssl.wrap_socket(s.socket, keyfile=\\'../key.pem\\', certfile=\\'../cert.pem\\'); \\\\\\ns.serve_forever()\" '\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_get_chall_pref", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001664.py"} {"focal_file": "letsencrypt/plugins/manual.py", "focal_class": null, "focal_method": "perform", "tests": "import unittest\n\nclass Test_perform(unittest.TestCase):\n def test_perform_empty(self):\n self.assertEqual([], self.auth.perform([]))\n\n @mock.patch('letsencrypt.plugins.manual.sys.stdout')\n @mock.patch('letsencrypt.plugins.manual.os.urandom')\n @mock.patch('acme.challenges.SimpleHTTPResponse.simple_verify')\n @mock.patch('__builtin__.raw_input')\n def test_perform(self, mock_raw_input, mock_verify, mock_urandom, mock_stdout):\n mock_urandom.return_value = 'foo'\n mock_verify.return_value = True\n resp = challenges.SimpleHTTPResponse(tls=False, path='Zm9v')\n self.assertEqual([resp], self.auth.perform(self.achalls))\n self.assertEqual(1, mock_raw_input.call_count)\n mock_verify.assert_called_with(self.achalls[0].challb, 'foo.com', 4430)\n message = mock_stdout.write.mock_calls[0][1][0]\n self.assertTrue(self.achalls[0].token in message)\n self.assertTrue('Zm9v' in message)\n mock_verify.return_value = False\n self.assertEqual([None], self.auth.perform(self.achalls))\n", "method_code": " def perform(self, achalls):\n responses = []\n for achall in achalls:\n responses.append(self._perform_single(achall))\n return responses\n ", "context": "class ManualAuthenticator(common.Plugin):\n def perform(self, achalls): ...\n def __init__(self, *args, **kwargs): ...\n def prepare(self): ...\n def more_info(self): ...\n def get_chall_pref(self, domain): ...\n def _perform_single(self, achall): ...\n def _notify_and_wait(self, message): ...\n def cleanup(self, achalls): ...\n\n self.template = self.HTTP_TEMPLATE if self.config.no_simple_http_tls else self.HTTPS_TEMPLATE\n\n description = 'Manual Authenticator'\n MESSAGE_TEMPLATE = \"Make sure your web server displays the following content at\\n{uri} before continuing:\\n\\n{achall.token}\\n\\nContent-Type header MUST be set to {ct}.\\n\\nIf you don't have HTTP server configured, you can run the following\\ncommand on the target server (as root):\\n\\n{command}\\n\"\n HTTP_TEMPLATE = 'mkdir -p /tmp/letsencrypt/public_html/{response.URI_ROOT_PATH}\\ncd /tmp/letsencrypt/public_html\\necho -n {achall.token} > {response.URI_ROOT_PATH}/{response.path}\\n# run only once per server:\\npython -c \"import BaseHTTPServer, SimpleHTTPServer; \\\\\\nSimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map = {{\\'\\': \\'{ct}\\'}}; \\\\\\ns = BaseHTTPServer.HTTPServer((\\'\\', {port}), SimpleHTTPServer.SimpleHTTPRequestHandler); \\\\\\ns.serve_forever()\" '\n HTTPS_TEMPLATE = 'mkdir -p /tmp/letsencrypt/public_html/{response.URI_ROOT_PATH}\\ncd /tmp/letsencrypt/public_html\\necho -n {achall.token} > {response.URI_ROOT_PATH}/{response.path}\\n# run only once per server:\\nopenssl req -new -newkey rsa:4096 -subj \"/\" -days 1 -nodes -x509 -keyout ../key.pem -out ../cert.pem\\npython -c \"import BaseHTTPServer, SimpleHTTPServer, ssl; \\\\\\nSimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map = {{\\'\\': \\'{ct}\\'}}; \\\\\\ns = BaseHTTPServer.HTTPServer((\\'\\', {port}), SimpleHTTPServer.SimpleHTTPRequestHandler); \\\\\\ns.socket = ssl.wrap_socket(s.socket, keyfile=\\'../key.pem\\', certfile=\\'../cert.pem\\'); \\\\\\ns.serve_forever()\" '\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_perform_empty", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001665.py"} {"focal_file": "letsencrypt/account.py", "focal_class": null, "focal_method": "find_all", "tests": "import unittest\n\nclass Test_find_all(unittest.TestCase):\n def test_find_all(self):\n self.storage.save(self.acc)\n self.assertEqual([self.acc], self.storage.find_all())\n", "method_code": " def find_all(self):\n return self.accounts.values()\n ", "context": "class AccountMemoryStorage(interfaces.AccountStorage):\n def find_all(self): ...\n def __init__(self, initial_accounts=None): ...\n def save(self, account): ...\n def load(self, account_id): ...\n\n self.accounts = initial_accounts if initial_accounts is not None else {}\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_find_all", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001666.py"} {"focal_file": "letsencrypt/achallenges.py", "focal_class": null, "focal_method": "gen_cert_and_response", "tests": "import unittest\n\nclass Test_gen_cert_and_response(unittest.TestCase):\n def test_gen_cert_and_response(self):\n cert_pem, _ = self.achall.gen_cert_and_response(s=self.response.s)\n cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_pem)\n self.assertEqual(cert.get_subject().CN, 'example.com')\n self.assertEqual(acme_crypto_util._pyopenssl_cert_or_req_san(cert), ['example.com', self.chall.nonce_domain, self.response.z_domain(self.chall)])\n", "method_code": " def gen_cert_and_response(self, s=None):\n \"\"\"Generate a DVSNI cert and response.\n \n :returns: ``(cert_pem, response)`` tuple, where ``cert_pem`` is the PEM\n encoded certificate and ``response`` is an instance\n :class:`acme.challenges.DVSNIResponse`.\n :rtype: tuple\n \n \"\"\"\n key = crypto_util.private_jwk_to_pyopenssl(self.key)\n response = challenges.DVSNIResponse(s=s)\n cert = response.gen_cert(self.challb.chall, self.domain, key)\n cert_pem = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)\n return (cert_pem, response)\n \n __slots__ = ('challb', 'domain', 'key')\n acme_type = challenges.DVSNI\n", "context": "class DVSNI(AnnotatedChallenge):\n def gen_cert_and_response(self, s=None): ...", "repository": "stewnorriss/letsencrypt", "test_name": "test_gen_cert_and_response", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001667.py"} {"focal_file": "letsencrypt/auth_handler.py", "focal_class": null, "focal_method": "_poll_challenges", "tests": "import unittest\n\nclass Test_poll_challenges(unittest.TestCase):\n @mock.patch('letsencrypt.auth_handler.time')\n def test_poll_challenges(self, unused_mock_time):\n self.mock_net.poll.side_effect = self._mock_poll_solve_one_valid\n self.handler._poll_challenges(self.chall_update, False)\n for authzr in self.handler.authzr.values():\n self.assertEqual(authzr.body.status, messages.STATUS_VALID)\n", "method_code": " def _poll_challenges(self, chall_update, best_effort, min_sleep=3, max_rounds=15):\n \"\"\"Wait for all challenge results to be determined.\"\"\"\n dom_to_check = set(chall_update.keys())\n comp_domains = set()\n rounds = 0\n while dom_to_check and rounds < max_rounds:\n time.sleep(min_sleep)\n all_failed_achalls = set()\n for domain in dom_to_check:\n comp_achalls, failed_achalls = self._handle_check(domain, chall_update[domain])\n if len(comp_achalls) == len(chall_update[domain]):\n comp_domains.add(domain)\n elif not failed_achalls:\n for achall, _ in comp_achalls:\n chall_update[domain].remove(achall)\n elif best_effort:\n comp_domains.add(domain)\n else:\n all_failed_achalls.update((updated for _, updated in failed_achalls))\n if all_failed_achalls:\n _report_failed_challs(all_failed_achalls)\n raise errors.FailedChallenges(all_failed_achalls)\n dom_to_check -= comp_domains\n comp_domains.clear()\n rounds += 1\n ", "context": "class AuthHandler(object):\n def _poll_challenges(self, chall_update, best_effort, min_sleep=3, max_rounds=15): ...\n def __init__(self, dv_auth, cont_auth, acme, account): ...\n def get_authorizations(self, domains, best_effort=False): ...\n def _choose_challenges(self, domains): ...\n def _solve_challenges(self): ...\n def _respond(self, cont_resp, dv_resp, best_effort): ...\n def _send_responses(self, achalls, resps, chall_update): ...\n def _handle_check(self, domain, achalls): ...\n def _find_updated_challb(self, authzr, achall): ...\n def _get_chall_pref(self, domain): ...\n def _cleanup_challenges(self, achall_list=None): ...\n def verify_authzr_complete(self): ...\n def _challenge_factory(self, domain, path): ...\n\n self.dv_auth = dv_auth\n self.cont_auth = cont_auth\n self.acme = acme\n self.account = account\n self.authzr = dict()\n self.dv_c = []\n self.cont_c = []\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001668.py"} {"focal_file": "letsencrypt/client.py", "focal_class": null, "focal_method": "obtain_certificate_from_csr", "tests": "import unittest\n\nclass Test_obtain_certificate_from_csr(unittest.TestCase):\n def test_obtain_certificate_from_csr(self):\n self._mock_obtain_certificate()\n self.assertEqual((mock.sentinel.certr, mock.sentinel.chain), self.client.obtain_certificate_from_csr(le_util.CSR(form='der', file=None, data=CSR_SAN)))\n self._check_obtain_certificate()\n", "method_code": " def obtain_certificate_from_csr(self, csr):\n \"\"\"Obtain certficiate from CSR.\n \n :param .le_util.CSR csr: DER-encoded Certificate Signing\n Request.\n \n :returns: `.CertificateResource` and certificate chain (as\n returned by `.fetch_chain`).\n :rtype: tuple\n \n \"\"\"\n return self._obtain_certificate(crypto_util.get_sans_from_csr(csr.data, OpenSSL.crypto.FILETYPE_ASN1), csr)\n ", "context": "class Client(object):\n def obtain_certificate_from_csr(self, csr): ...\n def __init__(self, config, account_, dv_auth, installer, acme=None): ...\n def _obtain_certificate(self, domains, csr): ...\n def obtain_certificate(self, domains): ...\n def obtain_and_enroll_certificate(self, domains, authenticator, installer, plugins): ...\n def _report_renewal_status(self, cert): ...\n def save_certificate(self, certr, chain_cert, cert_path, chain_path): ...\n def deploy_certificate(self, domains, privkey_path, cert_path, chain_path): ...\n def enhance_config(self, domains, redirect=None): ...\n def redirect_to_ssl(self, domains): ...\n\n self.config = config\n self.account = account_\n self.installer = installer\n self.acme = acme\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_obtain_certificate_from_csr", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001669.py"} {"focal_file": "letsencrypt/client.py", "focal_class": null, "focal_method": "obtain_certificate", "tests": "import unittest\n\nclass Test_obtain_certificate(unittest.TestCase):\n @mock.patch('letsencrypt.client.crypto_util')\n def test_obtain_certificate(self, mock_crypto_util):\n self._mock_obtain_certificate()\n csr = le_util.CSR(form='der', file=None, data=CSR_SAN)\n mock_crypto_util.init_save_csr.return_value = csr\n mock_crypto_util.init_save_key.return_value = mock.sentinel.key\n domains = ['example.com', 'www.example.com']\n self.assertEqual(self.client.obtain_certificate(domains), (mock.sentinel.certr, mock.sentinel.chain, mock.sentinel.key, csr))\n mock_crypto_util.init_save_key.assert_called_once_with(self.config.rsa_key_size, self.config.key_dir)\n mock_crypto_util.init_save_csr.assert_called_once_with(mock.sentinel.key, domains, self.config.cert_dir)\n self._check_obtain_certificate()\n", "method_code": " def obtain_certificate(self, domains):\n \"\"\"Obtains a certificate from the ACME server.\n \n `.register` must be called before `.obtain_certificate`\n \n :param set domains: domains to get a certificate\n \n :returns: `.CertificateResource`, certificate chain (as\n returned by `.fetch_chain`), and newly generated private key\n (`.le_util.Key`) and DER-encoded Certificate Signing Request\n (`.le_util.CSR`).\n :rtype: tuple\n \n \"\"\"\n key = crypto_util.init_save_key(self.config.rsa_key_size, self.config.key_dir)\n csr = crypto_util.init_save_csr(key, domains, self.config.cert_dir)\n return self._obtain_certificate(domains, csr) + (key, csr)\n ", "context": "class Client(object):\n def obtain_certificate(self, domains): ...\n def __init__(self, config, account_, dv_auth, installer, acme=None): ...\n def _obtain_certificate(self, domains, csr): ...\n def obtain_certificate_from_csr(self, csr): ...\n def obtain_and_enroll_certificate(self, domains, authenticator, installer, plugins): ...\n def _report_renewal_status(self, cert): ...\n def save_certificate(self, certr, chain_cert, cert_path, chain_path): ...\n def deploy_certificate(self, domains, privkey_path, cert_path, chain_path): ...\n def enhance_config(self, domains, redirect=None): ...\n def redirect_to_ssl(self, domains): ...\n\n self.config = config\n self.account = account_\n self.installer = installer\n self.acme = acme\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001670.py"} {"focal_file": "letsencrypt/client.py", "focal_class": null, "focal_method": "_report_renewal_status", "tests": "import unittest\n\nclass Test_report_renewal_status(unittest.TestCase):\n @mock.patch('letsencrypt.client.zope.component.getUtility')\n def test_report_renewal_status(self, mock_zope):\n cert = mock.MagicMock()\n cert.configuration = configobj.ConfigObj()\n cert.cli_config = configuration.RenewerConfiguration(self.config)\n cert.configuration['autorenew'] = 'True'\n cert.configuration['autodeploy'] = 'True'\n self.client._report_renewal_status(cert)\n msg = mock_zope().add_message.call_args[0][0]\n self.assertTrue('renewal and deployment has been' in msg)\n self.assertTrue(cert.cli_config.renewal_configs_dir in msg)\n cert.configuration['autorenew'] = 'False'\n self.client._report_renewal_status(cert)\n msg = mock_zope().add_message.call_args[0][0]\n self.assertTrue('deployment but not automatic renewal' in msg)\n self.assertTrue(cert.cli_config.renewal_configs_dir in msg)\n cert.configuration['autodeploy'] = 'False'\n self.client._report_renewal_status(cert)\n msg = mock_zope().add_message.call_args[0][0]\n self.assertTrue('renewal and deployment has not' in msg)\n self.assertTrue(cert.cli_config.renewal_configs_dir in msg)\n cert.configuration['autorenew'] = 'True'\n self.client._report_renewal_status(cert)\n msg = mock_zope().add_message.call_args[0][0]\n self.assertTrue('renewal but not automatic deployment' in msg)\n self.assertTrue(cert.cli_config.renewal_configs_dir in msg)\n", "method_code": " def _report_renewal_status(self, cert):\n \"\"\"Informs the user about automatic renewal and deployment.\n \n :param .RenewableCert cert: Newly issued certificate\n \n \"\"\"\n if 'autorenew' not in cert.configuration or cert.configuration.as_bool('autorenew'):\n if 'autodeploy' not in cert.configuration or cert.configuration.as_bool('autodeploy'):\n msg = 'Automatic renewal and deployment has '\n else:\n msg = 'Automatic renewal but not automatic deployment has '\n elif 'autodeploy' not in cert.configuration or cert.configuration.as_bool('autodeploy'):\n msg = 'Automatic deployment but not automatic renewal has '\n else:\n msg = 'Automatic renewal and deployment has not '\n msg += 'been enabled for your certificate. These settings can be configured in the directories under {0}.'.format(cert.cli_config.renewal_configs_dir)\n reporter = zope.component.getUtility(interfaces.IReporter)\n reporter.add_message(msg, reporter.LOW_PRIORITY, True)\n ", "context": "class Client(object):\n def _report_renewal_status(self, cert): ...\n def __init__(self, config, account_, dv_auth, installer, acme=None): ...\n def _obtain_certificate(self, domains, csr): ...\n def obtain_certificate_from_csr(self, csr): ...\n def obtain_certificate(self, domains): ...\n def obtain_and_enroll_certificate(self, domains, authenticator, installer, plugins): ...\n def save_certificate(self, certr, chain_cert, cert_path, chain_path): ...\n def deploy_certificate(self, domains, privkey_path, cert_path, chain_path): ...\n def enhance_config(self, domains, redirect=None): ...\n def redirect_to_ssl(self, domains): ...\n\n self.config = config\n self.account = account_\n self.installer = installer\n self.acme = acme\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001671.py"} {"focal_file": "letsencrypt/continuity_auth.py", "focal_class": null, "focal_method": "get_chall_pref", "tests": "import unittest\n\nclass Test_get_chall_pref(unittest.TestCase):\n def test_chall_pref(self):\n self.assertEqual(self.auth.get_chall_pref('example.com'), [challenges.ProofOfPossession, challenges.RecoveryToken])\n", "method_code": " def get_chall_pref(self, unused_domain):\n \"\"\"Return list of challenge preferences.\"\"\"\n return [challenges.ProofOfPossession, challenges.RecoveryToken]\n ", "context": "class ContinuityAuthenticator(object):\n def get_chall_pref(self, unused_domain): ...\n def __init__(self, config, installer): ...\n def perform(self, achalls): ...\n def cleanup(self, achalls): ...\n\n self.rec_token = recovery_token.RecoveryToken(config.server, config.rec_token_dir)\n self.proof_of_pos = proof_of_possession.ProofOfPossession(installer)\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_chall_pref", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001672.py"} {"focal_file": "letsencrypt/recovery_token.py", "focal_class": null, "focal_method": "store_token", "tests": "import unittest\n\nclass Test_store_token(unittest.TestCase):\n def test_store_token(self):\n self.rec_token.store_token('example.com', 111)\n path = os.path.join(self.token_dir, 'example.com')\n self.assertTrue(os.path.isfile(path))\n with open(path) as token_fd:\n self.assertEqual(token_fd.read(), '111')\n", "method_code": " def store_token(self, domain, token):\n \"\"\"Store token for later automatic use.\n \n :param str domain: domain associated with the token\n :param str token: token from authorization\n \n \"\"\"\n le_util.make_or_verify_dir(self.token_dir, 448, os.geteuid())\n with open(os.path.join(self.token_dir, domain), 'w') as token_fd:\n token_fd.write(str(token))\n ", "context": "class RecoveryToken(object):\n def store_token(self, domain, token): ...\n def __init__(self, server, direc): ...\n def perform(self, chall): ...\n def cleanup(self, chall): ...\n def requires_human(self, domain): ...\n\n self.token_dir = os.path.join(direc, server)\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_store_token", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001673.py"} {"focal_file": "letsencrypt/recovery_token.py", "focal_class": null, "focal_method": "requires_human", "tests": "import unittest\n\nclass Test_requires_human(unittest.TestCase):\n def test_requires_human(self):\n self.rec_token.store_token('example2.com', 222)\n self.assertFalse(self.rec_token.requires_human('example2.com'))\n self.assertTrue(self.rec_token.requires_human('example3.com'))\n", "method_code": " def requires_human(self, domain):\n \"\"\"Indicates whether or not domain can be auto solved.\"\"\"\n return not os.path.isfile(os.path.join(self.token_dir, domain))\n ", "context": "class RecoveryToken(object):\n def requires_human(self, domain): ...\n def __init__(self, server, direc): ...\n def perform(self, chall): ...\n def cleanup(self, chall): ...\n def store_token(self, domain, token): ...\n\n self.token_dir = os.path.join(direc, server)\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_requires_human", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001674.py"} {"focal_file": "letsencrypt/recovery_token.py", "focal_class": "acme.challenges.RecoveryToken", "focal_method": "cleanup", "tests": "import unittest\n\nclass Test_acme_challenges_RecoveryToken_cleanup(unittest.TestCase):\n def test_cleanup(self):\n self.rec_token.store_token('example3.com', 333)\n self.assertFalse(self.rec_token.requires_human('example3.com'))\n self.rec_token.cleanup(achallenges.RecoveryToken(challb=challenges.RecoveryToken(), domain='example3.com'))\n self.assertTrue(self.rec_token.requires_human('example3.com'))\n self.rec_token.cleanup(achallenges.RecoveryToken(challb=None, domain='example4.com'))\n self.assertRaises(OSError, self.rec_token.cleanup, achallenges.RecoveryToken(challb=None, domain='a' + 'r' * 10000 + '.com'))\n", "method_code": " def cleanup(self, chall):\n \"\"\"Cleanup the saved recovery token if it exists.\n \n :param chall: Recovery Token Challenge\n :type chall: :class:`letsencrypt.achallenges.RecoveryToken`\n \n \"\"\"\n try:\n le_util.safely_remove(os.path.join(self.token_dir, chall.domain))\n except OSError as err:\n if err.errno != errno.ENOENT:\n raise\n ", "context": "class RecoveryToken(object):\n def cleanup(self, chall): ...\n def __init__(self, server, direc): ...\n def perform(self, chall): ...\n def requires_human(self, domain): ...\n def store_token(self, domain, token): ...\n\n self.token_dir = os.path.join(direc, server)\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_cleanup", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001675.py"} {"focal_file": "letsencrypt/reverter.py", "focal_class": null, "focal_method": "add_to_temp_checkpoint", "tests": "import unittest\n\nclass Test_add_to_temp_checkpoint(unittest.TestCase):\n def test_basic_add_to_temp_checkpoint(self):\n self.reverter.add_to_temp_checkpoint(self.sets[0], 'save1')\n self.reverter.add_to_temp_checkpoint(self.sets[1], 'save2')\n self.assertTrue(os.path.isdir(self.config.temp_checkpoint_dir))\n self.assertEqual(get_save_notes(self.config.temp_checkpoint_dir), 'save1save2')\n self.assertFalse(os.path.isfile(os.path.join(self.config.temp_checkpoint_dir, 'NEW_FILES')))\n self.assertEqual(get_filepaths(self.config.temp_checkpoint_dir), '{0}\\n{1}\\n'.format(self.config1, self.config2))\n", "method_code": " def add_to_temp_checkpoint(self, save_files, save_notes):\n \"\"\"Add files to temporary checkpoint.\n \n :param set save_files: set of filepaths to save\n :param str save_notes: notes about changes during the save\n \n \"\"\"\n self._add_to_checkpoint_dir(self.config.temp_checkpoint_dir, save_files, save_notes)\n ", "context": "class Reverter(object):\n def add_to_temp_checkpoint(self, save_files, save_notes): ...\n def __init__(self, config): ...\n def revert_temporary_config(self): ...\n def rollback_checkpoints(self, rollback=1): ...\n def view_config_changes(self): ...\n def add_to_checkpoint(self, save_files, save_notes): ...\n def _add_to_checkpoint_dir(self, cp_dir, save_files, save_notes): ...\n def _read_and_append(self, filepath): ...\n def _recover_checkpoint(self, cp_dir): ...\n def _check_tempfile_saves(self, save_files): ...\n def register_file_creation(self, temporary, *files): ...\n def recovery_routine(self): ...\n def _remove_contained_files(self, file_list): ...\n def finalize_checkpoint(self, title): ...\n def _timestamp_progress_dir(self): ...\n\n self.config = config\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_basic_add_to_temp_checkpoint", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001676.py"} {"focal_file": "letsencrypt/reverter.py", "focal_class": null, "focal_method": "add_to_checkpoint", "tests": "import unittest\n\nclass Test_add_to_checkpoint(unittest.TestCase):\n def test_checkpoint_conflict(self):\n \"\"\"Make sure that checkpoint errors are thrown appropriately.\"\"\"\n config3 = os.path.join(self.dir1, 'config3.txt')\n self.reverter.register_file_creation(True, config3)\n update_file(config3, 'This is a new file!')\n self.reverter.add_to_checkpoint(self.sets[2], 'save1')\n self.reverter.add_to_temp_checkpoint(self.sets[0], 'save2')\n self.assertRaises(errors.ReverterError, self.reverter.add_to_checkpoint, self.sets[2], 'save3')\n self.reverter.add_to_checkpoint(self.sets[1], 'save4')\n self.assertRaises(errors.ReverterError, self.reverter.add_to_checkpoint, set([config3]), 'invalid save')\n", "method_code": " def add_to_checkpoint(self, save_files, save_notes):\n \"\"\"Add files to a permanent checkpoint.\n \n :param set save_files: set of filepaths to save\n :param str save_notes: notes about changes during the save\n \n \"\"\"\n self._check_tempfile_saves(save_files)\n self._add_to_checkpoint_dir(self.config.in_progress_dir, save_files, save_notes)\n ", "context": "class Reverter(object):\n def add_to_checkpoint(self, save_files, save_notes): ...\n def __init__(self, config): ...\n def revert_temporary_config(self): ...\n def rollback_checkpoints(self, rollback=1): ...\n def view_config_changes(self): ...\n def add_to_temp_checkpoint(self, save_files, save_notes): ...\n def _add_to_checkpoint_dir(self, cp_dir, save_files, save_notes): ...\n def _read_and_append(self, filepath): ...\n def _recover_checkpoint(self, cp_dir): ...\n def _check_tempfile_saves(self, save_files): ...\n def register_file_creation(self, temporary, *files): ...\n def recovery_routine(self): ...\n def _remove_contained_files(self, file_list): ...\n def finalize_checkpoint(self, title): ...\n def _timestamp_progress_dir(self): ...\n\n self.config = config\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_checkpoint_conflict", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001677.py"} {"focal_file": "letsencrypt/reverter.py", "focal_class": null, "focal_method": "recovery_routine", "tests": "import unittest\n\nclass Test_recovery_routine(unittest.TestCase):\n def test_recovery_routine_temp_and_perm(self):\n config3 = os.path.join(self.dir1, 'config3.txt')\n self.reverter.register_file_creation(False, config3)\n update_file(config3, 'This is a new perm file!')\n self.reverter.add_to_checkpoint(self.sets[0], 'perm save1')\n update_file(self.config1, 'updated perm config1')\n self.reverter.add_to_checkpoint(self.sets[1], 'perm save2')\n update_file(self.config2, 'updated perm config2')\n self.reverter.add_to_temp_checkpoint(self.sets[0], 'temp save1')\n update_file(self.config1, 'second update now temp config1')\n config4 = os.path.join(self.dir2, 'config4.txt')\n self.reverter.register_file_creation(True, config4)\n update_file(config4, 'New temporary file!')\n self.reverter.recovery_routine()\n self.assertFalse(os.path.isfile(config3))\n self.assertFalse(os.path.isfile(config4))\n self.assertEqual(read_in(self.config1), 'directive-dir1')\n self.assertEqual(read_in(self.config2), 'directive-dir2')\n", "method_code": " def recovery_routine(self):\n \"\"\"Revert configuration to most recent finalized checkpoint.\n \n Remove all changes (temporary and permanent) that have not been\n finalized. This is useful to protect against crashes and other\n execution interruptions.\n \n \"\"\"\n self.revert_temporary_config()\n if os.path.isdir(self.config.in_progress_dir):\n try:\n self._recover_checkpoint(self.config.in_progress_dir)\n except errors.ReverterError:\n logger.fatal('Incomplete or failed recovery for IN_PROGRESS checkpoint - %s', self.config.in_progress_dir)\n raise errors.ReverterError('Incomplete or failed recovery for IN_PROGRESS checkpoint - %s' % self.config.in_progress_dir)\n ", "context": "class Reverter(object):\n def recovery_routine(self): ...\n def __init__(self, config): ...\n def revert_temporary_config(self): ...\n def rollback_checkpoints(self, rollback=1): ...\n def view_config_changes(self): ...\n def add_to_temp_checkpoint(self, save_files, save_notes): ...\n def add_to_checkpoint(self, save_files, save_notes): ...\n def _add_to_checkpoint_dir(self, cp_dir, save_files, save_notes): ...\n def _read_and_append(self, filepath): ...\n def _recover_checkpoint(self, cp_dir): ...\n def _check_tempfile_saves(self, save_files): ...\n def register_file_creation(self, temporary, *files): ...\n def _remove_contained_files(self, file_list): ...\n def finalize_checkpoint(self, title): ...\n def _timestamp_progress_dir(self): ...\n\n self.config = config\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_recovery_routine_temp_and_perm", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001678.py"} {"focal_file": "letsencrypt/reverter.py", "focal_class": null, "focal_method": "rollback_checkpoints", "tests": "import unittest\n\nclass Test_rollback_checkpoints(unittest.TestCase):\n def test_rollback_finalize_checkpoint_valid_inputs(self):\n config3 = self._setup_three_checkpoints()\n self.assertEqual(len(os.listdir(self.config.backup_dir)), 3)\n self.reverter.rollback_checkpoints(1)\n self.assertEqual(read_in(self.config1), 'update config1')\n self.assertEqual(read_in(self.config2), 'update config2')\n self.assertEqual(read_in(config3), 'Final form config3')\n self.reverter.rollback_checkpoints(1)\n self.assertEqual(read_in(self.config1), 'update config1')\n self.assertEqual(read_in(self.config2), 'directive-dir2')\n self.assertFalse(os.path.isfile(config3))\n all_dirs = os.listdir(self.config.backup_dir)\n self.assertEqual(len(all_dirs), 1)\n self.assertTrue('First Checkpoint' in get_save_notes(os.path.join(self.config.backup_dir, all_dirs[0])))\n self.reverter.rollback_checkpoints(1)\n self.assertEqual(read_in(self.config1), 'directive-dir1')\n", "method_code": " def rollback_checkpoints(self, rollback=1):\n \"\"\"Revert 'rollback' number of configuration checkpoints.\n \n :param int rollback: Number of checkpoints to reverse. A str num will be\n cast to an integer. So \"2\" is also acceptable.\n \n :raises .ReverterError:\n if there is a problem with the input or if the function is\n unable to correctly revert the configuration checkpoints\n \n \"\"\"\n try:\n rollback = int(rollback)\n except ValueError:\n logger.error('Rollback argument must be a positive integer')\n raise errors.ReverterError('Invalid Input')\n if rollback < 0:\n logger.error('Rollback argument must be a positive integer')\n raise errors.ReverterError('Invalid Input')\n backups = os.listdir(self.config.backup_dir)\n backups.sort()\n if len(backups) < rollback:\n logger.warning('Unable to rollback %d checkpoints, only %d exist', rollback, len(backups))\n while rollback > 0 and backups:\n cp_dir = os.path.join(self.config.backup_dir, backups.pop())\n try:\n self._recover_checkpoint(cp_dir)\n except errors.ReverterError:\n logger.fatal('Failed to load checkpoint during rollback')\n raise errors.ReverterError('Unable to load checkpoint during rollback')\n rollback -= 1\n ", "context": "class Reverter(object):\n def rollback_checkpoints(self, rollback=1): ...\n def __init__(self, config): ...\n def revert_temporary_config(self): ...\n def view_config_changes(self): ...\n def add_to_temp_checkpoint(self, save_files, save_notes): ...\n def add_to_checkpoint(self, save_files, save_notes): ...\n def _add_to_checkpoint_dir(self, cp_dir, save_files, save_notes): ...\n def _read_and_append(self, filepath): ...\n def _recover_checkpoint(self, cp_dir): ...\n def _check_tempfile_saves(self, save_files): ...\n def register_file_creation(self, temporary, *files): ...\n def recovery_routine(self): ...\n def _remove_contained_files(self, file_list): ...\n def finalize_checkpoint(self, title): ...\n def _timestamp_progress_dir(self): ...\n\n self.config = config\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_rollback_finalize_checkpoint_valid_inputs", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001679.py"} {"focal_file": "letsencrypt/reverter.py", "focal_class": null, "focal_method": "finalize_checkpoint", "tests": "import unittest\n\nclass Test_finalize_checkpoint(unittest.TestCase):\n def test_finalize_checkpoint_no_in_progress(self):\n self.reverter.finalize_checkpoint('No checkpoint...')\n", "method_code": " def finalize_checkpoint(self, title):\n \"\"\"Finalize the checkpoint.\n \n Timestamps and permanently saves all changes made through the use\n of :func:`~add_to_checkpoint` and :func:`~register_file_creation`\n \n :param str title: Title describing checkpoint\n \n :raises letsencrypt.errors.ReverterError: when the\n checkpoint is not able to be finalized.\n \n \"\"\"\n if not os.path.isdir(self.config.in_progress_dir):\n return\n changes_since_path = os.path.join(self.config.in_progress_dir, 'CHANGES_SINCE')\n changes_since_tmp_path = os.path.join(self.config.in_progress_dir, 'CHANGES_SINCE.tmp')\n try:\n with open(changes_since_tmp_path, 'w') as changes_tmp:\n changes_tmp.write('-- %s --\\n' % title)\n with open(changes_since_path, 'r') as changes_orig:\n changes_tmp.write(changes_orig.read())\n shutil.move(changes_since_tmp_path, changes_since_path)\n except (IOError, OSError):\n logger.error('Unable to finalize checkpoint - adding title')\n raise errors.ReverterError('Unable to add title')\n self._timestamp_progress_dir()\n ", "context": "class Reverter(object):\n def finalize_checkpoint(self, title): ...\n def __init__(self, config): ...\n def revert_temporary_config(self): ...\n def rollback_checkpoints(self, rollback=1): ...\n def view_config_changes(self): ...\n def add_to_temp_checkpoint(self, save_files, save_notes): ...\n def add_to_checkpoint(self, save_files, save_notes): ...\n def _add_to_checkpoint_dir(self, cp_dir, save_files, save_notes): ...\n def _read_and_append(self, filepath): ...\n def _recover_checkpoint(self, cp_dir): ...\n def _check_tempfile_saves(self, save_files): ...\n def register_file_creation(self, temporary, *files): ...\n def recovery_routine(self): ...\n def _remove_contained_files(self, file_list): ...\n def _timestamp_progress_dir(self): ...\n\n self.config = config\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_finalize_checkpoint_no_in_progress", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001680.py"} {"focal_file": "letsencrypt/reverter.py", "focal_class": null, "focal_method": "view_config_changes", "tests": "import unittest\n\nclass Test_view_config_changes(unittest.TestCase):\n @mock.patch('letsencrypt.reverter.zope.component.getUtility')\n def test_view_config_changes(self, mock_output):\n \"\"\"This is not strict as this is subject to change.\"\"\"\n self._setup_three_checkpoints()\n self.reverter.view_config_changes()\n self.assertEqual(mock_output().notification.call_count, 1)\n\n @mock.patch('letsencrypt.reverter.logger')\n def test_view_config_changes_no_backups(self, mock_logger):\n self.reverter.view_config_changes()\n self.assertTrue(mock_logger.info.call_count > 0)\n", "method_code": " def view_config_changes(self):\n \"\"\"Displays all saved checkpoints.\n \n All checkpoints are printed by\n :meth:`letsencrypt.interfaces.IDisplay.notification`.\n \n .. todo:: Decide on a policy for error handling, OSError IOError...\n \n \"\"\"\n backups = os.listdir(self.config.backup_dir)\n backups.sort(reverse=True)\n if not backups:\n logger.info(\"The Let's Encrypt client has not saved any backups of your configuration\")\n return\n try:\n for bkup in backups:\n float(bkup)\n except ValueError:\n raise errors.ReverterError('Invalid directories in {0}'.format(self.config.backup_dir))\n output = []\n for bkup in backups:\n output.append(time.ctime(float(bkup)))\n cur_dir = os.path.join(self.config.backup_dir, bkup)\n with open(os.path.join(cur_dir, 'CHANGES_SINCE')) as changes_fd:\n output.append(changes_fd.read())\n output.append('Affected files:')\n with open(os.path.join(cur_dir, 'FILEPATHS')) as paths_fd:\n filepaths = paths_fd.read().splitlines()\n for path in filepaths:\n output.append(' {0}'.format(path))\n if os.path.isfile(os.path.join(cur_dir, 'NEW_FILES')):\n with open(os.path.join(cur_dir, 'NEW_FILES')) as new_fd:\n output.append('New Configuration Files:')\n filepaths = new_fd.read().splitlines()\n for path in filepaths:\n output.append(' {0}'.format(path))\n output.append(os.linesep)\n zope.component.getUtility(interfaces.IDisplay).notification(os.linesep.join(output), display_util.HEIGHT)\n ", "context": "class Reverter(object):\n def view_config_changes(self): ...\n def __init__(self, config): ...\n def revert_temporary_config(self): ...\n def rollback_checkpoints(self, rollback=1): ...\n def add_to_temp_checkpoint(self, save_files, save_notes): ...\n def add_to_checkpoint(self, save_files, save_notes): ...\n def _add_to_checkpoint_dir(self, cp_dir, save_files, save_notes): ...\n def _read_and_append(self, filepath): ...\n def _recover_checkpoint(self, cp_dir): ...\n def _check_tempfile_saves(self, save_files): ...\n def register_file_creation(self, temporary, *files): ...\n def recovery_routine(self): ...\n def _remove_contained_files(self, file_list): ...\n def finalize_checkpoint(self, title): ...\n def _timestamp_progress_dir(self): ...\n\n self.config = config\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001681.py"} {"focal_file": "letsencrypt/revoker.py", "focal_class": null, "focal_method": "revoke_from_key", "tests": "import unittest\n\nclass Test_revoke_from_key(unittest.TestCase):\n @mock.patch('acme.client.Client.revoke')\n @mock.patch('letsencrypt.revoker.revocation')\n def test_revoke_by_wrong_key(self, mock_display, mock_acme):\n mock_display().confirm_revocation.return_value = True\n key_path = test_util.vector_path('rsa256_key.pem')\n wrong_key = le_util.Key(key_path, open(key_path).read())\n self.revoker.revoke_from_key(wrong_key)\n self.assertEqual(len(self._get_rows()), 2)\n self.assertEqual(mock_acme.call_count, 0)\n", "method_code": " def revoke_from_key(self, authkey):\n \"\"\"Revoke all certificates under an authorized key.\n \n :param authkey: Authorized key used in previous transactions\n :type authkey: :class:`letsencrypt.le_util.Key`\n \n \"\"\"\n certs = []\n try:\n clean_pem = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, authkey.pem))\n except OpenSSL.crypto.Error as error:\n logger.debug(error, exc_info=True)\n raise errors.RevokerError('Invalid key file specified to revoke_from_key')\n with open(self.list_path, 'rb') as csvfile:\n csvreader = csv.reader(csvfile)\n for row in csvreader:\n _, b_k = self._row_to_backup(row)\n try:\n test_pem = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, open(b_k).read()))\n except OpenSSL.crypto.Error as error:\n logger.debug(error, exc_info=True)\n raise errors.RevokerError('%s - backup file is corrupted.')\n if clean_pem == test_pem:\n certs.append(Cert.fromrow(row, self.config.cert_key_backup))\n if certs:\n self._safe_revoke(certs)\n else:\n logger.info('No certificates using the authorized key were found.')\n ", "context": "class Revoker(object):\n def revoke_from_key(self, authkey): ...\n def __init__(self, installer, config, no_confirm=False): ...\n def revoke_from_cert(self, cert_path): ...\n def revoke_from_menu(self): ...\n def _populate_saved_certs(self, csha1_vhlist): ...\n def _get_installed_locations(self): ...\n def _safe_revoke(self, certs): ...\n def _acme_revoke(self, cert): ...\n def _remove_certs_keys(self, cert_list): ...\n def _remove_certs_from_list(self, cert_list): ...\n def _row_to_backup(self, row): ...\n def store_cert_key(cls, cert_path, key_path, config): ...\n def _catalog_files(cls, backup_dir, cert_path, key_path, list_path): ...\n def _copy_files(cls, backup_dir, idx, cert_path, key_path): ...\n def _get_backup(cls, backup_dir, idx, orig_path): ...\n\n self.acme = acme_client.Client(new_reg_uri=None, key=None, alg=None)\n self.installer = installer\n self.config = config\n self.no_confirm = no_confirm\n self.list_path = os.path.join(config.cert_key_backup, 'LIST')\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001682.py"} {"focal_file": "letsencrypt/revoker.py", "focal_class": null, "focal_method": "revoke_from_cert", "tests": "import unittest\n\nclass Test_revoke_from_cert(unittest.TestCase):\n @mock.patch('acme.client.Client.revoke')\n @mock.patch('letsencrypt.revoker.revocation')\n def test_revoke_by_cert(self, mock_display, mock_acme):\n mock_display().confirm_revocation.return_value = True\n self.revoker.revoke_from_cert(self.paths[1])\n row0 = self.certs[0].get_row()\n row1 = self.certs[1].get_row()\n self.assertEqual(self._get_rows(), [row0])\n self.assertTrue(self._backups_exist(row0))\n self.assertFalse(self._backups_exist(row1))\n self.assertEqual(mock_acme.call_count, 1)\n", "method_code": " def revoke_from_cert(self, cert_path):\n \"\"\"Revoke a certificate by specifying a file path.\n \n .. todo:: Add the ability to revoke the certificate even if the cert\n is not stored locally. A path to the auth key will need to be\n attained from the user.\n \n :param str cert_path: path to ACME certificate in pem form\n \n \"\"\"\n cert_to_revoke = Cert(cert_path)\n with open(self.list_path, 'rb') as csvfile:\n csvreader = csv.reader(csvfile)\n for row in csvreader:\n cert = Cert.fromrow(row, self.config.cert_key_backup)\n if cert.get_der() == cert_to_revoke.get_der():\n self._safe_revoke([cert])\n return\n logger.info('Associated ACME certificate was not found.')\n ", "context": "class Revoker(object):\n def revoke_from_cert(self, cert_path): ...\n def __init__(self, installer, config, no_confirm=False): ...\n def revoke_from_key(self, authkey): ...\n def revoke_from_menu(self): ...\n def _populate_saved_certs(self, csha1_vhlist): ...\n def _get_installed_locations(self): ...\n def _safe_revoke(self, certs): ...\n def _acme_revoke(self, cert): ...\n def _remove_certs_keys(self, cert_list): ...\n def _remove_certs_from_list(self, cert_list): ...\n def _row_to_backup(self, row): ...\n def store_cert_key(cls, cert_path, key_path, config): ...\n def _catalog_files(cls, backup_dir, cert_path, key_path, list_path): ...\n def _copy_files(cls, backup_dir, idx, cert_path, key_path): ...\n def _get_backup(cls, backup_dir, idx, orig_path): ...\n\n self.acme = acme_client.Client(new_reg_uri=None, key=None, alg=None)\n self.installer = installer\n self.config = config\n self.no_confirm = no_confirm\n self.list_path = os.path.join(config.cert_key_backup, 'LIST')\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001683.py"} {"focal_file": "letsencrypt/revoker.py", "focal_class": null, "focal_method": "revoke_from_menu", "tests": "import unittest\n\nclass Test_revoke_from_menu(unittest.TestCase):\n @mock.patch('acme.client.Client.revoke')\n @mock.patch('letsencrypt.revoker.revocation')\n def test_revoke_by_menu(self, mock_display, mock_acme):\n mock_display().confirm_revocation.return_value = True\n mock_display.display_certs.side_effect = [(display_util.HELP, 0), (display_util.OK, 0), (display_util.CANCEL, -1)]\n self.revoker.revoke_from_menu()\n row0 = self.certs[0].get_row()\n row1 = self.certs[1].get_row()\n self.assertEqual(self._get_rows(), [row1])\n self.assertFalse(self._backups_exist(row0))\n self.assertTrue(self._backups_exist(row1))\n self.assertEqual(mock_acme.call_count, 1)\n self.assertEqual(mock_display.more_info_cert.call_count, 1)\n", "method_code": " def revoke_from_menu(self):\n \"\"\"List trusted Let's Encrypt certificates.\"\"\"\n csha1_vhlist = self._get_installed_locations()\n certs = self._populate_saved_certs(csha1_vhlist)\n while True:\n if certs:\n code, selection = revocation.display_certs(certs)\n if code == display_util.OK:\n revoked_certs = self._safe_revoke([certs[selection]])\n if revoked_certs:\n del certs[selection]\n elif code == display_util.HELP:\n revocation.more_info_cert(certs[selection])\n else:\n return\n else:\n logger.info(\"There are not any trusted Let's Encrypt certificates for this server.\")\n return\n ", "context": "class Revoker(object):\n def revoke_from_menu(self): ...\n def __init__(self, installer, config, no_confirm=False): ...\n def revoke_from_key(self, authkey): ...\n def revoke_from_cert(self, cert_path): ...\n def _populate_saved_certs(self, csha1_vhlist): ...\n def _get_installed_locations(self): ...\n def _safe_revoke(self, certs): ...\n def _acme_revoke(self, cert): ...\n def _remove_certs_keys(self, cert_list): ...\n def _remove_certs_from_list(self, cert_list): ...\n def _row_to_backup(self, row): ...\n def store_cert_key(cls, cert_path, key_path, config): ...\n def _catalog_files(cls, backup_dir, cert_path, key_path, list_path): ...\n def _copy_files(cls, backup_dir, idx, cert_path, key_path): ...\n def _get_backup(cls, backup_dir, idx, orig_path): ...\n\n self.acme = acme_client.Client(new_reg_uri=None, key=None, alg=None)\n self.installer = installer\n self.config = config\n self.no_confirm = no_confirm\n self.list_path = os.path.join(config.cert_key_backup, 'LIST')\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001684.py"} {"focal_file": "letsencrypt/revoker.py", "focal_class": null, "focal_method": "_safe_revoke", "tests": "import unittest\n\nclass Test_safe_revoke(unittest.TestCase):\n @mock.patch('letsencrypt.revoker.revocation')\n @mock.patch('letsencrypt.revoker.Revoker._acme_revoke')\n @mock.patch('letsencrypt.revoker.logger')\n def test_safe_revoke_acme_fail(self, mock_log, mock_revoke, mock_display):\n mock_revoke.side_effect = errors.Error\n mock_display().confirm_revocation.return_value = True\n self.revoker._safe_revoke(self.certs)\n self.assertTrue(mock_log.error.called)\n", "method_code": " def _safe_revoke(self, certs):\n \"\"\"Confirm and revoke certificates.\n \n :param certs: certs intended to be revoked\n :type certs: :class:`list` of :class:`letsencrypt.revoker.Cert`\n \n :returns: certs successfully revoked\n :rtype: :class:`list` of :class:`letsencrypt.revoker.Cert`\n \n \"\"\"\n success_list = []\n try:\n for cert in certs:\n if self.no_confirm or revocation.confirm_revocation(cert):\n try:\n self._acme_revoke(cert)\n except errors.Error:\n logger.error('Unable to revoke cert:%s%s', os.linesep, str(cert))\n success_list.append(cert)\n revocation.success_revocation(cert)\n finally:\n if success_list:\n self._remove_certs_keys(success_list)\n return success_list\n ", "context": "class Revoker(object):\n def _safe_revoke(self, certs): ...\n def __init__(self, installer, config, no_confirm=False): ...\n def revoke_from_key(self, authkey): ...\n def revoke_from_cert(self, cert_path): ...\n def revoke_from_menu(self): ...\n def _populate_saved_certs(self, csha1_vhlist): ...\n def _get_installed_locations(self): ...\n def _acme_revoke(self, cert): ...\n def _remove_certs_keys(self, cert_list): ...\n def _remove_certs_from_list(self, cert_list): ...\n def _row_to_backup(self, row): ...\n def store_cert_key(cls, cert_path, key_path, config): ...\n def _catalog_files(cls, backup_dir, cert_path, key_path, list_path): ...\n def _copy_files(cls, backup_dir, idx, cert_path, key_path): ...\n def _get_backup(cls, backup_dir, idx, orig_path): ...\n\n self.acme = acme_client.Client(new_reg_uri=None, key=None, alg=None)\n self.installer = installer\n self.config = config\n self.no_confirm = no_confirm\n self.list_path = os.path.join(config.cert_key_backup, 'LIST')\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001685.py"} {"focal_file": "letsencrypt/revoker.py", "focal_class": null, "focal_method": "_get_installed_locations", "tests": "import unittest\n\nclass Test_get_installed_locations(unittest.TestCase):\n def test_no_installer_get_installed_locations(self):\n revoker = self._get_revoker(None)\n self.assertEqual(revoker._get_installed_locations(), {})\n\n def test_get_installed_locations(self):\n mock_installer = mock.MagicMock()\n mock_installer.get_all_certs_keys.return_value = self.certs_keys\n revoker = self._get_revoker(mock_installer)\n sha_vh = revoker._get_installed_locations()\n self.assertEqual(len(sha_vh), 2)\n for i, cert in enumerate(self.certs):\n self.assertTrue(cert.get_fingerprint() in sha_vh)\n self.assertEqual(sha_vh[cert.get_fingerprint()], self.installs[i])\n\n @mock.patch('letsencrypt.revoker.OpenSSL.crypto.load_certificate')\n def test_get_installed_load_failure(self, mock_load_certificate):\n mock_installer = mock.MagicMock()\n mock_installer.get_all_certs_keys.return_value = self.certs_keys\n mock_load_certificate.side_effect = OpenSSL.crypto.Error\n revoker = self._get_revoker(mock_installer)\n self.assertEqual(revoker._get_installed_locations(), {})\n\n def test_get_installed_load_failure_open(self):\n tmp = tempfile.mkdtemp()\n mock_installer = mock.MagicMock()\n mock_installer.get_all_certs_keys.return_value = [(os.path.join(tmp, 'missing'), None, None)]\n revoker = self._get_revoker(mock_installer)\n self.assertEqual(revoker._get_installed_locations(), {})\n os.rmdir(tmp)\n", "method_code": " def _get_installed_locations(self):\n \"\"\"Get installed locations of certificates.\n \n :returns: map from cert sha1 fingerprint to :class:`list` of vhosts\n where the certificate is installed.\n \n \"\"\"\n csha1_vhlist = {}\n if self.installer is None:\n return csha1_vhlist\n for cert_path, _, path in self.installer.get_all_certs_keys():\n try:\n with open(cert_path) as cert_file:\n cert_data = cert_file.read()\n except IOError:\n continue\n try:\n cert_obj, _ = crypto_util.pyopenssl_load_certificate(cert_data)\n except errors.Error:\n continue\n cert_sha1 = cert_obj.digest('sha1')\n if cert_sha1 in csha1_vhlist:\n csha1_vhlist[cert_sha1].append(path)\n else:\n csha1_vhlist[cert_sha1] = [path]\n return csha1_vhlist\n ", "context": "class Revoker(object):\n def _get_installed_locations(self): ...\n def __init__(self, installer, config, no_confirm=False): ...\n def revoke_from_key(self, authkey): ...\n def revoke_from_cert(self, cert_path): ...\n def revoke_from_menu(self): ...\n def _populate_saved_certs(self, csha1_vhlist): ...\n def _safe_revoke(self, certs): ...\n def _acme_revoke(self, cert): ...\n def _remove_certs_keys(self, cert_list): ...\n def _remove_certs_from_list(self, cert_list): ...\n def _row_to_backup(self, row): ...\n def store_cert_key(cls, cert_path, key_path, config): ...\n def _catalog_files(cls, backup_dir, cert_path, key_path, list_path): ...\n def _copy_files(cls, backup_dir, idx, cert_path, key_path): ...\n def _get_backup(cls, backup_dir, idx, orig_path): ...\n\n self.acme = acme_client.Client(new_reg_uri=None, key=None, alg=None)\n self.installer = installer\n self.config = config\n self.no_confirm = no_confirm\n self.list_path = os.path.join(config.cert_key_backup, 'LIST')\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_no_installer_get_installed_locations", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001686.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "notification", "tests": "import unittest\n\nclass Test_notification(unittest.TestCase):\n @mock.patch('letsencrypt.display.util.dialog.Dialog.msgbox')\n def test_notification(self, mock_msgbox):\n \"\"\"Kind of worthless... one liner.\"\"\"\n self.displayer.notification('message')\n self.assertEqual(mock_msgbox.call_count, 1)\n\n def test_notification_no_pause(self):\n self.displayer.notification('message', 10, False)\n string = self.mock_stdout.write.call_args[0][0]\n self.assertTrue('message' in string)\n\n def test_notification_pause(self):\n with mock.patch('__builtin__.raw_input', return_value='enter'):\n self.displayer.notification('message')\n self.assertTrue('message' in self.mock_stdout.write.call_args[0][0])\n", "method_code": " def notification(self, message, height=10, pause=False):\n \"\"\"Display a notification to the user and wait for user acceptance.\n \n .. todo:: It probably makes sense to use one of the transient message\n types for pause. It isn't straightforward how best to approach\n the matter though given the context of our messages.\n http://pythondialog.sourceforge.net/doc/widgets.html#displaying-transient-messages\n \n :param str message: Message to display\n :param int height: Height of the dialog box\n :param bool pause: Not applicable to NcursesDisplay\n \n \"\"\"\n self.dialog.msgbox(message, height, width=self.width)\n ", "context": "class NcursesDisplay(object):\n def notification(self, message, height=10, pause=False): ...\n def __init__(self, width=WIDTH, height=HEIGHT): ...\n def menu(self, message, choices, ok_label='OK', cancel_label='Cancel', help_label=''): ...\n def input(self, message): ...\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n def checklist(self, message, tags, default_status=True): ...\n\n self.dialog = dialog.Dialog()\n self.width = width\n self.height = height\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001687.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "input", "tests": "import unittest\n\nclass Test_input(unittest.TestCase):\n @mock.patch('letsencrypt.display.util.dialog.Dialog.inputbox')\n def test_input(self, mock_input):\n self.displayer.input('message')\n self.assertEqual(mock_input.call_count, 1)\n", "method_code": " def input(self, message):\n \"\"\"Display an input box to the user.\n \n :param str message: Message to display that asks for input.\n \n :returns: tuple of the form (code, string) where\n `code` - int display exit code\n `string` - input entered by the user\n \n \"\"\"\n return self.dialog.inputbox(message, width=self.width)\n ", "context": "class NcursesDisplay(object):\n def input(self, message): ...\n def __init__(self, width=WIDTH, height=HEIGHT): ...\n def notification(self, message, height=10, pause=False): ...\n def menu(self, message, choices, ok_label='OK', cancel_label='Cancel', help_label=''): ...\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n def checklist(self, message, tags, default_status=True): ...\n\n self.dialog = dialog.Dialog()\n self.width = width\n self.height = height\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001688.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "yesno", "tests": "import unittest\n\nclass Test_yesno(unittest.TestCase):\n def test_yesno(self):\n with mock.patch('__builtin__.raw_input', return_value='Yes'):\n self.assertTrue(self.displayer.yesno('message'))\n with mock.patch('__builtin__.raw_input', return_value='y'):\n self.assertTrue(self.displayer.yesno('message'))\n with mock.patch('__builtin__.raw_input', side_effect=['maybe', 'y']):\n self.assertTrue(self.displayer.yesno('message'))\n with mock.patch('__builtin__.raw_input', return_value='No'):\n self.assertFalse(self.displayer.yesno('message'))\n with mock.patch('__builtin__.raw_input', side_effect=['cancel', 'n']):\n self.assertFalse(self.displayer.yesno('message'))\n with mock.patch('__builtin__.raw_input', return_value='a'):\n self.assertTrue(self.displayer.yesno('msg', yes_label='Agree'))\n", "method_code": " def yesno(self, message, yes_label='Yes', no_label='No'):\n \"\"\"Display a Yes/No dialog box.\n \n Yes and No label must begin with different letters.\n \n :param str message: message to display to user\n :param str yes_label: label on the \"yes\" button\n :param str no_label: label on the \"no\" button\n \n :returns: if yes_label was selected\n :rtype: bool\n \n \"\"\"\n return self.dialog.DIALOG_OK == self.dialog.yesno(message, self.height, self.width, yes_label=yes_label, no_label=no_label)\n ", "context": "class NcursesDisplay(object):\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n def __init__(self, width=WIDTH, height=HEIGHT): ...\n def notification(self, message, height=10, pause=False): ...\n def menu(self, message, choices, ok_label='OK', cancel_label='Cancel', help_label=''): ...\n def input(self, message): ...\n def checklist(self, message, tags, default_status=True): ...\n\n self.dialog = dialog.Dialog()\n self.width = width\n self.height = height\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_yesno", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001689.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "checklist", "tests": "import unittest\n\nclass Test_checklist(unittest.TestCase):\n @mock.patch('letsencrypt.display.util.dialog.Dialog.checklist')\n def test_checklist(self, mock_checklist):\n self.displayer.checklist('message', TAGS)\n choices = [(TAGS[0], '', True), (TAGS[1], '', True), (TAGS[2], '', True)]\n mock_checklist.assert_called_with('message', width=display_util.WIDTH, height=display_util.HEIGHT, choices=choices)\n", "method_code": " def checklist(self, message, tags, default_status=True):\n \"\"\"Displays a checklist.\n \n :param message: Message to display before choices\n :param list tags: where each is of type :class:`str` len(tags) > 0\n :param bool default_status: If True, items are in a selected state by\n default.\n \n \n :returns: tuple of the form (code, list_tags) where\n `code` - int display exit code\n `list_tags` - list of str tags selected by the user\n \n \"\"\"\n choices = [(tag, '', default_status) for tag in tags]\n return self.dialog.checklist(message, width=self.width, height=self.height, choices=choices)\n ", "context": "class NcursesDisplay(object):\n def checklist(self, message, tags, default_status=True): ...\n def __init__(self, width=WIDTH, height=HEIGHT): ...\n def notification(self, message, height=10, pause=False): ...\n def menu(self, message, choices, ok_label='OK', cancel_label='Cancel', help_label=''): ...\n def input(self, message): ...\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n\n self.dialog = dialog.Dialog()\n self.width = width\n self.height = height\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001690.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "menu", "tests": "import unittest\n\nclass Test_menu(unittest.TestCase):\n @mock.patch('letsencrypt.display.util.FileDisplay._get_valid_int_ans')\n def test_menu(self, mock_ans):\n mock_ans.return_value = (display_util.OK, 1)\n ret = self.displayer.menu('message', CHOICES)\n self.assertEqual(ret, (display_util.OK, 0))\n", "method_code": " def menu(self, message, choices, ok_label='OK', cancel_label='Cancel', help_label=''):\n \"\"\"Display a menu.\n \n :param str message: title of menu\n \n :param choices: menu lines, len must be > 0\n :type choices: list of tuples (`tag`, `item`) tags must be unique or\n list of items (tags will be enumerated)\n \n :param str ok_label: label of the OK button\n :param str help_label: label of the help button\n \n :returns: tuple of the form (`code`, `tag`) where\n `code` - `str` display_util exit code\n `tag` - `int` index corresponding to the item chosen\n :rtype: tuple\n \n \"\"\"\n menu_options = {'choices': choices, 'ok_label': ok_label, 'cancel_label': cancel_label, 'help_button': bool(help_label), 'help_label': help_label, 'width': self.width, 'height': self.height, 'menu_height': self.height - 6}\n if choices and isinstance(choices[0], tuple):\n code, selection = self.dialog.menu(message, **menu_options)\n for i, choice in enumerate(choices):\n if choice[0] == selection:\n return (code, i)\n return (code, -1)\n else:\n menu_options['choices'] = [(str(i), choice) for i, choice in enumerate(choices, 1)]\n code, tag = self.dialog.menu(message, **menu_options)\n if code == CANCEL:\n return (code, -1)\n return (code, int(tag) - 1)\n ", "context": "class NcursesDisplay(object):\n def menu(self, message, choices, ok_label='OK', cancel_label='Cancel', help_label=''): ...\n def __init__(self, width=WIDTH, height=HEIGHT): ...\n def notification(self, message, height=10, pause=False): ...\n def input(self, message): ...\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n def checklist(self, message, tags, default_status=True): ...\n\n self.dialog = dialog.Dialog()\n self.width = width\n self.height = height\n", "repository": "stewnorriss/letsencrypt", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001691.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "_scrub_checklist_input", "tests": "import unittest\n\nclass Test_scrub_checklist_input(unittest.TestCase):\n def test_scrub_checklist_input_valid(self):\n indices = [['1'], ['1', '2', '1'], ['2', '3']]\n exp = [set(['tag1']), set(['tag1', 'tag2']), set(['tag2', 'tag3'])]\n for i, list_ in enumerate(indices):\n set_tags = set(self.displayer._scrub_checklist_input(list_, TAGS))\n self.assertEqual(set_tags, exp[i])\n\n def test_scrub_checklist_input_invalid(self):\n indices = [['0'], ['4'], ['tag1'], ['1', 'tag1'], ['2', 'o']]\n for list_ in indices:\n self.assertEqual(self.displayer._scrub_checklist_input(list_, TAGS), [])\n", "method_code": " def _scrub_checklist_input(self, indices, tags):\n \"\"\"Validate input and transform indices to appropriate tags.\n \n :param list indices: input\n :param list tags: Original tags of the checklist\n \n :returns: valid tags the user selected\n :rtype: :class:`list` of :class:`str`\n \n \"\"\"\n try:\n indices = [int(index) for index in indices]\n except ValueError:\n return []\n indices = list(set(indices))\n for index in indices:\n if index < 1 or index > len(tags):\n return []\n return [tags[index - 1] for index in indices]\n ", "context": "class FileDisplay(object):\n def _scrub_checklist_input(self, indices, tags): ...\n def __init__(self, outfile): ...\n def notification(self, message, height=10, pause=True): ...\n def menu(self, message, choices, ok_label='', cancel_label='', help_label=''): ...\n def input(self, message): ...\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n def checklist(self, message, tags, default_status=True): ...\n def _print_menu(self, message, choices): ...\n def _wrap_lines(self, msg): ...\n def _get_valid_int_ans(self, max_): ...\n\n self.outfile = outfile\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_scrub_checklist_input_valid", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001692.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "_print_menu", "tests": "import unittest\n\nclass Test_print_menu(unittest.TestCase):\n def test_print_menu(self):\n self.displayer._print_menu('msg', CHOICES)\n self.displayer._print_menu('msg', TAGS)\n", "method_code": " def _print_menu(self, message, choices):\n \"\"\"Print a menu on the screen.\n \n :param str message: title of menu\n :param choices: Menu lines\n :type choices: list of tuples (tag, item) or\n list of descriptions (tags will be enumerated)\n \n \"\"\"\n if choices and isinstance(choices[0], tuple):\n choices = ['%s - %s' % (c[0], c[1]) for c in choices]\n self.outfile.write('{new}{msg}{new}'.format(new=os.linesep, msg=message))\n side_frame = '-' * 79 + os.linesep\n self.outfile.write(side_frame)\n for i, desc in enumerate(choices, 1):\n self.outfile.write(textwrap.fill('{num}: {desc}'.format(num=i, desc=desc), 80))\n self.outfile.write(os.linesep)\n self.outfile.write(side_frame)\n ", "context": "class FileDisplay(object):\n def _print_menu(self, message, choices): ...\n def __init__(self, outfile): ...\n def notification(self, message, height=10, pause=True): ...\n def menu(self, message, choices, ok_label='', cancel_label='', help_label=''): ...\n def input(self, message): ...\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n def checklist(self, message, tags, default_status=True): ...\n def _scrub_checklist_input(self, indices, tags): ...\n def _wrap_lines(self, msg): ...\n def _get_valid_int_ans(self, max_): ...\n\n self.outfile = outfile\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_print_menu", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001693.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "_wrap_lines", "tests": "import unittest\n\nclass Test_wrap_lines(unittest.TestCase):\n def test_wrap_lines(self):\n msg = 'This is just a weak test{0}This function is only meant to be for easy viewing{0}Test a really really really really really really really really really really really really long line...'.format(os.linesep)\n text = self.displayer._wrap_lines(msg)\n self.assertEqual(text.count(os.linesep), 3)\n", "method_code": " def _wrap_lines(self, msg):\n \"\"\"Format lines nicely to 80 chars.\n \n :param str msg: Original message\n \n :returns: Formatted message respecting newlines in message\n :rtype: str\n \n \"\"\"\n lines = msg.splitlines()\n fixed_l = []\n for line in lines:\n fixed_l.append(textwrap.fill(line, 80))\n return os.linesep.join(fixed_l)\n ", "context": "class FileDisplay(object):\n def _wrap_lines(self, msg): ...\n def __init__(self, outfile): ...\n def notification(self, message, height=10, pause=True): ...\n def menu(self, message, choices, ok_label='', cancel_label='', help_label=''): ...\n def input(self, message): ...\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n def checklist(self, message, tags, default_status=True): ...\n def _scrub_checklist_input(self, indices, tags): ...\n def _print_menu(self, message, choices): ...\n def _get_valid_int_ans(self, max_): ...\n\n self.outfile = outfile\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_wrap_lines", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001694.py"} {"focal_file": "letsencrypt/display/util.py", "focal_class": null, "focal_method": "_get_valid_int_ans", "tests": "import unittest\n\nclass Test_get_valid_int_ans(unittest.TestCase):\n def test_get_valid_int_ans_valid(self):\n with mock.patch('__builtin__.raw_input', return_value='1'):\n self.assertEqual(self.displayer._get_valid_int_ans(1), (display_util.OK, 1))\n ans = '2'\n with mock.patch('__builtin__.raw_input', return_value=ans):\n self.assertEqual(self.displayer._get_valid_int_ans(3), (display_util.OK, int(ans)))\n\n def test_get_valid_int_ans_invalid(self):\n answers = [['0', 'c'], ['4', 'one', 'C'], ['c']]\n for ans in answers:\n with mock.patch('__builtin__.raw_input', side_effect=ans):\n self.assertEqual(self.displayer._get_valid_int_ans(3), (display_util.CANCEL, -1))\n", "method_code": " def _get_valid_int_ans(self, max_):\n \"\"\"Get a numerical selection.\n \n :param int max: The maximum entry (len of choices), must be positive\n \n :returns: tuple of the form (`code`, `selection`) where\n `code` - str display exit code ('ok' or cancel')\n `selection` - int user's selection\n :rtype: tuple\n \n \"\"\"\n selection = -1\n if max_ > 1:\n input_msg = \"Select the appropriate number [1-{max_}] then [enter] (press 'c' to cancel): \".format(max_=max_)\n else:\n input_msg = \"Press 1 [enter] to confirm the selection (press 'c' to cancel): \"\n while selection < 1:\n ans = raw_input(input_msg)\n if ans.startswith('c') or ans.startswith('C'):\n return (CANCEL, -1)\n try:\n selection = int(ans)\n if selection < 1 or selection > max_:\n selection = -1\n raise ValueError\n except ValueError:\n self.outfile.write('{0}** Invalid input **{0}'.format(os.linesep))\n return (OK, selection)\n ", "context": "class FileDisplay(object):\n def _get_valid_int_ans(self, max_): ...\n def __init__(self, outfile): ...\n def notification(self, message, height=10, pause=True): ...\n def menu(self, message, choices, ok_label='', cancel_label='', help_label=''): ...\n def input(self, message): ...\n def yesno(self, message, yes_label='Yes', no_label='No'): ...\n def checklist(self, message, tags, default_status=True): ...\n def _scrub_checklist_input(self, indices, tags): ...\n def _print_menu(self, message, choices): ...\n def _wrap_lines(self, msg): ...\n\n self.outfile = outfile\n", "repository": "stewnorriss/letsencrypt", "test_name": "test_get_valid_int_ans_valid", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001695.py"} {"focal_file": "Crypto/PublicKey/DSA.py", "focal_class": null, "focal_method": "generate", "tests": "import unittest\n\nclass Test_generate(unittest.TestCase):\n def test_generate_1arg(self):\n \"\"\"DSA (default implementation) generated key (1 argument)\"\"\"\n dsaObj = self.dsa.generate(1024)\n self._check_private_key(dsaObj)\n pub = dsaObj.publickey()\n self._check_public_key(pub)\n\n def test_generate_2arg(self):\n \"\"\"DSA (default implementation) generated key (2 arguments)\"\"\"\n dsaObj = self.dsa.generate(1024, Random.new().read)\n self._check_private_key(dsaObj)\n pub = dsaObj.publickey()\n self._check_public_key(pub)\n", "method_code": " def generate(self, bits, randfunc=None, progress_func=None):\n for i in (0, 1, 2, 3, 4, 5, 6, 7, 8):\n if bits == 512 + 64 * i:\n return self._generate(bits, randfunc, progress_func)\n raise ValueError('Number of bits in p must be a multiple of 64 between 512 and 1024, not %d bits' % (bits,))\n ", "context": "class DSAImplementation(object):\n def generate(self, bits, randfunc=None, progress_func=None): ...\n def __init__(self, **kwargs): ...\n def _get_randfunc(self, randfunc): ...\n def _generate(self, bits, randfunc=None, progress_func=None): ...\n def construct(self, tup): ...\n\n self.error = self._math.error\n self._default_randfunc = kwargs.get('default_randfunc', None)\n self._current_randfunc = None\n", "repository": "twinkleMing/CIS753_PA2", "test_name": "test_generate_1arg", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001696.py"} {"focal_file": "Crypto/PublicKey/DSA.py", "focal_class": null, "focal_method": "construct", "tests": "import unittest\n\nclass Test_construct(unittest.TestCase):\n def test_construct_4tuple(self):\n \"\"\"DSA (default implementation) constructed key (4-tuple)\"\"\"\n y, g, p, q = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]\n dsaObj = self.dsa.construct((y, g, p, q))\n self._test_verification(dsaObj)\n\n def test_construct_5tuple(self):\n \"\"\"DSA (default implementation) constructed key (5-tuple)\"\"\"\n y, g, p, q, x = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]\n dsaObj = self.dsa.construct((y, g, p, q, x))\n self._test_signing(dsaObj)\n self._test_verification(dsaObj)\n", "method_code": " def construct(self, tup):\n key = self._math.dsa_construct(*tup)\n return _DSAobj(self, key)\n ", "context": "class DSAImplementation(object):\n def construct(self, tup): ...\n def __init__(self, **kwargs): ...\n def _get_randfunc(self, randfunc): ...\n def generate(self, bits, randfunc=None, progress_func=None): ...\n def _generate(self, bits, randfunc=None, progress_func=None): ...\n\n self.error = self._math.error\n self._default_randfunc = kwargs.get('default_randfunc', None)\n self._current_randfunc = None\n", "repository": "twinkleMing/CIS753_PA2", "test_name": "test_construct_4tuple", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001697.py"} {"focal_file": "PDDL.py", "focal_class": null, "focal_method": "scan_tokens", "tests": "import unittest\n\nclass Test_scan_tokens(unittest.TestCase):\n def test_scan_tokens_domain(self):\n parser = PDDL_Parser()\n self.assertEqual(parser.scan_tokens('examples/dinner/dinner.pddl'), ['define', ['domain', 'dinner'], [':requirements', ':strips'], [':predicates', ['clean'], ['dinner'], ['quiet'], ['present'], ['garbage']], [':action', 'cook', ':precondition', ['clean'], ':effect', ['dinner']], [':action', 'wrap', ':precondition', ['quiet'], ':effect', ['present']], [':action', 'carry', ':precondition', ['garbage'], ':effect', ['and', ['not', ['garbage']], ['not', ['clean']]]], [':action', 'dolly', ':precondition', ['garbage'], ':effect', ['and', ['not', ['garbage']], ['not', ['quiet']]]]])\n\n def test_scan_tokens_problem(self):\n parser = PDDL_Parser()\n self.assertEqual(parser.scan_tokens('examples/dinner/pb1.pddl'), ['define', ['problem', 'pb1'], [':domain', 'dinner'], [':init', ['garbage'], ['clean'], ['quiet']], [':goal', ['and', ['dinner'], ['present'], ['not', ['garbage']]]]])\n", "method_code": " def scan_tokens(self, filename):\n with open(filename, 'r') as f:\n str = re.sub(';.*$', '', f.read(), flags=re.MULTILINE).lower()\n stack = []\n list = []\n for t in re.findall('[()]|[^\\\\s()]+', str):\n if t == '(':\n stack.append(list)\n list = []\n elif t == ')':\n if stack:\n l = list\n list = stack.pop()\n list.append(l)\n else:\n raise Exception('Missing open parentheses')\n else:\n list.append(t)\n if stack:\n raise Exception('Missing close parentheses')\n if len(list) != 1:\n raise Exception('Malformed expression')\n return list[0]\n ", "context": "class PDDL_Parser():\n def scan_tokens(self, filename): ...\n def parse_domain(self, domain_filename): ...\n def parse_domain_extended(self, t, group): ...\n def parse_hierarchy(self, group, structure, name, redefine): ...\n def parse_objects(self, group, name): ...\n def parse_types(self, group): ...\n def parse_predicates(self, group): ...\n def parse_action(self, group): ...\n def parse_action_extended(self, t, group): ...\n def parse_problem(self, problem_filename): ...\n def parse_problem_extended(self, t, group): ...\n def split_predicates(self, group, positive, negative, name, part): ...\n\n SUPPORTED_REQUIREMENTS = [':strips', ':negative-preconditions', ':typing']\n", "repository": "pucrs-automated-planning/pddl-parser", "test_name": "test_scan_tokens_domain", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001698.py"} {"focal_file": "PDDL.py", "focal_class": null, "focal_method": "parse_domain", "tests": "import unittest\n\nclass Test_parse_domain(unittest.TestCase):\n def test_parse_domain(self):\n parser = PDDL_Parser()\n parser.parse_domain('examples/dinner/dinner.pddl')\n self.assertEqual(parser.domain_name, 'dinner')\n self.assertEqual(parser.requirements, [':strips'])\n self.assertEqual(parser.predicates, {'clean': {}, 'dinner': {}, 'quiet': {}, 'present': {}, 'garbage': {}})\n self.assertEqual(parser.types, {})\n self.assertEqual(parser.actions, [Action('cook', [], [['clean']], [], [['dinner']], []), Action('wrap', [], [['quiet']], [], [['present']], []), Action('carry', [], [['garbage']], [], [], [['garbage'], ['clean']]), Action('dolly', [], [['garbage']], [], [], [['garbage'], ['quiet']])])\n", "method_code": " def parse_domain(self, domain_filename):\n tokens = self.scan_tokens(domain_filename)\n if type(tokens) is list and tokens.pop(0) == 'define':\n self.domain_name = 'unknown'\n self.requirements = []\n self.types = {}\n self.objects = {}\n self.actions = []\n self.predicates = {}\n while tokens:\n group = tokens.pop(0)\n t = group.pop(0)\n if t == 'domain':\n self.domain_name = group[0]\n elif t == ':requirements':\n for req in group:\n if not req in self.SUPPORTED_REQUIREMENTS:\n raise Exception('Requirement ' + req + ' not supported')\n self.requirements = group\n elif t == ':constants':\n self.parse_objects(group, t)\n elif t == ':predicates':\n self.parse_predicates(group)\n elif t == ':types':\n self.parse_types(group)\n elif t == ':action':\n self.parse_action(group)\n else:\n self.parse_domain_extended(t, group)\n else:\n raise Exception('File ' + domain_filename + ' does not match domain pattern')\n ", "context": "class PDDL_Parser():\n def parse_domain(self, domain_filename): ...\n def scan_tokens(self, filename): ...\n def parse_domain_extended(self, t, group): ...\n def parse_hierarchy(self, group, structure, name, redefine): ...\n def parse_objects(self, group, name): ...\n def parse_types(self, group): ...\n def parse_predicates(self, group): ...\n def parse_action(self, group): ...\n def parse_action_extended(self, t, group): ...\n def parse_problem(self, problem_filename): ...\n def parse_problem_extended(self, t, group): ...\n def split_predicates(self, group, positive, negative, name, part): ...\n\n SUPPORTED_REQUIREMENTS = [':strips', ':negative-preconditions', ':typing']\n", "repository": "pucrs-automated-planning/pddl-parser", "test_name": "test_parse_domain", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001699.py"} {"focal_file": "PDDL.py", "focal_class": null, "focal_method": "parse_problem", "tests": "import unittest\n\nclass Test_parse_problem(unittest.TestCase):\n def test_parse_problem(self):\n\n def frozenset_of_tuples(data):\n return frozenset([tuple(t) for t in data])\n parser = PDDL_Parser()\n parser.parse_domain('examples/dinner/dinner.pddl')\n parser.parse_problem('examples/dinner/pb1.pddl')\n self.assertEqual(parser.problem_name, 'pb1')\n self.assertEqual(parser.objects, {})\n self.assertEqual(parser.state, frozenset_of_tuples([['garbage'], ['clean'], ['quiet']]))\n self.assertEqual(parser.positive_goals, frozenset_of_tuples([['dinner'], ['present']]))\n self.assertEqual(parser.negative_goals, frozenset_of_tuples([['garbage']]))\n", "method_code": " def parse_problem(self, problem_filename):\n \n def frozenset_of_tuples(data):\n return frozenset([tuple(t) for t in data])\n tokens = self.scan_tokens(problem_filename)\n if type(tokens) is list and tokens.pop(0) == 'define':\n self.problem_name = 'unknown'\n self.state = frozenset()\n self.positive_goals = frozenset()\n self.negative_goals = frozenset()\n while tokens:\n group = tokens.pop(0)\n t = group.pop(0)\n if t == 'problem':\n self.problem_name = group[0]\n elif t == ':domain':\n if self.domain_name != group[0]:\n raise Exception('Different domain specified in problem file')\n elif t == ':requirements':\n pass\n elif t == ':objects':\n self.parse_objects(group, t)\n elif t == ':init':\n self.state = frozenset_of_tuples(group)\n elif t == ':goal':\n positive_goals = []\n negative_goals = []\n self.split_predicates(group[0], positive_goals, negative_goals, '', 'goals')\n self.positive_goals = frozenset_of_tuples(positive_goals)\n self.negative_goals = frozenset_of_tuples(negative_goals)\n else:\n self.parse_problem_extended(t, group)\n else:\n raise Exception('File ' + problem_filename + ' does not match problem pattern')\n ", "context": "class PDDL_Parser():\n def parse_problem(self, problem_filename): ...\n def scan_tokens(self, filename): ...\n def parse_domain(self, domain_filename): ...\n def parse_domain_extended(self, t, group): ...\n def parse_hierarchy(self, group, structure, name, redefine): ...\n def parse_objects(self, group, name): ...\n def parse_types(self, group): ...\n def parse_predicates(self, group): ...\n def parse_action(self, group): ...\n def parse_action_extended(self, t, group): ...\n def parse_problem_extended(self, t, group): ...\n def split_predicates(self, group, positive, negative, name, part): ...\n\n SUPPORTED_REQUIREMENTS = [':strips', ':negative-preconditions', ':typing']\n", "repository": "pucrs-automated-planning/pddl-parser", "test_name": "test_parse_problem", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001700.py"} {"focal_file": "PDDL.py", "focal_class": null, "focal_method": "parse_predicates", "tests": "import unittest\n\nclass Test_parse_predicates(unittest.TestCase):\n def test_parse_predicates(self):\n parser = PDDL_Parser()\n parser.predicates = {}\n parser.parse_predicates([['untyped_pred', '?v1', '?v2', '?v3'], ['typed_pred', '?v1', '-', 'type1', '?v2', '-', 'type1', '?v3', '-', 'object'], ['shared_type_pred', '?v1', '?v2', '-', 'type1', '?v3']])\n self.assertEqual(parser.predicates, {'untyped_pred': {'?v1': 'object', '?v2': 'object', '?v3': 'object'}, 'typed_pred': {'?v1': 'type1', '?v2': 'type1', '?v3': 'object'}, 'shared_type_pred': {'?v1': 'type1', '?v2': 'type1', '?v3': 'object'}})\n", "method_code": " def parse_predicates(self, group):\n for pred in group:\n predicate_name = pred.pop(0)\n if predicate_name in self.predicates:\n raise Exception('Predicate ' + predicate_name + ' redefined')\n arguments = {}\n untyped_variables = []\n while pred:\n t = pred.pop(0)\n if t == '-':\n if not untyped_variables:\n raise Exception('Unexpected hyphen in predicates')\n type = pred.pop(0)\n while untyped_variables:\n arguments[untyped_variables.pop(0)] = type\n else:\n untyped_variables.append(t)\n while untyped_variables:\n arguments[untyped_variables.pop(0)] = 'object'\n self.predicates[predicate_name] = arguments\n ", "context": "class PDDL_Parser():\n def parse_predicates(self, group): ...\n def scan_tokens(self, filename): ...\n def parse_domain(self, domain_filename): ...\n def parse_domain_extended(self, t, group): ...\n def parse_hierarchy(self, group, structure, name, redefine): ...\n def parse_objects(self, group, name): ...\n def parse_types(self, group): ...\n def parse_action(self, group): ...\n def parse_action_extended(self, t, group): ...\n def parse_problem(self, problem_filename): ...\n def parse_problem_extended(self, t, group): ...\n def split_predicates(self, group, positive, negative, name, part): ...\n\n SUPPORTED_REQUIREMENTS = [':strips', ':negative-preconditions', ':typing']\n", "repository": "pucrs-automated-planning/pddl-parser", "test_name": "test_parse_predicates", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001701.py"} {"focal_file": "PDDL.py", "focal_class": null, "focal_method": "parse_types", "tests": "import unittest\n\nclass Test_parse_types(unittest.TestCase):\n def test_parse_undefined_types(self):\n parser = PDDL_Parser()\n parser.types = {}\n parser.parse_types(['location', 'pile', 'robot', 'crane', 'container'])\n self.assertEqual(parser.types, {'object': ['location', 'pile', 'robot', 'crane', 'container']})\n\n def test_parse_defined_types(self):\n parser = PDDL_Parser()\n parser.types = {}\n parser.parse_types(['place', 'locatable', 'level', '-', 'object', 'depot', 'market', '-', 'place', 'truck', 'goods', '-', 'locatable'])\n self.assertEqual(parser.types, {'object': ['place', 'locatable', 'level'], 'place': ['depot', 'market'], 'locatable': ['truck', 'goods']})\n", "method_code": " def parse_types(self, group):\n self.parse_hierarchy(group, self.types, 'types', True)\n ", "context": "class PDDL_Parser():\n def parse_types(self, group): ...\n def scan_tokens(self, filename): ...\n def parse_domain(self, domain_filename): ...\n def parse_domain_extended(self, t, group): ...\n def parse_hierarchy(self, group, structure, name, redefine): ...\n def parse_objects(self, group, name): ...\n def parse_predicates(self, group): ...\n def parse_action(self, group): ...\n def parse_action_extended(self, t, group): ...\n def parse_problem(self, problem_filename): ...\n def parse_problem_extended(self, t, group): ...\n def split_predicates(self, group, positive, negative, name, part): ...\n\n SUPPORTED_REQUIREMENTS = [':strips', ':negative-preconditions', ':typing']\n", "repository": "pucrs-automated-planning/pddl-parser", "test_name": "test_parse_undefined_types", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001702.py"} {"focal_file": "PDDL.py", "focal_class": null, "focal_method": "parse_objects", "tests": "import unittest\n\nclass Test_parse_objects(unittest.TestCase):\n def test_parse_objects(self):\n parser = PDDL_Parser()\n parser.types = {}\n parser.objects = {}\n parser.parse_types(['airplane', 'segment', 'direction', 'airplanetype', 'a'])\n parser.parse_objects(['b', '-', 'a', 'a', '-', 'a', 'north', 'south', '-', 'direction', 'light', 'medium', 'heavy', '-', 'airplanetype', 'element1', '-', 'object', 'seg_pp_0_60', 'seg_ppdoor_0_40', '-', 'segment', 'airplane_CFBEG', '-', 'airplane', 'element2'], 'test')\n self.assertEqual(parser.objects, {'a': ['b', 'a'], 'object': ['element1', 'element2'], 'direction': ['north', 'south'], 'airplanetype': ['light', 'medium', 'heavy'], 'segment': ['seg_pp_0_60', 'seg_ppdoor_0_40'], 'airplane': ['airplane_CFBEG']})\n", "method_code": " def parse_objects(self, group, name):\n self.parse_hierarchy(group, self.objects, name, False)\n ", "context": "class PDDL_Parser():\n def parse_objects(self, group, name): ...\n def scan_tokens(self, filename): ...\n def parse_domain(self, domain_filename): ...\n def parse_domain_extended(self, t, group): ...\n def parse_hierarchy(self, group, structure, name, redefine): ...\n def parse_types(self, group): ...\n def parse_predicates(self, group): ...\n def parse_action(self, group): ...\n def parse_action_extended(self, t, group): ...\n def parse_problem(self, problem_filename): ...\n def parse_problem_extended(self, t, group): ...\n def split_predicates(self, group, positive, negative, name, part): ...\n\n SUPPORTED_REQUIREMENTS = [':strips', ':negative-preconditions', ':typing']\n", "repository": "pucrs-automated-planning/pddl-parser", "test_name": "test_parse_objects", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001703.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "version", "tests": "import unittest\n\nclass Test_version(unittest.TestCase):\n def test_server_vars(self):\n version = self.server.version()\n self.assertTrue(isinstance(version, basestring))\n config = self.server.config()\n self.assertTrue(isinstance(config, dict))\n tasks = self.server.tasks()\n self.assertTrue(isinstance(tasks, list))\n", "method_code": " def version(self):\n \"\"\"The version string of the CouchDB server.\n \n Note that this results in a request being made, and can also be used\n to check for the availability of the server.\n \n :rtype: `unicode`\"\"\"\n status, headers, data = self.resource.get_json()\n return data['version']\n ", "context": "class Server(object):\n def version(self): ...\n def __init__(self, url=DEFAULT_BASE_URL, full_commit=True, session=None): ...\n def __contains__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __repr__(self): ...\n def __delitem__(self, name): ...\n def __getitem__(self, name): ...\n def config(self): ...\n def stats(self, name=None): ...\n def tasks(self): ...\n def uuids(self, count=None): ...\n def create(self, name): ...\n def delete(self, name): ...\n def replicate(self, source, target, **options): ...\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_server_vars", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001704.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "stats", "tests": "import unittest\n\nclass Test_stats(unittest.TestCase):\n def test_server_stats(self):\n stats = self.server.stats()\n self.assertTrue(isinstance(stats, dict))\n stats = self.server.stats('httpd/requests')\n self.assertTrue(isinstance(stats, dict))\n self.assertTrue(len(stats) == 1 and len(stats['httpd']) == 1)\n", "method_code": " def stats(self, name=None):\n \"\"\"Server statistics.\n \n :param name: name of single statistic, e.g. httpd/requests\n (None -- return all statistics)\n \"\"\"\n if not name:\n resource = self.resource('_stats')\n else:\n resource = self.resource('_stats', *name.split('/'))\n status, headers, data = resource.get_json()\n return data\n ", "context": "class Server(object):\n def stats(self, name=None): ...\n def __init__(self, url=DEFAULT_BASE_URL, full_commit=True, session=None): ...\n def __contains__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __repr__(self): ...\n def __delitem__(self, name): ...\n def __getitem__(self, name): ...\n def config(self): ...\n def version(self): ...\n def tasks(self): ...\n def uuids(self, count=None): ...\n def create(self, name): ...\n def delete(self, name): ...\n def replicate(self, source, target, **options): ...\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_server_stats", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001705.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "replicate", "tests": "import unittest\n\nclass Test_replicate(unittest.TestCase):\n def test_replicate(self):\n aname, a = self.temp_db()\n bname, b = self.temp_db()\n id, rev = a.save({'test': 'a'})\n result = self.server.replicate(aname, bname)\n self.assertEqual(result['ok'], True)\n self.assertEqual(b[id]['test'], 'a')\n doc = b[id]\n doc['test'] = 'b'\n b.update([doc])\n self.server.replicate(bname, aname)\n self.assertEqual(a[id]['test'], 'b')\n self.assertEqual(b[id]['test'], 'b')\n", "method_code": " def replicate(self, source, target, **options):\n \"\"\"Replicate changes from the source database to the target database.\n \n :param source: URL of the source database\n :param target: URL of the target database\n :param options: optional replication args, e.g. continuous=True\n \"\"\"\n data = {'source': source, 'target': target}\n data.update(options)\n status, headers, data = self.resource.post_json('_replicate', data)\n return data\n ", "context": "class Server(object):\n def replicate(self, source, target, **options): ...\n def __init__(self, url=DEFAULT_BASE_URL, full_commit=True, session=None): ...\n def __contains__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __repr__(self): ...\n def __delitem__(self, name): ...\n def __getitem__(self, name): ...\n def config(self): ...\n def version(self): ...\n def stats(self, name=None): ...\n def tasks(self): ...\n def uuids(self, count=None): ...\n def create(self, name): ...\n def delete(self, name): ...\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_replicate", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001706.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "uuids", "tests": "import unittest\n\nclass Test_uuids(unittest.TestCase):\n def test_uuids(self):\n ls = self.server.uuids()\n assert type(ls) == list\n ls = self.server.uuids(count=10)\n assert type(ls) == list and len(ls) == 10\n", "method_code": " def uuids(self, count=None):\n \"\"\"Retrieve a batch of uuids\n \n :param count: a number of uuids to fetch\n (None -- get as many as the server sends)\n :return: a list of uuids\n \"\"\"\n if count is None:\n _, _, data = self.resource.get_json('_uuids')\n else:\n _, _, data = self.resource.get_json('_uuids', count=count)\n return data['uuids']\n ", "context": "class Server(object):\n def uuids(self, count=None): ...\n def __init__(self, url=DEFAULT_BASE_URL, full_commit=True, session=None): ...\n def __contains__(self, name): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __repr__(self): ...\n def __delitem__(self, name): ...\n def __getitem__(self, name): ...\n def config(self): ...\n def version(self): ...\n def stats(self, name=None): ...\n def tasks(self): ...\n def create(self, name): ...\n def delete(self, name): ...\n def replicate(self, source, target, **options): ...\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_uuids", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001707.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "commit", "tests": "import unittest\n\nclass Test_commit(unittest.TestCase):\n def test_commit(self):\n self.assertTrue(self.db.commit()['ok'] == True)\n", "method_code": " def commit(self):\n \"\"\"If the server is configured to delay commits, or previous requests\n used the special ``X-Couch-Full-Commit: false`` header to disable\n immediate commits, this method can be used to ensure that any\n non-committed changes are committed to physical storage.\n \"\"\"\n _, _, data = self.resource.post_json('_ensure_full_commit', headers={'Content-Type': 'application/json'})\n return data\n ", "context": "class Database(object):\n def commit(self): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_commit", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001708.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "put_attachment", "tests": "import unittest\n\nclass Test_put_attachment(unittest.TestCase):\n def test_attachment_crud(self):\n doc = {'bar': 42}\n self.db['foo'] = doc\n old_rev = doc['_rev']\n self.db.put_attachment(doc, 'Foo bar', 'foo.txt', 'text/plain')\n self.assertNotEqual(old_rev, doc['_rev'])\n doc = self.db['foo']\n attachment = doc['_attachments']['foo.txt']\n self.assertEqual(len('Foo bar'), attachment['length'])\n self.assertEqual('text/plain', attachment['content_type'])\n self.assertEqual('Foo bar', self.db.get_attachment(doc, 'foo.txt').read())\n self.assertEqual('Foo bar', self.db.get_attachment('foo', 'foo.txt').read())\n old_rev = doc['_rev']\n self.db.delete_attachment(doc, 'foo.txt')\n self.assertNotEqual(old_rev, doc['_rev'])\n self.assertEqual(None, self.db['foo'].get('_attachments'))\n\n def test_empty_attachment(self):\n doc = {}\n self.db['foo'] = doc\n old_rev = doc['_rev']\n self.db.put_attachment(doc, '', 'empty.txt')\n self.assertNotEqual(old_rev, doc['_rev'])\n doc = self.db['foo']\n attachment = doc['_attachments']['empty.txt']\n self.assertEqual(0, attachment['length'])\n\n def test_attachment_from_fs(self):\n tmpdir = tempfile.mkdtemp()\n tmpfile = os.path.join(tmpdir, 'test.txt')\n f = open(tmpfile, 'w')\n f.write('Hello!')\n f.close()\n doc = {}\n self.db['foo'] = doc\n with open(tmpfile) as f:\n self.db.put_attachment(doc, f)\n doc = self.db.get('foo')\n self.assertTrue(doc['_attachments']['test.txt']['content_type'] == 'text/plain')\n shutil.rmtree(tmpdir)\n\n def test_json_attachment(self):\n doc = {}\n self.db['foo'] = doc\n self.db.put_attachment(doc, '{}', 'test.json', 'application/json')\n self.assertEqual(self.db.get_attachment(doc, 'test.json').read(), '{}')\n", "method_code": " def put_attachment(self, doc, content, filename=None, content_type=None):\n \"\"\"Create or replace an attachment.\n \n Note that the provided `doc` is required to have a ``_rev`` field. Thus,\n if the `doc` is based on a view row, the view row would need to include\n the ``_rev`` field.\n \n :param doc: the dictionary or `Document` object representing the\n document that the attachment should be added to\n :param content: the content to upload, either a file-like object or\n a string\n :param filename: the name of the attachment file; if omitted, this\n function tries to get the filename from the file-like\n object passed as the `content` argument value\n :param content_type: content type of the attachment; if omitted, the\n MIME type is guessed based on the file name\n extension\n :since: 0.4.1\n \"\"\"\n if filename is None:\n if hasattr(content, 'name'):\n filename = os.path.basename(content.name)\n else:\n raise ValueError('no filename specified for attachment')\n if content_type is None:\n content_type = ';'.join(filter(None, mimetypes.guess_type(filename)))\n resource = _doc_resource(self.resource, doc['_id'])\n status, headers, data = resource.put_json(filename, body=content, headers={'Content-Type': content_type}, rev=doc['_rev'])\n doc['_rev'] = data['rev']\n ", "context": "class Database(object):\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def commit(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_attachment_crud", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001709.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "get_attachment", "tests": "import unittest\n\nclass Test_get_attachment(unittest.TestCase):\n def test_default_attachment(self):\n doc = {}\n self.db['foo'] = doc\n self.assertTrue(self.db.get_attachment(doc, 'missing.txt') is None)\n sentinel = object()\n self.assertTrue(self.db.get_attachment(doc, 'missing.txt', sentinel) is sentinel)\n", "method_code": " def get_attachment(self, id_or_doc, filename, default=None):\n \"\"\"Return an attachment from the specified doc id and filename.\n \n :param id_or_doc: either a document ID or a dictionary or `Document`\n object representing the document that the attachment\n belongs to\n :param filename: the name of the attachment file\n :param default: default value to return when the document or attachment\n is not found\n :return: a file-like object with read and close methods, or the value\n of the `default` argument if the attachment is not found\n :since: 0.4.1\n \"\"\"\n if isinstance(id_or_doc, basestring):\n id = id_or_doc\n else:\n id = id_or_doc['_id']\n try:\n _, _, data = _doc_resource(self.resource, id).get(filename)\n return data\n except http.ResourceNotFound:\n return default\n ", "context": "class Database(object):\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def commit(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_default_attachment", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001710.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "changes", "tests": "import unittest\n\nclass Test_changes(unittest.TestCase):\n def test_changes(self):\n self.db['foo'] = {'bar': True}\n self.assertEqual(self.db.changes(since=0)['last_seq'], 1)\n first = self.db.changes(feed='continuous').next()\n self.assertEqual(first['seq'], 1)\n self.assertEqual(first['id'], 'foo')\n", "method_code": " def changes(self, **opts):\n \"\"\"Retrieve a changes feed from the database.\n \n :param opts: optional query string parameters\n :return: an iterable over change notification dicts\n \"\"\"\n if opts.get('feed') == 'continuous':\n return self._changes(**opts)\n _, _, data = self.resource.get_json('_changes', **opts)\n return data\n ", "context": "class Database(object):\n def changes(self, **opts): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def commit(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_changes", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001711.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "purge", "tests": "import unittest\n\nclass Test_purge(unittest.TestCase):\n def test_purge(self):\n doc = {'a': 'b'}\n self.db['foo'] = doc\n self.assertEqual(self.db.purge([doc])['purge_seq'], 1)\n", "method_code": " def purge(self, docs):\n \"\"\"Perform purging (complete removing) of the given documents.\n \n Uses a single HTTP request to purge all given documents. Purged\n documents do not leave any meta-data in the storage and are not\n replicated.\n \"\"\"\n content = {}\n for doc in docs:\n if isinstance(doc, dict):\n content[doc['_id']] = [doc['_rev']]\n elif hasattr(doc, 'items'):\n doc = dict(doc.items())\n content[doc['_id']] = [doc['_rev']]\n else:\n raise TypeError('expected dict, got %s' % type(doc))\n _, _, data = self.resource.post_json('_purge', body=content)\n return data\n ", "context": "class Database(object):\n def purge(self, docs): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def commit(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_purge", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001712.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "info", "tests": "import unittest\n\nclass Test_info(unittest.TestCase):\n def test_ddoc_info(self):\n self.db['_design/test'] = {'language': 'javascript', 'views': {'test': {'map': 'function(doc) { emit(doc.type, null); }'}}}\n info = self.db.info('test')\n self.assertEqual(info['view_index']['compact_running'], False)\n", "method_code": " def info(self, ddoc=None):\n \"\"\"Return information about the database or design document as a\n dictionary.\n \n Without an argument, returns database information. With an argument,\n return information for the given design document.\n \n The returned dictionary exactly corresponds to the JSON response to\n a ``GET`` request on the database or design document's info URI.\n \n :return: a dictionary of database properties\n :rtype: ``dict``\n :since: 0.4\n \"\"\"\n if ddoc is not None:\n _, _, data = self.resource('_design', ddoc, '_info').get_json()\n else:\n _, _, data = self.resource.get_json()\n self._name = data['db_name']\n return data\n ", "context": "class Database(object):\n def info(self, ddoc=None): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def commit(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_ddoc_info", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001713.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "compact", "tests": "import unittest\n\nclass Test_compact(unittest.TestCase):\n def test_view_compaction(self):\n for i in range(1, 6):\n self.db.save({'i': i})\n self.db['_design/test'] = {'language': 'javascript', 'views': {'multi_key': {'map': 'function(doc) { emit(doc.i, null); }'}}}\n self.db.view('test/multi_key')\n self.assertTrue(self.db.compact('test'))\n", "method_code": " def compact(self, ddoc=None):\n \"\"\"Compact the database or a design document's index.\n \n Without an argument, this will try to prune all old revisions from the\n database. With an argument, it will compact the index cache for all\n views in the design document specified.\n \n :return: a boolean to indicate whether the compaction was initiated\n successfully\n :rtype: `bool`\n \"\"\"\n if ddoc:\n resource = self.resource('_compact', ddoc)\n else:\n resource = self.resource('_compact')\n _, _, data = resource.post_json(headers={'Content-Type': 'application/json'})\n return data['ok']\n ", "context": "class Database(object):\n def compact(self, ddoc=None): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def commit(self): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_view_compaction", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001714.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "cleanup", "tests": "import unittest\n\nclass Test_cleanup(unittest.TestCase):\n def test_view_cleanup(self):\n for i in range(1, 6):\n self.db.save({'i': i})\n self.db['_design/test'] = {'language': 'javascript', 'views': {'multi_key': {'map': 'function(doc) { emit(doc.i, null); }'}}}\n self.db.view('test/multi_key')\n ddoc = self.db['_design/test']\n ddoc['views'] = {'ids': {'map': 'function(doc) { emit(doc._id, null); }'}}\n self.db.update([ddoc])\n self.db.view('test/ids')\n self.assertTrue(self.db.cleanup())\n", "method_code": " def cleanup(self):\n \"\"\"Clean up old design document indexes.\n \n Remove all unused index files from the database storage area.\n \n :return: a boolean to indicate successful cleanup initiation\n :rtype: `bool`\n \"\"\"\n headers = {'Content-Type': 'application/json'}\n _, _, data = self.resource('_view_cleanup').post_json(headers=headers)\n return data['ok']\n ", "context": "class Database(object):\n def cleanup(self): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def commit(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_view_cleanup", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001715.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "list", "tests": "import unittest\n\nclass Test_list(unittest.TestCase):\n def test_list(self):\n self.assertEqual(self.db.list('foo/list', 'foo/by_id')[1].read(), '1\\r\\n2\\r\\n')\n self.assertEqual(self.db.list('foo/list', 'foo/by_id', include_header='true')[1].read(), 'id\\r\\n1\\r\\n2\\r\\n')\n", "method_code": " def list(self, name, view, **options):\n \"\"\"Format a view using a 'list' function.\n \n :param name: the name of the list function in the format\n ``designdoc/listname``\n :param view: the name of the view in the format ``designdoc/viewname``\n :param options: optional query string parameters\n :return: (headers, body) tuple, where headers is a dict of headers\n returned from the list function and body is a readable\n file-like instance\n \"\"\"\n path = _path_from_name(name, '_list')\n path.extend(view.split('/', 1))\n _, headers, body = _call_viewlike(self.resource(*path), options)\n return (headers, body)\n ", "context": "class Database(object):\n def list(self, name, view, **options): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def commit(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def update_doc(self, name, docid=None, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_list", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001716.py"} {"focal_file": "couchdb/client.py", "focal_class": null, "focal_method": "update_doc", "tests": "import unittest\n\nclass Test_update_doc(unittest.TestCase):\n def test_update_doc(self):\n self.assertEqual(self.db.update_doc('foo/bar', 'existed')[1].read(), 'hello doc')\n", "method_code": " def update_doc(self, name, docid=None, **options):\n \"\"\"Calls server side update handler.\n \n :param name: the name of the update handler function in the format\n ``designdoc/updatename``.\n :param docid: optional ID of a document to pass to the update handler.\n :param options: optional query string parameters.\n :return: (headers, body) tuple, where headers is a dict of headers\n returned from the list function and body is a readable\n file-like instance\n \"\"\"\n path = _path_from_name(name, '_update')\n if docid is None:\n func = self.resource(*path).post\n else:\n path.append(docid)\n func = self.resource(*path).put\n _, headers, body = func(**options)\n return (headers, body)\n ", "context": "class Database(object):\n def update_doc(self, name, docid=None, **options): ...\n def __init__(self, url, name=None, session=None): ...\n def __repr__(self): ...\n def __contains__(self, id): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __nonzero__(self): ...\n def __delitem__(self, id): ...\n def __getitem__(self, id): ...\n def __setitem__(self, id, content): ...\n def name(self): ...\n def create(self, data): ...\n def save(self, doc, **options): ...\n def cleanup(self): ...\n def commit(self): ...\n def compact(self, ddoc=None): ...\n def copy(self, src, dest): ...\n def delete(self, doc): ...\n def get(self, id, default=None, **options): ...\n def revisions(self, id, **options): ...\n def info(self, ddoc=None): ...\n def delete_attachment(self, doc, filename): ...\n def get_attachment(self, id_or_doc, filename, default=None): ...\n def put_attachment(self, doc, content, filename=None, content_type=None): ...\n def query(self, map_fun, reduce_fun=None, language='javascript', wrapper=None, **options): ...\n def update(self, documents, **options): ...\n def purge(self, docs): ...\n def view(self, name, wrapper=None, **options): ...\n def iterview(self, name, batch, wrapper=None, **options): ...\n def show(self, name, docid=None, **options): ...\n def list(self, name, view, **options): ...\n def _changes(self, **opts): ...\n def changes(self, **opts): ...\n\n self._name = name\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_update_doc", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001717.py"} {"focal_file": "couchdb/design.py", "focal_class": "couchdb.design.ViewDefinition", "focal_method": "sync_many", "tests": "import unittest\n\nclass Test_couchdb_design_ViewDefinition_sync_many(unittest.TestCase):\n def test_sync_many(self):\n \"\"\"see issue 218\"\"\"\n func = 'function(doc) { emit(doc._id, doc._rev); }'\n first_view = design.ViewDefinition('design_doc', 'view_one', func)\n second_view = design.ViewDefinition('design_doc_two', 'view_one', func)\n third_view = design.ViewDefinition('design_doc', 'view_two', func)\n _, db = self.temp_db()\n results = design.ViewDefinition.sync_many(db, (first_view, second_view, third_view))\n self.assertEqual(len(results), 2, 'There should only be two design documents')\n", "method_code": " def sync_many(db, views, remove_missing=False, callback=None):\n \"\"\"Ensure that the views stored in the database that correspond to a\n given list of `ViewDefinition` instances match the code defined in\n those instances.\n \n This function might update more than one design document. This is done\n using the CouchDB bulk update feature to ensure atomicity of the\n operation.\n \n :param db: the `Database` instance\n :param views: a sequence of `ViewDefinition` instances\n :param remove_missing: whether views found in a design document that\n are not found in the list of `ViewDefinition`\n instances should be removed\n :param callback: a callback function that is invoked when a design\n document gets updated; the callback gets passed the\n design document as only parameter, before that doc\n has actually been saved back to the database\n \"\"\"\n docs = []\n views = sorted(views, key=attrgetter('design'))\n for design, views in groupby(views, key=attrgetter('design')):\n doc_id = '_design/%s' % design\n doc = db.get(doc_id, {'_id': doc_id})\n orig_doc = deepcopy(doc)\n languages = set()\n missing = list(doc.get('views', {}).keys())\n for view in views:\n funcs = {'map': view.map_fun}\n if view.reduce_fun:\n funcs['reduce'] = view.reduce_fun\n if view.options:\n funcs['options'] = view.options\n doc.setdefault('views', {})[view.name] = funcs\n languages.add(view.language)\n if view.name in missing:\n missing.remove(view.name)\n if remove_missing and missing:\n for name in missing:\n del doc['views'][name]\n elif missing and 'language' in doc:\n languages.add(doc['language'])\n if len(languages) > 1:\n raise ValueError('Found different language views in one design document (%r)', list(languages))\n doc['language'] = list(languages)[0]\n if doc != orig_doc:\n if callback is not None:\n callback(doc)\n docs.append(doc)\n return db.update(docs)\n ", "context": "class ViewDefinition(object):\n @staticmethod\n def sync_many(db, views, remove_missing=False, callback=None): ...\n def __init__(self, design, name, map_fun, reduce_fun=None, language='javascript', wrapper=None, options=None, **defaults): ...\n def __call__(self, db, **options): ...\n def __repr__(self): ...\n def get_doc(self, db): ...\n def sync(self, db): ...\n\n self.design = design\n self.name = name\n self.map_fun = dedent(map_fun.lstrip('\\n'))\n self.reduce_fun = reduce_fun\n self.language = language\n self.wrapper = wrapper\n self.options = options\n self.defaults = defaults\n", "repository": "ajmirsky/couchdb-python", "test_name": "test_sync_many", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001718.py"} {"focal_file": "apiclient/channel.py", "focal_class": null, "focal_method": "new_webhook_channel", "tests": "import unittest\n\nclass Test_new_webhook_channel(unittest.TestCase):\n def test_new_webhook_channel(self):\n ch = channel.new_webhook_channel('http://example.com/callback')\n self.assertEqual(0, ch.expiration)\n self.assertEqual('http://example.com/callback', ch.address)\n self.assertEqual(None, ch.params)\n ch = channel.new_webhook_channel('http://example.com/callback', expiration=datetime.datetime(1965, 1, 1))\n self.assertEqual(0, ch.expiration)\n ch = channel.new_webhook_channel('http://example.com/callback', expiration=datetime.datetime(1970, 1, 1, second=5))\n self.assertEqual(5000, ch.expiration)\n self.assertEqual('http://example.com/callback', ch.address)\n self.assertEqual(None, ch.params)\n ch = channel.new_webhook_channel('http://example.com/callback', expiration=datetime.datetime(1970, 1, 1, second=5, microsecond=1000), params={'some': 'stuff'})\n self.assertEqual(5001, ch.expiration)\n self.assertEqual('http://example.com/callback', ch.address)\n self.assertEqual({'some': 'stuff'}, ch.params)\n", "method_code": "def new_webhook_channel(url, token=None, expiration=None, params=None):\n \"\"\"Create a new webhook Channel.\n\n Args:\n url: str, URL to post notifications to.\n token: str, An arbitrary string associated with the channel that\n is delivered to the target address with each notification delivered\n over this channel.\n expiration: datetime.datetime, A time in the future when the channel\n should expire. Can also be None if the subscription should use the\n default expiration. Note that different services may have different\n limits on how long a subscription lasts. Check the response from the\n watch() method to see the value the service has set for an expiration\n time.\n params: dict, Extra parameters to pass on channel creation. Currently\n not used for webhook channels.\n \"\"\"\n expiration_ms = 0\n if expiration:\n delta = expiration - EPOCH\n expiration_ms = delta.microseconds / 1000 + (delta.seconds + delta.days * 24 * 3600) * 1000\n if expiration_ms < 0:\n expiration_ms = 0\n return Channel('web_hook', str(uuid.uuid4()), token, url, expiration=expiration_ms, params=params)", "context": "@util.positional(2)\ndef new_webhook_channel(url, token=None, expiration=None, params=None): ...\ndef _upper_header_keys(headers): ...\ndef notification_from_headers(channel, headers): ...\ndef new_webhook_channel(url, token=None, expiration=None, params=None): ...\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_new_webhook_channel", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001719.py"} {"focal_file": "apiclient/channel.py", "focal_class": "apiclient.channel.Channel", "focal_method": "notification_from_headers", "tests": "import unittest\n\nclass Test_apiclient_channel_Channel_notification_from_headers(unittest.TestCase):\n def test_notification_from_headers(self):\n headers = {'X-GoOG-CHANNEL-ID': 'myid', 'X-Goog-MESSAGE-NUMBER': '1', 'X-Goog-rESOURCE-STATE': 'sync', 'X-Goog-reSOURCE-URI': 'http://example.com/', 'X-Goog-resOURCE-ID': 'http://example.com/resource_1'}\n ch = channel.Channel('web_hook', 'myid', 'mytoken', 'http://example.org/callback', expiration=0, params={'extra': 'info'}, resource_id='the_resource_id', resource_uri='http://example.com/resource_1')\n n = channel.notification_from_headers(ch, headers)\n self.assertEqual('http://example.com/resource_1', n.resource_id)\n self.assertEqual('http://example.com/', n.resource_uri)\n self.assertEqual('sync', n.state)\n self.assertEqual(1, n.message_number)\n ch.id = 'different_id'\n try:\n n = channel.notification_from_headers(ch, headers)\n self.fail('Should have raised exception')\n except errors.InvalidNotificationError:\n pass\n ch.id = 'myid'\n", "method_code": "def notification_from_headers(channel, headers):\n \"\"\"Parse a notification from the webhook request headers, validate\n the notification, and return a Notification object.\n\n Args:\n channel: Channel, The channel that the notification is associated with.\n headers: dict, A dictionary like object that contains the request headers\n from the webhook HTTP request.\n\n Returns:\n A Notification object.\n\n Raises:\n errors.InvalidNotificationError if the notification is invalid.\n ValueError if the X-GOOG-MESSAGE-NUMBER can't be converted to an int.\n \"\"\"\n headers = _upper_header_keys(headers)\n channel_id = headers[X_GOOG_CHANNEL_ID]\n if channel.id != channel_id:\n raise errors.InvalidNotificationError('Channel id mismatch: %s != %s' % (channel.id, channel_id))\n else:\n message_number = int(headers[X_GOOG_MESSAGE_NUMBER])\n state = headers[X_GOOG_RESOURCE_STATE]\n resource_uri = headers[X_GOOG_RESOURCE_URI]\n resource_id = headers[X_GOOG_RESOURCE_ID]\n return Notification(message_number, state, resource_uri, resource_id)", "context": "def notification_from_headers(channel, headers): ...\ndef _upper_header_keys(headers): ...\ndef notification_from_headers(channel, headers): ...\ndef new_webhook_channel(url, token=None, expiration=None, params=None): ...\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_notification_from_headers", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001720.py"} {"focal_file": "apiclient/model.py", "focal_class": null, "focal_method": "makepatch", "tests": "import unittest\n\nclass Test_makepatch(unittest.TestCase):\n def test_patch(self):\n for msg, orig, mod, expected_patch in TEST_CASES:\n self.assertEqual(expected_patch, makepatch(orig, mod), msg=msg)\n", "method_code": "def makepatch(original, modified):\n \"\"\"Create a patch object.\n\n Some methods support PATCH, an efficient way to send updates to a resource.\n This method allows the easy construction of patch bodies by looking at the\n differences between a resource before and after it was modified.\n\n Args:\n original: object, the original deserialized resource\n modified: object, the modified deserialized resource\n Returns:\n An object that contains only the changes from original to modified, in a\n form suitable to pass to a PATCH method.\n\n Example usage:\n item = service.activities().get(postid=postid, userid=userid).execute()\n original = copy.deepcopy(item)\n item['object']['content'] = 'This is updated.'\n service.activities.patch(postid=postid, userid=userid,\n body=makepatch(original, item)).execute()\n \"\"\"\n patch = {}\n for key, original_value in original.iteritems():\n modified_value = modified.get(key, None)\n if modified_value is None:\n patch[key] = None\n elif original_value != modified_value:\n if type(original_value) == type({}):\n patch[key] = makepatch(original_value, modified_value)\n else:\n patch[key] = modified_value\n else:\n pass\n for key in modified:\n if key not in original:\n patch[key] = modified[key]\n return patch", "context": "def makepatch(original, modified): ...\ndef _abstract(): ...\ndef makepatch(original, modified): ...\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_patch", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001721.py"} {"focal_file": "oauth2client/client.py", "focal_class": null, "focal_method": "_refresh", "tests": "import unittest\n\nclass Test_refresh(unittest.TestCase):\n def test_good_refresh(self):\n m = mox.Mox()\n httplib2_response = m.CreateMock(object)\n httplib2_response.status = 200\n httplib2_request = m.CreateMock(object)\n httplib2_request.__call__('http://metadata.google.internal/0.1/meta-data/service-accounts/default/acquire?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb').AndReturn((httplib2_response, '{\"accessToken\": \"this-is-a-token\"}'))\n m.ReplayAll()\n c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b'])\n c._refresh(httplib2_request)\n self.assertEquals('this-is-a-token', c.access_token)\n m.UnsetStubs()\n m.VerifyAll()\n\n def test_fail_refresh(self):\n m = mox.Mox()\n httplib2_response = m.CreateMock(object)\n httplib2_response.status = 400\n httplib2_request = m.CreateMock(object)\n httplib2_request.__call__('http://metadata.google.internal/0.1/meta-data/service-accounts/default/acquire?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb').AndReturn((httplib2_response, '{\"accessToken\": \"this-is-a-token\"}'))\n m.ReplayAll()\n c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b'])\n try:\n c._refresh(httplib2_request)\n self.fail('Should have raised exception on 400')\n except AccessTokenRefreshError:\n pass\n m.UnsetStubs()\n m.VerifyAll()\n", "method_code": " def _refresh(self, http_request):\n \"\"\"Refreshes the access_token.\n \n This method first checks by reading the Storage object if available.\n If a refresh is still needed, it holds the Storage lock until the\n refresh is completed.\n \n Args:\n http_request: callable, a callable that matches the method signature of\n httplib2.Http.request, used to make the refresh request.\n \n Raises:\n AccessTokenRefreshError: When the refresh fails.\n \"\"\"\n if not self.store:\n self._do_refresh_request(http_request)\n else:\n self.store.acquire_lock()\n try:\n new_cred = self.store.locked_get()\n if new_cred and (not new_cred.invalid) and (new_cred.access_token != self.access_token):\n logger.info('Updated access_token read from Storage')\n self._updateFromCredential(new_cred)\n else:\n self._do_refresh_request(http_request)\n finally:\n self.store.release_lock()\n ", "context": "class OAuth2Credentials(Credentials):\n def _refresh(self, http_request): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def to_json(self): ...\n def from_json(cls, s): ...\n def access_token_expired(self): ...\n def set_store(self, store): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _do_refresh_request(self, http_request): ...\n def _revoke(self, http_request): ...\n def _do_revoke(self, http_request, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.invalid = False\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_good_refresh", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001722.py"} {"focal_file": "oauth2client/client.py", "focal_class": null, "focal_method": "to_json", "tests": "import unittest\n\nclass Test_to_json(unittest.TestCase):\n def test_to_from_json(self):\n c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b'])\n json = c.to_json()\n c2 = Credentials.new_from_json(json)\n self.assertEqual(c.access_token, c2.access_token)\n", "method_code": " def to_json(self):\n \"\"\"Creating a JSON representation of an instance of Credentials.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)\n ", "context": "class Credentials(object):\n def to_json(self): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip): ...\n def new_from_json(cls, s): ...\n def from_json(cls, s): ...\n\n NON_SERIALIZED_MEMBERS = ['store']\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_to_from_json", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001723.py"} {"focal_file": "oauth2client/client.py", "focal_class": null, "focal_method": "verify_id_token", "tests": "import unittest\n\nclass Test_verify_id_token(unittest.TestCase):\n def test_verify_id_token_with_certs_uri(self):\n jwt = self._create_signed_jwt()\n http = HttpMockSequence([({'status': '200'}, datafile('certs.json'))])\n contents = verify_id_token(jwt, 'some_audience_address@testing.gserviceaccount.com', http=http)\n self.assertEqual('billy bob', contents['user'])\n self.assertEqual('data', contents['metadata']['meta'])\n", "method_code": "def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATON_CERTS):\n \"\"\"Verifies a signed JWT id_token.\n\n This function requires PyOpenSSL and because of that it does not work on\n App Engine.\n\n Args:\n id_token: string, A Signed JWT.\n audience: string, The audience 'aud' that the token should be for.\n http: httplib2.Http, instance to use to make the HTTP request. Callers\n should supply an instance that has caching enabled.\n cert_uri: string, URI of the certificates in JSON format to\n verify the JWT against.\n\n Returns:\n The deserialized JSON in the JWT.\n\n Raises:\n oauth2client.crypt.AppIdentityError if the JWT fails to verify.\n \"\"\"\n if http is None:\n http = _cached_http\n resp, content = http.request(cert_uri)\n if resp.status == 200:\n certs = simplejson.loads(content)\n return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)\n else:\n raise VerifyJwtTokenError('Status code: %d' % resp.status)", "context": "@util.positional(2)\ndef verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATON_CERTS): ...\ndef _abstract(): ...\ndef clean_headers(headers): ...\ndef _update_query_params(uri, params): ...\ndef _urlsafe_b64decode(b64string): ...\ndef _extract_id_token(id_token): ...\ndef _parse_exchange_token_response(content): ...\ndef credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=GOOGLE_TOKEN_URI, auth_uri=GOOGLE_AUTH_URI, revoke_uri=GOOGLE_REVOKE_URI): ...\ndef credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None): ...\ndef flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None): ...\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_verify_id_token_with_certs_uri", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001724.py"} {"focal_file": "oauth2client/client.py", "focal_class": "SignedJwtAssertionCredentials", "focal_method": "authorize", "tests": "import unittest\n\nclass Test_SignedJwtAssertionCredentials_authorize(unittest.TestCase):\n def test_credentials_good(self):\n private_key = datafile('privatekey.%s' % self.format)\n credentials = SignedJwtAssertionCredentials('some_account@example.com', private_key, scope='read+write', sub='joe@example.org')\n http = HttpMockSequence([({'status': '200'}, '{\"access_token\":\"1/3w\",\"expires_in\":3600}'), ({'status': '200'}, 'echo_request_headers')])\n http = credentials.authorize(http)\n resp, content = http.request('http://example.org')\n self.assertEqual('Bearer 1/3w', content['Authorization'])\n", "method_code": " def authorize(self, http):\n \"\"\"Take an httplib2.Http instance (or equivalent) and authorizes it.\n \n Authorizes it for the set of credentials, usually by replacing\n http.request() with a method that adds in the appropriate headers and then\n delegates to the original Http.request() method.\n \n Args:\n http: httplib2.Http, an http object to be used to make the refresh\n request.\n \"\"\"\n _abstract()\n ", "context": "class Credentials(object):\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip): ...\n def to_json(self): ...\n def new_from_json(cls, s): ...\n def from_json(cls, s): ...\n\n NON_SERIALIZED_MEMBERS = ['store']\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_credentials_good", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001725.py"} {"focal_file": "oauth2client/client.py", "focal_class": "SignedJwtAssertionCredentials", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_SignedJwtAssertionCredentials_to_json(unittest.TestCase):\n def test_credentials_to_from_json(self):\n private_key = datafile('privatekey.%s' % self.format)\n credentials = SignedJwtAssertionCredentials('some_account@example.com', private_key, scope='read+write', sub='joe@example.org')\n json = credentials.to_json()\n restored = Credentials.new_from_json(json)\n self.assertEqual(credentials.private_key, restored.private_key)\n self.assertEqual(credentials.private_key_password, restored.private_key_password)\n self.assertEqual(credentials.kwargs, restored.kwargs)\n", "method_code": " def to_json(self):\n \"\"\"Creating a JSON representation of an instance of Credentials.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)\n ", "context": "class Credentials(object):\n def to_json(self): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip): ...\n def new_from_json(cls, s): ...\n def from_json(cls, s): ...\n\n NON_SERIALIZED_MEMBERS = ['store']\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_credentials_to_from_json", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001726.py"} {"focal_file": "oauth2client/client.py", "focal_class": "SignedJwtAssertionCredentials", "focal_method": "set_store", "tests": "import unittest\n\nclass Test_SignedJwtAssertionCredentials_set_store(unittest.TestCase):\n def test_credentials_refresh_with_storage(self):\n private_key = datafile('privatekey.%s' % self.format)\n credentials = SignedJwtAssertionCredentials('some_account@example.com', private_key, scope='read+write', sub='joe@example.org')\n filehandle, filename = tempfile.mkstemp()\n os.close(filehandle)\n store = Storage(filename)\n store.put(credentials)\n credentials.set_store(store)\n content = self._credentials_refresh(credentials)\n self.assertEqual('Bearer 3/3w', content['Authorization'])\n os.unlink(filename)\n", "method_code": " def set_store(self, store):\n \"\"\"Set the Storage for the credential.\n \n Args:\n store: Storage, an implementation of Stroage object.\n This is needed to store the latest access_token if it\n has expired and been refreshed. This implementation uses\n locking to check for updates before updating the\n access_token.\n \"\"\"\n self.store = store\n ", "context": "class OAuth2Credentials(Credentials):\n def set_store(self, store): ...\n def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri=None, id_token=None, token_response=None): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def to_json(self): ...\n def from_json(cls, s): ...\n def access_token_expired(self): ...\n def _updateFromCredential(self, other): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def _generate_refresh_request_body(self): ...\n def _generate_refresh_request_headers(self): ...\n def _refresh(self, http_request): ...\n def _do_refresh_request(self, http_request): ...\n def _revoke(self, http_request): ...\n def _do_revoke(self, http_request, token): ...\n\n self.access_token = access_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.refresh_token = refresh_token\n self.store = None\n self.token_expiry = token_expiry\n self.token_uri = token_uri\n self.user_agent = user_agent\n self.revoke_uri = revoke_uri\n self.id_token = id_token\n self.token_response = token_response\n self.invalid = False\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_credentials_refresh_with_storage", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001727.py"} {"focal_file": "oauth2client/client.py", "focal_class": "OAuth2Credentials", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_OAuth2Credentials_to_json(unittest.TestCase):\n def test_json_credentials_storage(self):\n access_token = 'foo'\n client_id = 'some_client_id'\n client_secret = 'cOuDdkfjxxnv+'\n refresh_token = '1/0/a.df219fjls0'\n token_expiry = datetime.datetime.utcnow()\n user_agent = 'refresh_checker/1.0'\n credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, GOOGLE_TOKEN_URI, user_agent)\n m = mox.Mox()\n m.StubOutWithMock(keyring, 'get_password')\n m.StubOutWithMock(keyring, 'set_password')\n keyring.get_password('my_unit_test', 'me').AndReturn(None)\n keyring.set_password('my_unit_test', 'me', credentials.to_json())\n keyring.get_password('my_unit_test', 'me').AndReturn(credentials.to_json())\n m.ReplayAll()\n s = Storage('my_unit_test', 'me')\n self.assertEquals(None, s.get())\n s.put(credentials)\n restored = s.get()\n self.assertEqual('foo', restored.access_token)\n self.assertEqual('some_client_id', restored.client_id)\n m.UnsetStubs()\n m.VerifyAll()\n", "method_code": " def to_json(self):\n \"\"\"Creating a JSON representation of an instance of Credentials.\n \n Returns:\n string, a JSON representation of this instance, suitable to pass to\n from_json().\n \"\"\"\n return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)\n ", "context": "class Credentials(object):\n def to_json(self): ...\n def authorize(self, http): ...\n def refresh(self, http): ...\n def revoke(self, http): ...\n def apply(self, headers): ...\n def _to_json(self, strip): ...\n def new_from_json(cls, s): ...\n def from_json(cls, s): ...\n\n NON_SERIALIZED_MEMBERS = ['store']\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_json_credentials_storage", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001728.py"} {"focal_file": "apiclient/model.py", "focal_class": null, "focal_method": "response", "tests": "import unittest\n\nclass Test_response(unittest.TestCase):\n def test_good_response(self):\n resp = httplib2.Response({'status': '200'})\n resp.reason = 'OK'\n content = 'data'\n content = self.model.response(resp, content)\n self.assertEqual(content, MockProtocolBuffer('data'))\n\n def test_no_content_response(self):\n resp = httplib2.Response({'status': '204'})\n resp.reason = 'No Content'\n content = ''\n content = self.model.response(resp, content)\n self.assertEqual(content, MockProtocolBuffer())\n", "method_code": " def response(self, resp, content):\n \"\"\"Convert the response wire format into a Python object.\n \n Args:\n resp: httplib2.Response, the HTTP response headers and status\n content: string, the body of the HTTP response\n \n Returns:\n The body de-serialized as a Python object.\n \n Raises:\n apiclient.errors.HttpError if a non 2xx response is received.\n \"\"\"\n _abstract()\n ", "context": "class Model(object):\n def response(self, resp, content): ...\n def request(self, headers, path_params, query_params, body_value): ...\n", "repository": "ValentineClays/google-api-python-client", "test_name": "test_good_response", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001729.py"} {"focal_file": "yowsup/layers/auth/keystream.py", "focal_class": null, "focal_method": "generateKeys", "tests": "import unittest\n\nclass Test_generateKeys(unittest.TestCase):\n def test_generateKeys(self):\n keys = KeyStream.generateKeys(self.password, self.salt)\n self.assertEqual(keys, self.keysTarget)\n", "method_code": " def generateKeys(password, nonce):\n resultBytes = []\n for i in range(1, 5):\n currNonce = nonce + bytearray([i])\n resultBytes.append(KeyStream.pbkdf2(password, currNonce, 2, 20))\n return resultBytes\n ", "context": "class KeyStream():\n @staticmethod\n def generateKeys(password, nonce): ...\n def __init__(self, key, macKey): ...\n def computeMac(self, bytes_buffer, int_offset, int_length): ...\n def decodeMessage(self, bufdata, macOffset, offset, length): ...\n def encodeMessage(self, buf, macOffset, offset, length): ...\n def pbkdf2(password, salt, itercount, keylen, hashfn=hashlib.sha1): ...\n\n self.key = key if sys.version_info < (3, 0) else bytes(key)\n self.rc4 = RC4(self.key, 768)\n self.macKey = str(macKey) if sys.version_info < (3, 0) else bytes(macKey)\n self.seq = 0\n", "repository": "Lijo050/yowsup-goibibo", "test_name": "test_generateKeys", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001730.py"} {"focal_file": "yowsup/layers/auth/keystream.py", "focal_class": null, "focal_method": "pbkdf2", "tests": "import unittest\n\nclass Test_pbkdf2(unittest.TestCase):\n def test_pbkdf2(self):\n result = KeyStream.pbkdf2(self.password, self.salt, 2, 20)\n result = bytearray(result)\n self.assertEqual(result, self.pbkdbf2_res)\n", "method_code": " def pbkdf2(password, salt, itercount, keylen, hashfn=hashlib.sha1):\n \n def pbkdf2_F(h, salt, itercount, blocknum):\n \n def prf(h, data):\n hm = h.copy()\n try:\n hm.update(bytearray(data))\n except TypeError:\n hm.update(bytes(data))\n d = hm.digest()\n return bytearray(d)\n U = prf(h, salt + pack('>i', blocknum))\n T = U\n for i in range(2, itercount + 1):\n U = prf(h, U)\n T = starmap(xor, zip(T, U))\n return T\n digest_size = hashfn().digest_size\n l = int(keylen / digest_size)\n if keylen % digest_size != 0:\n l += 1\n h = hmac.new(bytes(password), None, hashfn)\n T = bytearray()\n for i in range(1, l + 1):\n tmp = pbkdf2_F(h, salt, itercount, i)\n T.extend(tmp)\n return T[0:keylen]\n ", "context": "class KeyStream():\n @staticmethod\n def pbkdf2(password, salt, itercount, keylen, hashfn=hashlib.sha1): ...\n def __init__(self, key, macKey): ...\n def computeMac(self, bytes_buffer, int_offset, int_length): ...\n def decodeMessage(self, bufdata, macOffset, offset, length): ...\n def encodeMessage(self, buf, macOffset, offset, length): ...\n def generateKeys(password, nonce): ...\n\n self.key = key if sys.version_info < (3, 0) else bytes(key)\n self.rc4 = RC4(self.key, 768)\n self.macKey = str(macKey) if sys.version_info < (3, 0) else bytes(macKey)\n self.seq = 0\n", "repository": "Lijo050/yowsup-goibibo", "test_name": "test_pbkdf2", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001731.py"} {"focal_file": "yowsup/layers/auth/keystream.py", "focal_class": "KeyStream", "focal_method": "computeMac", "tests": "import unittest\n\nclass Test_KeyStream_computeMac(unittest.TestCase):\n def test_computemac(self):\n keys = self.keysTarget\n kstream = KeyStream(keys[2], keys[3])\n res = kstream.computeMac(self.inputMessage, 4, len(self.inputMessage) - 4)\n self.assertEqual(res, self.inputMessageComputedMac)\n", "method_code": " def computeMac(self, bytes_buffer, int_offset, int_length):\n mac = hmac.new(self.macKey, None, hashlib.sha1)\n updateData = bytes_buffer[int_offset:] + bytearray([self.seq >> 24, (self.seq >> 16) % 256, (self.seq >> 8) % 256, self.seq % 256])\n try:\n mac.update(updateData)\n except TypeError:\n mac.update(bytes(updateData))\n self.seq += 1\n return bytearray(mac.digest())\n ", "context": "class KeyStream():\n def computeMac(self, bytes_buffer, int_offset, int_length): ...\n def __init__(self, key, macKey): ...\n def decodeMessage(self, bufdata, macOffset, offset, length): ...\n def encodeMessage(self, buf, macOffset, offset, length): ...\n def generateKeys(password, nonce): ...\n def pbkdf2(password, salt, itercount, keylen, hashfn=hashlib.sha1): ...\n\n self.key = key if sys.version_info < (3, 0) else bytes(key)\n self.rc4 = RC4(self.key, 768)\n self.macKey = str(macKey) if sys.version_info < (3, 0) else bytes(macKey)\n self.seq = 0\n", "repository": "Lijo050/yowsup-goibibo", "test_name": "test_computemac", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001732.py"} {"focal_file": "yowsup/layers/auth/keystream.py", "focal_class": "KeyStream", "focal_method": "encodeMessage", "tests": "import unittest\n\nclass Test_KeyStream_encodeMessage(unittest.TestCase):\n def test_encodeMessage(self):\n keys = self.keysTarget\n kstream = KeyStream(keys[2], keys[3])\n encoded = kstream.encodeMessage(self.inputMessage, 0, 4, len(self.inputMessage) - 4)\n", "method_code": " def encodeMessage(self, buf, macOffset, offset, length):\n self.rc4.cipher(buf, offset, length)\n mac = self.computeMac(buf, offset, length)\n output = buf[0:macOffset] + mac[0:4] + buf[macOffset + 4:]\n return output\n ", "context": "class KeyStream():\n def encodeMessage(self, buf, macOffset, offset, length): ...\n def __init__(self, key, macKey): ...\n def computeMac(self, bytes_buffer, int_offset, int_length): ...\n def decodeMessage(self, bufdata, macOffset, offset, length): ...\n def generateKeys(password, nonce): ...\n def pbkdf2(password, salt, itercount, keylen, hashfn=hashlib.sha1): ...\n\n self.key = key if sys.version_info < (3, 0) else bytes(key)\n self.rc4 = RC4(self.key, 768)\n self.macKey = str(macKey) if sys.version_info < (3, 0) else bytes(macKey)\n self.seq = 0\n", "repository": "Lijo050/yowsup-goibibo", "test_name": "test_encodeMessage", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001733.py"} {"focal_file": "yowsup/layers/coder/tokendictionary.py", "focal_class": null, "focal_method": "getToken", "tests": "import unittest\n\nclass Test_getToken(unittest.TestCase):\n def test_getToken(self):\n self.assertEqual(self.tokenDictionary.getToken(74), 'iq')\n\n def test_getSecondaryToken(self):\n self.assertEqual(self.tokenDictionary.getToken(238), 'wmv')\n\n def test_getSecondaryTokenExplicit(self):\n self.assertEqual(self.tokenDictionary.getToken(1, True), 'wmv')\n", "method_code": " def getToken(self, index, secondary=False):\n targetDict = self.dictionary\n if secondary:\n targetDict = self.secondaryDictionary\n elif index > 236 and index < 236 + len(self.secondaryDictionary):\n targetDict = self.secondaryDictionary\n index = index - 237\n if index < 0 or index > len(targetDict) - 1:\n return None\n return targetDict[index]\n ", "context": "class TokenDictionary():\n def getToken(self, index, secondary=False): ...\n def __init__(self): ...\n def getIndex(self, token): ...\n\n self.dictionary = ['', '', '', 'account', 'ack', 'action', 'active', 'add', 'after', 'all', 'allow', 'apple', 'auth', 'author', 'available', 'bad-protocol', 'bad-request', 'before', 'body', 'broadcast', 'cancel', 'category', 'challenge', 'chat', 'clean', 'code', 'composing', 'config', 'contacts', 'count', 'create', 'creation', 'debug', 'default', 'delete', 'delivery', 'delta', 'deny', 'digest', 'dirty', 'duplicate', 'elapsed', 'enable', 'encoding', 'error', 'event', 'expiration', 'expired', 'fail', 'failure', 'false', 'favorites', 'feature', 'features', 'feature-not-implemented', 'field', 'first', 'free', 'from', 'g.us', 'get', 'google', 'group', 'groups', 'groups_v2', 'http://etherx.jabber.org/streams', 'http://jabber.org/protocol/chatstates', 'ib', 'id', 'image', 'img', 'index', 'internal-server-error', 'ip', 'iq', 'item-not-found', 'item', 'jabber:iq:last', 'jabber:iq:privacy', 'jabber:x:event', 'jid', 'kind', 'last', 'leave', 'list', 'max', 'mechanism', 'media', 'message_acks', 'message', 'method', 'microsoft', 'missing', 'modify', 'mute', 'name', 'nokia', 'none', 'not-acceptable', 'not-allowed', 'not-authorized', 'notification', 'notify', 'off', 'offline', 'order', 'owner', 'owning', 'p_o', 'p_t', 'paid', 'participant', 'participants', 'participating', 'paused', 'picture', 'pin', 'ping', 'platform', 'port', 'presence', 'preview', 'probe', 'prop', 'props', 'query', 'raw', 'read', 'readreceipts', 'reason', 'receipt', 'relay', 'remote-server-timeout', 'remove', 'request', 'required', 'resource-constraint', 'resource', 'response', 'result', 'retry', 'rim', 's_o', 's_t', 's.us', 's.whatsapp.net', 'seconds', 'server-error', 'server', 'service-unavailable', 'set', 'show', 'silent', 'stat', 'status', 'stream:error', 'stream:features', 'subject', 'subscribe', 'success', 'sync', 't', 'text', 'timeout', 'timestamp', 'to', 'true', 'type', 'unavailable', 'unsubscribe', 'uri', 'url', 'urn:ietf:params:xml:ns:xmpp-sasl', 'urn:ietf:params:xml:ns:xmpp-stanzas', 'urn:ietf:params:xml:ns:xmpp-streams', 'urn:xmpp:ping', 'urn:xmpp:whatsapp:account', 'urn:xmpp:whatsapp:dirty', 'urn:xmpp:whatsapp:mms', 'urn:xmpp:whatsapp:push', 'urn:xmpp:whatsapp', 'user', 'user-not-found', 'value', 'version', 'w:g', 'w:p:r', 'w:p', 'w:profile:picture', 'w', 'wait', 'WAUTH-2', 'xmlns:stream', 'xmlns', '1', 'chatstate', 'crypto', 'phash', 'enc', 'class', 'off_cnt', 'w:g2', 'promote', 'demote', 'creator', 'Bell.caf', 'Boing.caf', 'Glass.caf', 'Harp.caf', 'TimePassing.caf', 'Tri-tone.caf', 'Xylophone.caf', 'background', 'backoff', 'chunked', 'context', 'full', 'in', 'interactive', 'out', 'registration', 'sid', 'urn:xmpp:whatsapp:sync', 'flt', 's16', 'u8', 'adpcm', 'amrnb', 'amrwb', 'mp3', 'pcm', 'qcelp', 'wma', 'h263', 'h264', 'jpeg']\n self.secondaryDictionary = ['mpeg4', 'wmv', 'audio/3gpp', 'audio/aac', 'audio/amr', 'audio/mp4', 'audio/mpeg', 'audio/ogg', 'audio/qcelp', 'audio/wav', 'audio/webm', 'audio/x-caf', 'audio/x-ms-wma', 'image/gif', 'image/jpeg', 'image/png', 'video/3gpp', 'video/avi', 'video/mp4', 'video/mpeg', 'video/quicktime', 'video/x-flv', 'video/x-ms-asf', '302', '400', '401', '402', '403', '404', '405', '406', '407', '409', '410', '500', '501', '503', '504', 'abitrate', 'acodec', 'app_uptime', 'asampfmt', 'asampfreq', 'audio', 'clear', 'conflict', 'conn_no_nna', 'cost', 'currency', 'duration', 'extend', 'file', 'fps', 'g_notify', 'g_sound', 'gcm', 'gone', 'google_play', 'hash', 'height', 'invalid', 'jid-malformed', 'latitude', 'lc', 'lg', 'live', 'location', 'log', 'longitude', 'max_groups', 'max_participants', 'max_subject', 'mimetype', 'mode', 'napi_version', 'normalize', 'orighash', 'origin', 'passive', 'password', 'played', 'policy-violation', 'pop_mean_time', 'pop_plus_minus', 'price', 'pricing', 'redeem', 'Replaced by new connection', 'resume', 'signature', 'size', 'sound', 'source', 'system-shutdown', 'username', 'vbitrate', 'vcard', 'vcodec', 'video', 'width', 'xml-not-well-formed', 'checkmarks', 'image_max_edge', 'image_max_kbytes', 'image_quality', 'ka', 'ka_grow', 'ka_shrink', 'newmedia', 'library', 'caption', 'forward', 'c0', 'c1', 'c2', 'c3', 'clock_skew', 'cts', 'k0', 'k1', 'login_rtt', 'm_id', 'nna_msg_rtt', 'nna_no_off_count', 'nna_offline_ratio', 'nna_push_rtt', 'no_nna_con_count', 'off_msg_rtt', 'on_msg_rtt', 'stat_name', 'sts', 'suspect_conn', 'lists', 'self', 'qr', 'web', 'w:b', 'recipient', 'w:stats', 'forbidden', 'aurora.m4r', 'bamboo.m4r', 'chord.m4r', 'circles.m4r', 'complete.m4r', 'hello.m4r', 'input.m4r', 'keys.m4r', 'note.m4r', 'popcorn.m4r', 'pulse.m4r', 'synth.m4r', 'filehash', 'max_list_recipients', 'en-AU', 'en-GB', 'es-MX', 'pt-PT', 'zh-Hans', 'zh-Hant', 'relayelection', 'relaylatency', 'interruption', 'Apex.m4r', 'Beacon.m4r', 'Bulletin.m4r', 'By The Seaside.m4r', 'Chimes.m4r', 'Circuit.m4r', 'Constellation.m4r', 'Cosmic.m4r', 'Crystals.m4r', 'Hillside.m4r', 'Illuminate.m4r', 'Night Owl.m4r', 'Opening.m4r', 'Playtime.m4r', 'Presto.m4r', 'Radar.m4r', 'Radiate.m4r', 'Ripples.m4r', 'Sencha.m4r', 'Signal.m4r', 'Silk.m4r', 'Slow Rise.m4r', 'Stargaze.m4r', 'Summit.m4r', 'Twinkle.m4r', 'Uplift.m4r', 'Waves.m4r', 'voip', 'eligible', 'upgrade', 'planned', 'current', 'future', 'disable', 'expire', 'start', 'stop', 'accuracy', 'speed', 'bearing', 'recording', 'encrypt', 'key', 'identity', 'w:gp2', 'admin', 'locked', 'unlocked', 'new', 'battery', 'archive', 'adm', 'plaintext_size', 'compressed_size', 'delivered', 'msg', 'pkmsg', 'everyone', 'v', 'transport', 'call-id']\n", "repository": "Lijo050/yowsup-goibibo", "test_name": "test_getToken", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001734.py"} {"focal_file": "yowsup/layers/coder/tokendictionary.py", "focal_class": null, "focal_method": "getIndex", "tests": "import unittest\n\nclass Test_getIndex(unittest.TestCase):\n def test_getIndex(self):\n self.assertEqual(self.tokenDictionary.getIndex('iq'), (74, False))\n\n def test_getSecondaryIndex(self):\n self.assertEqual(self.tokenDictionary.getIndex('wmv'), (1, True))\n", "method_code": " def getIndex(self, token):\n if token in self.dictionary:\n return (self.dictionary.index(token), False)\n elif token in self.secondaryDictionary:\n return (self.secondaryDictionary.index(token), True)\n return None\n ", "context": "class TokenDictionary():\n def getIndex(self, token): ...\n def __init__(self): ...\n def getToken(self, index, secondary=False): ...\n\n self.dictionary = ['', '', '', 'account', 'ack', 'action', 'active', 'add', 'after', 'all', 'allow', 'apple', 'auth', 'author', 'available', 'bad-protocol', 'bad-request', 'before', 'body', 'broadcast', 'cancel', 'category', 'challenge', 'chat', 'clean', 'code', 'composing', 'config', 'contacts', 'count', 'create', 'creation', 'debug', 'default', 'delete', 'delivery', 'delta', 'deny', 'digest', 'dirty', 'duplicate', 'elapsed', 'enable', 'encoding', 'error', 'event', 'expiration', 'expired', 'fail', 'failure', 'false', 'favorites', 'feature', 'features', 'feature-not-implemented', 'field', 'first', 'free', 'from', 'g.us', 'get', 'google', 'group', 'groups', 'groups_v2', 'http://etherx.jabber.org/streams', 'http://jabber.org/protocol/chatstates', 'ib', 'id', 'image', 'img', 'index', 'internal-server-error', 'ip', 'iq', 'item-not-found', 'item', 'jabber:iq:last', 'jabber:iq:privacy', 'jabber:x:event', 'jid', 'kind', 'last', 'leave', 'list', 'max', 'mechanism', 'media', 'message_acks', 'message', 'method', 'microsoft', 'missing', 'modify', 'mute', 'name', 'nokia', 'none', 'not-acceptable', 'not-allowed', 'not-authorized', 'notification', 'notify', 'off', 'offline', 'order', 'owner', 'owning', 'p_o', 'p_t', 'paid', 'participant', 'participants', 'participating', 'paused', 'picture', 'pin', 'ping', 'platform', 'port', 'presence', 'preview', 'probe', 'prop', 'props', 'query', 'raw', 'read', 'readreceipts', 'reason', 'receipt', 'relay', 'remote-server-timeout', 'remove', 'request', 'required', 'resource-constraint', 'resource', 'response', 'result', 'retry', 'rim', 's_o', 's_t', 's.us', 's.whatsapp.net', 'seconds', 'server-error', 'server', 'service-unavailable', 'set', 'show', 'silent', 'stat', 'status', 'stream:error', 'stream:features', 'subject', 'subscribe', 'success', 'sync', 't', 'text', 'timeout', 'timestamp', 'to', 'true', 'type', 'unavailable', 'unsubscribe', 'uri', 'url', 'urn:ietf:params:xml:ns:xmpp-sasl', 'urn:ietf:params:xml:ns:xmpp-stanzas', 'urn:ietf:params:xml:ns:xmpp-streams', 'urn:xmpp:ping', 'urn:xmpp:whatsapp:account', 'urn:xmpp:whatsapp:dirty', 'urn:xmpp:whatsapp:mms', 'urn:xmpp:whatsapp:push', 'urn:xmpp:whatsapp', 'user', 'user-not-found', 'value', 'version', 'w:g', 'w:p:r', 'w:p', 'w:profile:picture', 'w', 'wait', 'WAUTH-2', 'xmlns:stream', 'xmlns', '1', 'chatstate', 'crypto', 'phash', 'enc', 'class', 'off_cnt', 'w:g2', 'promote', 'demote', 'creator', 'Bell.caf', 'Boing.caf', 'Glass.caf', 'Harp.caf', 'TimePassing.caf', 'Tri-tone.caf', 'Xylophone.caf', 'background', 'backoff', 'chunked', 'context', 'full', 'in', 'interactive', 'out', 'registration', 'sid', 'urn:xmpp:whatsapp:sync', 'flt', 's16', 'u8', 'adpcm', 'amrnb', 'amrwb', 'mp3', 'pcm', 'qcelp', 'wma', 'h263', 'h264', 'jpeg']\n self.secondaryDictionary = ['mpeg4', 'wmv', 'audio/3gpp', 'audio/aac', 'audio/amr', 'audio/mp4', 'audio/mpeg', 'audio/ogg', 'audio/qcelp', 'audio/wav', 'audio/webm', 'audio/x-caf', 'audio/x-ms-wma', 'image/gif', 'image/jpeg', 'image/png', 'video/3gpp', 'video/avi', 'video/mp4', 'video/mpeg', 'video/quicktime', 'video/x-flv', 'video/x-ms-asf', '302', '400', '401', '402', '403', '404', '405', '406', '407', '409', '410', '500', '501', '503', '504', 'abitrate', 'acodec', 'app_uptime', 'asampfmt', 'asampfreq', 'audio', 'clear', 'conflict', 'conn_no_nna', 'cost', 'currency', 'duration', 'extend', 'file', 'fps', 'g_notify', 'g_sound', 'gcm', 'gone', 'google_play', 'hash', 'height', 'invalid', 'jid-malformed', 'latitude', 'lc', 'lg', 'live', 'location', 'log', 'longitude', 'max_groups', 'max_participants', 'max_subject', 'mimetype', 'mode', 'napi_version', 'normalize', 'orighash', 'origin', 'passive', 'password', 'played', 'policy-violation', 'pop_mean_time', 'pop_plus_minus', 'price', 'pricing', 'redeem', 'Replaced by new connection', 'resume', 'signature', 'size', 'sound', 'source', 'system-shutdown', 'username', 'vbitrate', 'vcard', 'vcodec', 'video', 'width', 'xml-not-well-formed', 'checkmarks', 'image_max_edge', 'image_max_kbytes', 'image_quality', 'ka', 'ka_grow', 'ka_shrink', 'newmedia', 'library', 'caption', 'forward', 'c0', 'c1', 'c2', 'c3', 'clock_skew', 'cts', 'k0', 'k1', 'login_rtt', 'm_id', 'nna_msg_rtt', 'nna_no_off_count', 'nna_offline_ratio', 'nna_push_rtt', 'no_nna_con_count', 'off_msg_rtt', 'on_msg_rtt', 'stat_name', 'sts', 'suspect_conn', 'lists', 'self', 'qr', 'web', 'w:b', 'recipient', 'w:stats', 'forbidden', 'aurora.m4r', 'bamboo.m4r', 'chord.m4r', 'circles.m4r', 'complete.m4r', 'hello.m4r', 'input.m4r', 'keys.m4r', 'note.m4r', 'popcorn.m4r', 'pulse.m4r', 'synth.m4r', 'filehash', 'max_list_recipients', 'en-AU', 'en-GB', 'es-MX', 'pt-PT', 'zh-Hans', 'zh-Hant', 'relayelection', 'relaylatency', 'interruption', 'Apex.m4r', 'Beacon.m4r', 'Bulletin.m4r', 'By The Seaside.m4r', 'Chimes.m4r', 'Circuit.m4r', 'Constellation.m4r', 'Cosmic.m4r', 'Crystals.m4r', 'Hillside.m4r', 'Illuminate.m4r', 'Night Owl.m4r', 'Opening.m4r', 'Playtime.m4r', 'Presto.m4r', 'Radar.m4r', 'Radiate.m4r', 'Ripples.m4r', 'Sencha.m4r', 'Signal.m4r', 'Silk.m4r', 'Slow Rise.m4r', 'Stargaze.m4r', 'Summit.m4r', 'Twinkle.m4r', 'Uplift.m4r', 'Waves.m4r', 'voip', 'eligible', 'upgrade', 'planned', 'current', 'future', 'disable', 'expire', 'start', 'stop', 'accuracy', 'speed', 'bearing', 'recording', 'encrypt', 'key', 'identity', 'w:gp2', 'admin', 'locked', 'unlocked', 'new', 'battery', 'archive', 'adm', 'plaintext_size', 'compressed_size', 'delivered', 'msg', 'pkmsg', 'everyone', 'v', 'transport', 'call-id']\n", "repository": "Lijo050/yowsup-goibibo", "test_name": "test_getIndex", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001735.py"} {"focal_file": "plugin.video.vodie/resources/lib/simplejson/tests/test_encode_basestring_ascii.py", "focal_class": null, "focal_method": "_test_encode_basestring_ascii", "tests": "import unittest\n\nclass Test_test_encode_basestring_ascii(unittest.TestCase):\n def test_py_encode_basestring_ascii(self):\n self._test_encode_basestring_ascii(simplejson.encoder.py_encode_basestring_ascii)\n\n def test_c_encode_basestring_ascii(self):\n self._test_encode_basestring_ascii(simplejson.encoder.c_encode_basestring_ascii)\n", "method_code": " def _test_encode_basestring_ascii(self, encode_basestring_ascii):\n fname = encode_basestring_ascii.__name__\n for input_string, expect in CASES:\n result = encode_basestring_ascii(input_string)\n self.assertEquals(result, expect, '%r != %r for %s(%r)' % (result, expect, fname, input_string))\n ", "context": "class TestEncodeBaseStringAscii(TestCase):\n def _test_encode_basestring_ascii(self, encode_basestring_ascii): ...\n def test_py_encode_basestring_ascii(self): ...\n def test_c_encode_basestring_ascii(self): ...\n", "repository": "rapidleech/xbmc-vodie", "test_name": "test_py_encode_basestring_ascii", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001736.py"} {"focal_file": "plugin.video.vodie/resources/lib/simplejson/tests/test_scanstring.py", "focal_class": null, "focal_method": "_test_scanstring", "tests": "import unittest\n\nclass Test_test_scanstring(unittest.TestCase):\n def test_py_scanstring(self):\n self._test_scanstring(simplejson.decoder.py_scanstring)\n\n def test_c_scanstring(self):\n self._test_scanstring(simplejson.decoder.c_scanstring)\n", "method_code": " def _test_scanstring(self, scanstring):\n self.assertEquals(scanstring('\"z\\\\ud834\\\\udd20x\"', 1, None, True), (u'z𝄠x', 16))\n if sys.maxunicode == 65535:\n self.assertEquals(scanstring(u'\"z𝄠x\"', 1, None, True), (u'z𝄠x', 6))\n else:\n self.assertEquals(scanstring(u'\"z𝄠x\"', 1, None, True), (u'z𝄠x', 5))\n self.assertEquals(scanstring('\"\\\\u007b\"', 1, None, True), (u'{', 8))\n self.assertEquals(scanstring('\"A JSON payload should be an object or array, not a string.\"', 1, None, True), (u'A JSON payload should be an object or array, not a string.', 60))\n self.assertEquals(scanstring('[\"Unclosed array\"', 2, None, True), (u'Unclosed array', 17))\n self.assertEquals(scanstring('[\"extra comma\",]', 2, None, True), (u'extra comma', 14))\n self.assertEquals(scanstring('[\"double extra comma\",,]', 2, None, True), (u'double extra comma', 21))\n self.assertEquals(scanstring('[\"Comma after the close\"],', 2, None, True), (u'Comma after the close', 24))\n self.assertEquals(scanstring('[\"Extra close\"]]', 2, None, True), (u'Extra close', 14))\n self.assertEquals(scanstring('{\"Extra comma\": true,}', 2, None, True), (u'Extra comma', 14))\n self.assertEquals(scanstring('{\"Extra value after close\": true} \"misplaced quoted value\"', 2, None, True), (u'Extra value after close', 26))\n self.assertEquals(scanstring('{\"Illegal expression\": 1 + 2}', 2, None, True), (u'Illegal expression', 21))\n self.assertEquals(scanstring('{\"Illegal invocation\": alert()}', 2, None, True), (u'Illegal invocation', 21))\n self.assertEquals(scanstring('{\"Numbers cannot have leading zeroes\": 013}', 2, None, True), (u'Numbers cannot have leading zeroes', 37))\n self.assertEquals(scanstring('{\"Numbers cannot be hex\": 0x14}', 2, None, True), (u'Numbers cannot be hex', 24))\n self.assertEquals(scanstring('[[[[[[[[[[[[[[[[[[[[\"Too deep\"]]]]]]]]]]]]]]]]]]]]', 21, None, True), (u'Too deep', 30))\n self.assertEquals(scanstring('{\"Missing colon\" null}', 2, None, True), (u'Missing colon', 16))\n self.assertEquals(scanstring('{\"Double colon\":: null}', 2, None, True), (u'Double colon', 15))\n self.assertEquals(scanstring('{\"Comma instead of colon\", null}', 2, None, True), (u'Comma instead of colon', 25))\n self.assertEquals(scanstring('[\"Colon instead of comma\": false]', 2, None, True), (u'Colon instead of comma', 25))\n self.assertEquals(scanstring('[\"Bad value\", truth]', 2, None, True), (u'Bad value', 12))\n ", "context": "class TestScanString(TestCase):\n def _test_scanstring(self, scanstring): ...\n def test_py_scanstring(self): ...\n def test_c_scanstring(self): ...\n", "repository": "rapidleech/xbmc-vodie", "test_name": "test_py_scanstring", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001737.py"} {"focal_file": "get_max_profit.py", "focal_class": null, "focal_method": "get_max_difference", "tests": "import unittest\n\nclass Test_get_max_difference(unittest.TestCase):\n def test_get_max_difference(self):\n result = self.calculator.get_max_difference(VALUES)\n self.assertEqual(EXPECTED, result)\n", "method_code": " def get_max_difference(self, values):\n max_diff = values[1] - values[0]\n min_price = values[0]\n for index, value in enumerate(values):\n if index > 0:\n max_diff = max(max_diff, value - min_price)\n min_price = min(value, min_price)\n return max_diff\n ", "context": "class GetMaxProfit():\n def get_max_difference(self, values): ...\n def check_values_length(self, values): ...\n def calculate_max_profit(self, values): ...\n", "repository": "jakobpederson/get_max_profit", "test_name": "test_get_max_difference", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001738.py"} {"focal_file": "get_max_profit.py", "focal_class": null, "focal_method": "check_values_length", "tests": "import unittest\n\nclass Test_check_values_length(unittest.TestCase):\n def test_check_values_length_if_gt_2(self):\n self.assertEqual(True, self.calculator.check_values_length(VALUES))\n\n def test_check_values_length_if_lt_2(self):\n self.assertEqual(False, self.calculator.check_values_length(VALUES_ONE))\n", "method_code": " def check_values_length(self, values):\n if len(values) >= 2:\n return True\n return False\n ", "context": "class GetMaxProfit():\n def check_values_length(self, values): ...\n def get_max_difference(self, values): ...\n def calculate_max_profit(self, values): ...\n", "repository": "jakobpederson/get_max_profit", "test_name": "test_check_values_length_if_gt_2", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001739.py"} {"focal_file": "get_max_profit.py", "focal_class": null, "focal_method": "calculate_max_profit", "tests": "import unittest\n\nclass Test_calculate_max_profit(unittest.TestCase):\n def test_calculate_max_profit(self):\n result = self.calculator.calculate_max_profit(VALUES)\n result_one = self.calculator.calculate_max_profit(VALUES_ONE)\n self.assertEqual(EXPECTED, result)\n self.assertEqual('Error: not enough values', result_one)\n", "method_code": " def calculate_max_profit(self, values):\n if self.check_values_length(values):\n return self.get_max_difference(values)\n return 'Error: not enough values'\n ", "context": "class GetMaxProfit():\n def calculate_max_profit(self, values): ...\n def get_max_difference(self, values): ...\n def check_values_length(self, values): ...\n", "repository": "jakobpederson/get_max_profit", "test_name": "test_calculate_max_profit", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001740.py"} {"focal_file": "openvas_lib/common.py", "focal_class": null, "focal_method": "make_xml_request", "tests": "import unittest\n\nclass Test_make_xml_request(unittest.TestCase):\n def test_make_xml_request_responses(self):\n xml1 = ''\n r1 = self.c.make_xml_request(xml1, xml_result=False)\n self.assertEqual(r1, 'Authentication failed')\n r2 = self.c.make_xml_request(xml1, xml_result=True)\n self.assertEqual(xml1, etree.tostring(r2))\n", "method_code": " def make_xml_request(self, xmldata, xml_result=False):\n \"\"\"\n \t\tLow-level interface to send OMP XML to the manager.\n \n \t\t`xmldata` may be either a utf-8 encoded string or an etree\n \t\tElement. If `xml_result` is true, the result is returned as an\n \t\tetree Element, otherwise a utf-8 encoded string is returned.\n \n \t\t:param xmldata: string with the XML data.\n \t\t:type: xmldata: str\n \n \t\t:param xml_result: boolean that indicates if the response will be in XML format.\n \t\t:type xml_result: bool\n \n \t\t:return: a text/xml data from the server.\n \t\t:rtype: `ElementTree`|str\n \n \t\t:raises: ClientError, ServerError, TypeError, ValueError\n \t\t\"\"\"\n if not isinstance(xmldata, str):\n raise TypeError(\"Expected str, got '%s' instead\" % type(xmldata))\n if not isinstance(xml_result, bool):\n raise TypeError(\"Expected bool, got '%s' instead\" % type(xml_result))\n response = self._send(xmldata)\n if response is None:\n raise TypeError(\"Expected ElementTree, got '%s' instead\" % type(response))\n try:\n status = response.get('status', None)\n except:\n raise ValueError('Missing status property in response')\n if status is None or status == '':\n raise ValueError('response is missing status: %s' % etree.tostring(response))\n if status.startswith('4'):\n raise ClientError('[%s] %s: %s' % (status, response.tag, response.get('status_text')))\n elif status.startswith('5'):\n raise ServerError('[%s] %s: %s' % (status, response.tag, response.get('status_text')))\n elif status.startswith('2'):\n if xml_result:\n return response\n else:\n return response.get('status_text')\n else:\n raise ServerError('Invalid status code returned by server: %s' % status)\n ", "context": "class ConnectionManager(object):\n def make_xml_request(self, xmldata, xml_result=False): ...\n def __init__(self, host, username, password, port=9390, timeout=None, ssl_verify=False): ...\n def _connect(self): ...\n def _authenticate(self, username, password): ...\n def _get_protocol_version(self): ...\n def _send(self, in_data): ...\n def close(self): ...\n def protocol_version(self): ...\n\n self.__host = host\n self.__username = username\n self.__password = password\n self.__port = port\n self.__ssl_verify = ssl_verify\n self.__timeout = ConnectionManager.TIMEOUT\n self.__socket_lock = RLock()\n self.socket = None\n self.__version = self._get_protocol_version()\n\n TIMEOUT = 10.0\n", "repository": "golismero/openvas_lib", "test_name": "test_make_xml_request_responses", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001741.py"} {"focal_file": "openvas_lib/__init__.py", "focal_class": null, "focal_method": "report_parser", "tests": "import unittest\n\nclass Test_report_parser(unittest.TestCase):\n def test_report_parser_check_empty_results(self):\n xml = StringIO.StringIO('')\n r = report_parser(xml)\n self.assertIsInstance(r, list)\n self.assertEqual(0, len(r))\n\n def test_report_parser_invalid_threat(self):\n xml_invalid_thread = StringIO.StringIO('\\n\\t\\n\\t\\t\\n\\t\\t\\t10.211.55.35\\n\\t\\t\\t10.211.55.35\\n\\t\\t\\tclm_pts (6200/tcp)\\n\\t\\t\\t\\n\\t\\t\\t\\tvsftpd Compromised Source Packages Backdoor Vulnerability\\n\\t\\t\\t\\tGain a shell remotely\\n\\t\\t\\t\\t7.5\\n\\t\\t\\t\\tHigh\\n\\t\\t\\t\\tNOCVE\\n\\t\\t\\t\\t48539\\n\\t\\t\\t\\tcvss_base_vector=AV:N/AC:L/Au:N/C:P/I:P/A:P\\n\\t\\t\\t\\t\\n\\t\\t\\t\\tNOXREF\\n\\t\\t\\t\\n\\t\\t\\tAA\\n\\t\\t\\t\\n Summary:\\n vsftpd is prone to a backdoor vulnerability.\\n\\nAttackers can exploit this issue to execute arbitrary commands in the\\ncontext of the application. Successful attacks will compromise the\\naffected application.\\n\\nThe vsftpd 2.3.4 source package is affected.\\n Solution:\\n The repaired package can be downloaded from\\nhttps://security.appspot.com/vsftpd.html. Please validate the package\\nwith its signature.\\n\\t\\t\\t\\n\\t\\t\\tHigh\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\n\\t\\n')\n xml_empty_thread = StringIO.StringIO('\\n\\t\\n\\t\\t\\n\\t\\t\\t10.211.55.35\\n\\t\\t\\t10.211.55.35\\n\\t\\t\\tclm_pts (6200/tcp)\\n\\t\\t\\t\\n\\t\\t\\t\\tvsftpd Compromised Source Packages Backdoor Vulnerability\\n\\t\\t\\t\\tGain a shell remotely\\n\\t\\t\\t\\t7.5\\n\\t\\t\\t\\tHigh\\n\\t\\t\\t\\tNOCVE\\n\\t\\t\\t\\t48539\\n\\t\\t\\t\\tcvss_base_vector=AV:N/AC:L/Au:N/C:P/I:P/A:P\\n\\t\\t\\t\\t\\n\\t\\t\\t\\tNOXREF\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\n Summary:\\n vsftpd is prone to a backdoor vulnerability.\\n\\nAttackers can exploit this issue to execute arbitrary commands in the\\ncontext of the application. Successful attacks will compromise the\\naffected application.\\n\\nThe vsftpd 2.3.4 source package is affected.\\n Solution:\\n The repaired package can be downloaded from\\nhttps://security.appspot.com/vsftpd.html. Please validate the package\\nwith its signature.\\n\\t\\t\\t\\n\\t\\t\\tHigh\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\n\\t\\n')\n self.assertEqual(0, len(report_parser(xml_invalid_thread)))\n self.assertEqual(0, len(report_parser(xml_empty_thread)))\n", "method_code": "def report_parser(path_or_file, ignore_log_info=True):\n \"\"\"\n\tThis functions transform XML OpenVas file report to OpenVASResult object structure.\n\n\tTo pass StringIO file as parameter, you must do that:\n\t>>> import StringIO\n\t>>> xml=''\n\t>>> f=StringIO.StringIO(xml)\n\t>>> report_parser(f)\n\t[OpenVASResult]\n\n\tTo pass a file path:\n\t>>> xml_path='/home/my_user/openvas_result.xml'\n\t>>> report_parser(xml_path)\n\t[OpenVASResult]\n\n\tLanguage specification: http://www.openvas.org/omp-4-0.html\n\n\t:param path_or_file: path or file descriptor to xml file.\n\t:type path_or_file: str | file | StringIO\n\n\t:param ignore_log_info: Ignore Threats with Log and Debug info\n\t:type ignore_log_info: bool\n\n\t:raises: etree.ParseError, IOError, TypeError\n\n\t:return: list of OpenVASResult structures.\n\t:rtype: list(OpenVASResult)\n\t\"\"\"\n if isinstance(path_or_file, str):\n if not os.path.exists(path_or_file):\n raise IOError('File %s not exits.' % path_or_file)\n if not os.path.isfile(path_or_file):\n raise IOError('%s is not a file.' % path_or_file)\n elif not getattr(getattr(path_or_file, '__class__', ''), '__name__', '') in ('file', 'StringIO', 'StringO', 'StringI'):\n raise TypeError(\"Expected str or file, got '%s' instead\" % type(path_or_file))\n try:\n xml_parsed = etree.parse(path_or_file)\n except etree.ParseError:\n raise etree.ParseError('Invalid XML file. Ensure file is correct and all tags are properly closed.')\n if type(xml_parsed).__name__ == 'Element':\n xml = xml_parsed\n elif type(xml_parsed).__name__ == 'ElementTree':\n xml = xml_parsed.getroot()\n else:\n raise TypeError(\"Expected ElementTree or Element, got '%s' instead\" % type(xml_parsed))\n if 'status' in xml.keys():\n xml = xml[0]\n if 'id' not in xml.keys():\n raise ValueError(\"XML format is not valid, doesn't contains id attribute.\")\n port_regex_specific = re.compile('([\\\\w\\\\d\\\\s]*)\\\\(([\\\\d]+)/([\\\\w\\\\W\\\\d]+)\\\\)')\n port_regex_generic = re.compile('([\\\\w\\\\d\\\\s]*)/([\\\\w\\\\W\\\\d]+)')\n cvss_regex = re.compile('(cvss_base_vector=[\\\\s]*)([\\\\w:/]+)')\n vulnerability_IDs = ('cve', 'bid', 'bugtraq')\n m_return = []\n m_return_append = m_return.append\n for l_results in xml.findall('.//result'):\n l_partial_result = OpenVASResult()\n l_vid = None\n try:\n l_vid = l_results.get('id')\n l_partial_result.id = l_vid\n except TypeError as e:\n logging.warning('%s is not a valid vulnerability ID, skipping vulnerability...' % l_vid)\n logging.debug(e)\n continue\n threat = l_results.find('threat')\n if threat is None:\n logging.warning(\"Vulnerability %s can't has 'None' as thread value, skipping vulnerability...\" % l_vid)\n continue\n elif threat.text not in OpenVASResult.risk_levels:\n logging.warning('%s is not a valid risk level for %s vulnerability. skipping vulnerability...' % (threat.text, l_vid))\n continue\n if threat.text in ('Log', 'Debug') and ignore_log_info is True:\n continue\n for l_val in l_results.getchildren():\n l_tag = l_val.tag\n if l_tag in ('subnet', 'host', 'threat'):\n try:\n setattr(l_partial_result, l_tag, l_val.text)\n except (TypeError, ValueError) as e:\n logging.warning('%s is not a valid value for %s property in %s vulnerability. skipping vulnerability...' % (l_val.text, l_tag, l_partial_result.id))\n logging.debug(e)\n continue\n elif l_tag == 'description':\n try:\n setattr(l_partial_result, 'raw_description', l_val.text)\n except TypeError as e:\n logging.warning('%s is not a valid description for %s vulnerability. skipping vulnerability...' % (l_val.text, l_vid))\n logging.debug(e)\n continue\n elif l_tag == 'port':\n l_port = port_regex_specific.search(l_val.text)\n if l_port:\n l_service = l_port.group(1)\n l_number = int(l_port.group(2))\n l_proto = l_port.group(3)\n try:\n l_partial_result.port = OpenVASPort(l_service, l_number, l_proto)\n except (TypeError, ValueError) as e:\n logging.warning('%s is not a valid port for %s vulnerability. skipping vulnerability...' % (l_val.text, l_vid))\n logging.debug(e)\n continue\n else:\n l_port = port_regex_generic.search(l_val.text)\n if l_port:\n l_service = l_port.group(1)\n l_proto = l_port.group(2)\n try:\n l_partial_result.port = OpenVASPort(l_service, 0, l_proto)\n except (TypeError, ValueError) as e:\n logging.warning('%s is not a valid port for %s vulnerability. skipping vulnerability...' % (l_val.text, l_vid))\n logging.debug(e)\n continue\n elif l_tag == 'nvt':\n l_nvt_object = OpenVASNVT()\n try:\n l_nvt_object.oid = l_val.attrib['oid']\n except TypeError as e:\n logging.warning('%s is not a valid NVT oid for %s vulnerability. skipping vulnerability...' % (l_val.attrib['oid'], l_vid))\n logging.debug(e)\n continue\n l_nvt_symbols = [x for x in dir(l_nvt_object) if not x.startswith('_')]\n for l_nvt in l_val.getchildren():\n l_nvt_tag = l_nvt.tag\n if l_nvt_tag in l_nvt_symbols:\n if l_nvt.text:\n if l_nvt.text.startswith('NO'):\n try:\n setattr(l_nvt_object, l_nvt_tag, '')\n except (TypeError, ValueError) as e:\n logging.warning('Empty value is not a valid NVT value for %s property in %s vulnerability. skipping vulnerability...' % (l_nvt_tag, l_vid))\n logging.debug(e)\n continue\n elif l_nvt_tag.lower() in vulnerability_IDs:\n l_nvt_text = getattr(l_nvt, 'text', '')\n try:\n setattr(l_nvt_object, l_nvt_tag, l_nvt_text.split(','))\n except (TypeError, ValueError) as e:\n logging.warning('%s value is not a valid NVT value for %s property in %s vulnerability. skipping vulnerability...' % (l_nvt_text, l_nvt_tag, l_vid))\n logging.debug(e)\n continue\n else:\n l_nvt_text = getattr(l_nvt, 'text', '')\n try:\n setattr(l_nvt_object, l_nvt_tag, l_nvt_text)\n except (TypeError, ValueError) as e:\n logging.warning('%s value is not a valid NVT value for %s property in %s vulnerability. skipping vulnerability...' % (l_nvt_text, l_nvt_tag, l_vid))\n logging.debug(e)\n continue\n else:\n try:\n setattr(l_nvt_object, l_nvt_tag, '')\n except (TypeError, ValueError) as e:\n logging.warning('Empty value is not a valid NVT value for %s property in %s vulnerability. skipping vulnerability...' % (l_nvt_tag, l_vid))\n logging.debug(e)\n continue\n cvss_candidate = l_val.find('tags')\n if cvss_candidate is not None and getattr(cvss_candidate, 'text', None):\n cvss_tmp = cvss_regex.search(cvss_candidate.text)\n if cvss_tmp:\n l_nvt_object.cvss_base_vector = cvss_tmp.group(2) if len(cvss_tmp.groups()) >= 2 else ''\n try:\n l_partial_result.nvt = l_nvt_object\n except (TypeError, ValueError) as e:\n logging.warning('NVT oid %s is not a valid NVT value for %s vulnerability. skipping vulnerability...' % (l_nvt_object.oid, l_vid))\n logging.debug(e)\n continue\n elif l_tag == 'severity':\n try:\n l_severity = l_val.text\n l_partial_result.severity = l_severity\n except TypeError as e:\n logging.warning('%s is not a valid severity, skipping vulnerability...' % l_severity)\n logging.debug(e)\n continue\n elif l_tag == 'name':\n try:\n l_name = l_val.text\n l_partial_result.name = l_name\n except TypeError as e:\n logging.warning('%s is not a valid vulnerability ID, skipping vulnerability...' % l_name)\n logging.debug(e)\n continue\n else:\n logging.warning('%s tag unrecognised' % l_tag)\n m_return_append(l_partial_result)\n return m_return", "context": "def report_parser(path_or_file, ignore_log_info=True): ...\ndef report_parser_from_text(text, ignore_log_info=True): ...\ndef report_parser(path_or_file, ignore_log_info=True): ...\n", "repository": "golismero/openvas_lib", "test_name": "test_report_parser_check_empty_results", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001742.py"} {"focal_file": "zorg/buildbot/commands/LitTestCommand.py", "focal_class": null, "focal_method": "parse_log", "tests": "import unittest\n\nclass Test_parse_log(unittest.TestCase):\n def test_verbose_logs(self):\n obs = self.parse_log(\"\\nFAIL: test-one (1 of 3)\\nFAIL: test-two (2 of 3)\\n**** TEST 'test-two' FAILED ****\\nbla bla bla\\n**********\\nFAIL: test-three (3 of 3)\\n\")\n self.assertEqual(obs.resultCounts, {'FAIL': 3})\n self.assertEqual(obs.step.logs, [('test-one', 'FAIL: test-one'), ('test-two', \"**** TEST 'test-two' FAILED ****\\nbla bla bla\\n**********\"), ('test-three', 'FAIL: test-three')])\n", "method_code": " def parse_log(self, text):\n observer = LitLogObserver()\n observer.step = StepProxy()\n for ln in text.split('\\n'):\n observer.outLineReceived(ln)\n return observer\n ", "context": "class TestLogObserver(unittest.TestCase):\n def parse_log(self, text): ...\n def test_basic(self): ...\n def test_verbose_logs(self): ...\n", "repository": "etherzhhb/PollyTryBot", "test_name": "test_verbose_logs", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001743.py"} {"focal_file": "src/tldt/diff.py", "focal_class": null, "focal_method": "file_to_diff", "tests": "import unittest\n\nclass Test_file_to_diff(unittest.TestCase):\n def test_file_to_diff(self):\n linum = self.mapper.file_to_diff('src/tldt/diff.py', 4)\n self.assertEqual(linum, 4)\n linum = self.mapper.file_to_diff('requirements.txt', 3)\n self.assertEqual(linum, None)\n linum = self.mapper.file_to_diff('src/tldt/tldt.py', 124)\n self.assertEqual(linum, 13)\n", "method_code": " def file_to_diff(self, filename, linum):\n f = self._map.get(filename, None)\n if f is None:\n return None\n hunk_offset = 0\n for hunk in f:\n start = hunk.target_start\n end = hunk.target_start + hunk.target_length - 1\n if not start <= linum <= end:\n hunk_offset += len(hunk.original_lines) + 1\n continue\n offset = linum - hunk.target_start\n final_line = offset + 1\n if hunk.original_types[offset] == '+':\n return final_line + hunk_offset\n ", "context": "class Mapper(object):\n def file_to_diff(self, filename, linum): ...\n def __init__(self, diff_file): ...\n\n self.diff = unidiff.parser.parse_unidiff(StringIO(diff_file))\n self._map = {}\n", "repository": "rciorba/tldt", "test_name": "test_file_to_diff", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001744.py"} {"focal_file": "pox/lib/mock_socket.py", "focal_class": null, "focal_method": "send", "tests": "import unittest\n\nclass Test_send(unittest.TestCase):\n def test_simple_send(self):\n a, b = MockSocket.pair()\n a.send('Hallo')\n self.assertEquals(b.recv(), 'Hallo')\n b.send('Servus')\n self.assertEquals(a.recv(), 'Servus')\n\n def test_basic_send(self):\n i = IOWorker()\n i.send('foo')\n self.assertTrue(i._ready_to_send)\n self.assertEqual(i.send_buf, 'foo')\n i._consume_send_buf(3)\n self.assertFalse(i._ready_to_send)\n", "method_code": " def send(self, data):\n \"\"\"\n Send data out on this socket.\n \n Data will be available for reading at the receiving socket pair.\n Note that this currently always succeeds and never blocks (unlimited\n receive buffer size)\n \"\"\"\n return self.sending.send(data)\n ", "context": "class MockSocket(object):\n def send(self, data): ...\n def __init__(self, receiving, sending): ...\n def recv(self, max_size=None): ...\n def set_on_ready_to_recv(self, on_ready): ...\n def ready_to_recv(self): ...\n def ready_to_send(self): ...\n def shutdown(self, sig=None): ...\n def close(self): ...\n def fileno(self): ...\n def pair(cls): ...\n\n self.receiving = receiving\n self.sending = sending\n", "repository": "jbteixeir/Openflow-DC-Framework", "test_name": "test_simple_send", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001745.py"} {"focal_file": "pox/lib/mock_socket.py", "focal_class": null, "focal_method": "recv", "tests": "import unittest\n\nclass Test_recv(unittest.TestCase):\n def test_ready_to_recv(self):\n a, b = MockSocket.pair()\n a.send('Hallo')\n self.assertFalse(a.ready_to_recv())\n self.assertTrue(b.ready_to_recv())\n self.assertEquals(b.recv(), 'Hallo')\n self.assertFalse(b.ready_to_recv())\n self.assertFalse(a.ready_to_recv())\n b.send('Servus')\n self.assertTrue(a.ready_to_recv())\n self.assertEquals(a.recv(), 'Servus')\n self.assertFalse(a.ready_to_recv())\n\n def test_empty_recv(self):\n \"\"\" test_empty_recv: Check that empty reads on socket return \"\"\n Note that this is actually non-sockety behavior and should probably be changed. This\n test documents it as intended for now, though\n \"\"\"\n a, b = MockSocket.pair()\n self.assertEquals(a.recv(), '')\n", "method_code": " def recv(self, max_size=None):\n \"\"\"\n receive data on this sockect.\n \n If no data is available to be received, return \"\".\n Note that this is non-standard socket behavior and should be\n changed to mimic either blocking on non-blocking socket semantics\n \"\"\"\n return self.receiving.recv(max_size)\n ", "context": "class MockSocket(object):\n def recv(self, max_size=None): ...\n def __init__(self, receiving, sending): ...\n def send(self, data): ...\n def set_on_ready_to_recv(self, on_ready): ...\n def ready_to_recv(self): ...\n def ready_to_send(self): ...\n def shutdown(self, sig=None): ...\n def close(self): ...\n def fileno(self): ...\n def pair(cls): ...\n\n self.receiving = receiving\n self.sending = sending\n", "repository": "jbteixeir/Openflow-DC-Framework", "test_name": "test_ready_to_recv", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001746.py"} {"focal_file": "pox/lib/mock_socket.py", "focal_class": null, "focal_method": "set_on_ready_to_recv", "tests": "import unittest\n\nclass Test_set_on_ready_to_recv(unittest.TestCase):\n def test_on_ready_to_recv(self):\n self.seen_size = -1\n self.called = 0\n\n def ready(socket, size):\n self.called += 1\n self.seen_size = size\n a, b = MockSocket.pair()\n b.set_on_ready_to_recv(ready)\n self.assertEquals(self.called, 0)\n a.send('Hallo')\n self.assertEquals(self.called, 1)\n self.assertEquals(self.seen_size, 5)\n b.send('Huhu')\n self.assertEquals(self.called, 1)\n", "method_code": " def set_on_ready_to_recv(self, on_ready):\n \"\"\"\n set a handler function on_ready(socket, size) to be called when\n data is available for reading at this socket\n \"\"\"\n self.receiving.on_data = lambda channel, size: on_ready(self, size)\n ", "context": "class MockSocket(object):\n def set_on_ready_to_recv(self, on_ready): ...\n def __init__(self, receiving, sending): ...\n def send(self, data): ...\n def recv(self, max_size=None): ...\n def ready_to_recv(self): ...\n def ready_to_send(self): ...\n def shutdown(self, sig=None): ...\n def close(self): ...\n def fileno(self): ...\n def pair(cls): ...\n\n self.receiving = receiving\n self.sending = sending\n", "repository": "jbteixeir/Openflow-DC-Framework", "test_name": "test_on_ready_to_recv", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001747.py"} {"focal_file": "pox/lib/mock_socket.py", "focal_class": null, "focal_method": "close", "tests": "import unittest\n\nclass Test_close(unittest.TestCase):\n def test_run_close(self):\n loop = RecocoIOLoop()\n left, right = MockSocket.pair()\n worker = loop.new_worker(left)\n self.assertFalse(worker in loop._workers, 'Should not add to _workers yet, until we start up the loop')\n self.assertTrue(len(loop._pending_commands) == 1, 'Should have added pending create() command')\n worker.close()\n self.assertTrue(len(loop._pending_commands) == 2, 'Should have added pending close() command')\n", "method_code": " def close(self):\n \"\"\"\n close a socket. Currently a no-op on this MockSocket object.\n \"\"\"\n pass\n ", "context": "class MockSocket(object):\n def close(self): ...\n def __init__(self, receiving, sending): ...\n def send(self, data): ...\n def recv(self, max_size=None): ...\n def set_on_ready_to_recv(self, on_ready): ...\n def ready_to_recv(self): ...\n def ready_to_send(self): ...\n def shutdown(self, sig=None): ...\n def fileno(self): ...\n def pair(cls): ...\n\n self.receiving = receiving\n self.sending = sending\n", "repository": "jbteixeir/Openflow-DC-Framework", "test_name": "test_run_close", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001748.py"} {"focal_file": "lib/simplejson/__init__.py", "focal_class": null, "focal_method": "dumps", "tests": "import unittest\n\nclass Test_dumps(unittest.TestCase):\n def test_namedtuple_dumps(self):\n for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:\n d = v._asdict()\n self.assertEqual(d, json.loads(json.dumps(v)))\n self.assertEqual(d, json.loads(json.dumps(v, namedtuple_as_object=True)))\n self.assertEqual(d, json.loads(json.dumps(v, tuple_as_array=False)))\n self.assertEqual(d, json.loads(json.dumps(v, namedtuple_as_object=True, tuple_as_array=False)))\n\n def test_asdict_not_callable_dumps(self):\n for f in CONSTRUCTORS:\n self.assertRaises(TypeError, json.dumps, f(DeadDuck()), namedtuple_as_object=True)\n self.assertEqual(json.dumps(f({})), json.dumps(f(DeadDict()), namedtuple_as_object=True))\n\n def test_tuple_array_dumps(self):\n t = (1, 2, 3)\n expect = json.dumps(list(t))\n self.assertEqual(expect, json.dumps(t))\n self.assertEqual(expect, json.dumps(t, tuple_as_array=True))\n self.assertRaises(TypeError, json.dumps, t, tuple_as_array=False)\n self.assertEqual(expect, json.dumps(t, default=repr))\n self.assertEqual(expect, json.dumps(t, tuple_as_array=True, default=repr))\n self.assertEqual(json.dumps(repr(t)), json.dumps(t, tuple_as_array=False, default=repr))\n", "method_code": "def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw):\n \"\"\"Serialize ``obj`` to a JSON formatted ``str``.\n\n If ``skipkeys`` is false then ``dict`` keys that are not basic types\n (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\n will be skipped instead of raising a ``TypeError``.\n\n If ``ensure_ascii`` is false, then the return value will be a\n ``unicode`` instance subject to normal Python ``str`` to ``unicode``\n coercion rules instead of being escaped to an ASCII ``str``.\n\n If ``check_circular`` is false, then the circular reference check\n for container types will be skipped and a circular reference will\n result in an ``OverflowError`` (or worse).\n\n If ``allow_nan`` is false, then it will be a ``ValueError`` to\n serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in\n strict compliance of the JSON specification, instead of using the\n JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n\n If ``indent`` is a string, then JSON array elements and object members\n will be pretty-printed with a newline followed by that string repeated\n for each level of nesting. ``None`` (the default) selects the most compact\n representation without any newlines. For backwards compatibility with\n versions of simplejson earlier than 2.1.0, an integer is also accepted\n and is converted to a string with that many spaces.\n\n If specified, ``separators`` should be an\n ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``\n if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most\n compact JSON representation, you should specify ``(',', ':')`` to eliminate\n whitespace.\n\n ``encoding`` is the character encoding for str instances, default is UTF-8.\n\n ``default(obj)`` is a function that should return a serializable version\n of obj or raise TypeError. The default simply raises TypeError.\n\n If *use_decimal* is true (default: ``True``) then decimal.Decimal\n will be natively serialized to JSON with full precision.\n\n If *namedtuple_as_object* is true (default: ``True``),\n :class:`tuple` subclasses with ``_asdict()`` methods will be encoded\n as JSON objects.\n\n If *tuple_as_array* is true (default: ``True``),\n :class:`tuple` (and subclasses) will be encoded as JSON arrays.\n\n If *iterable_as_array* is true (default: ``False``),\n any object not in the above table that implements ``__iter__()``\n will be encoded as a JSON array.\n\n If *bigint_as_string* is true (not the default), ints 2**53 and higher\n or lower than -2**53 will be encoded as strings. This is to avoid the\n rounding that happens in Javascript otherwise.\n\n If *int_as_string_bitcount* is a positive number (n), then int of size\n greater than or equal to 2**n or lower than or equal to -2**n will be\n encoded as strings.\n\n If specified, *item_sort_key* is a callable used to sort the items in\n each dictionary. This is useful if you want to sort items other than\n in alphabetical order by key. This option takes precendence over\n *sort_keys*.\n\n If *sort_keys* is true (default: ``False``), the output of dictionaries\n will be sorted by item.\n\n If *for_json* is true (default: ``False``), objects with a ``for_json()``\n method will use the return value of that method for encoding as JSON\n instead of the object.\n\n If *ignore_nan* is true (default: ``False``), then out of range\n :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as\n ``null`` in compliance with the ECMA-262 specification. If true, this will\n override *allow_nan*.\n\n To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n ``.default()`` method to serialize additional types), specify it with\n the ``cls`` kwarg. NOTE: You should use *default* instead of subclassing\n whenever possible.\n\n \"\"\"\n if not skipkeys and ensure_ascii and check_circular and allow_nan and (cls is None) and (indent is None) and (separators is None) and (encoding == 'utf-8') and (default is None) and use_decimal and namedtuple_as_object and tuple_as_array and (not iterable_as_array) and (not bigint_as_string) and (not sort_keys) and (not item_sort_key) and (not for_json) and (not ignore_nan) and (int_as_string_bitcount is None) and (not kw):\n return _default_encoder.encode(obj)\n if cls is None:\n cls = JSONEncoder\n return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, iterable_as_array=iterable_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, int_as_string_bitcount=int_as_string_bitcount, **kw).encode(obj)", "context": "def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef _import_OrderedDict(): ...\ndef _import_c_make_encoder(): ...\ndef dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): ...\ndef loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): ...\ndef _toggle_speedups(enabled): ...\ndef simple_first(kv): ...\n", "repository": "gladed/zenchart", "test_name": "test_namedtuple_dumps", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001749.py"} {"focal_file": "lib/simplejson/__init__.py", "focal_class": null, "focal_method": "dump", "tests": "import unittest\n\nclass Test_dump(unittest.TestCase):\n def test_namedtuple_dump(self):\n for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:\n d = v._asdict()\n sio = StringIO()\n json.dump(v, sio)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, namedtuple_as_object=True)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, tuple_as_array=False)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, namedtuple_as_object=True, tuple_as_array=False)\n self.assertEqual(d, json.loads(sio.getvalue()))\n\n def test_asdict_not_callable_dump(self):\n for f in CONSTRUCTORS:\n self.assertRaises(TypeError, json.dump, f(DeadDuck()), StringIO(), namedtuple_as_object=True)\n sio = StringIO()\n json.dump(f(DeadDict()), sio, namedtuple_as_object=True)\n self.assertEqual(json.dumps(f({})), sio.getvalue())\n\n def test_tuple_array_dump(self):\n t = (1, 2, 3)\n expect = json.dumps(list(t))\n sio = StringIO()\n json.dump(t, sio)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=True)\n self.assertEqual(expect, sio.getvalue())\n self.assertRaises(TypeError, json.dump, t, StringIO(), tuple_as_array=False)\n sio = StringIO()\n json.dump(t, sio, default=repr)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=True, default=repr)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=False, default=repr)\n self.assertEqual(json.dumps(repr(t)), sio.getvalue())\n", "method_code": "def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw):\n \"\"\"Serialize ``obj`` as a JSON formatted stream to ``fp`` (a\n ``.write()``-supporting file-like object).\n\n If *skipkeys* is true then ``dict`` keys that are not basic types\n (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\n will be skipped instead of raising a ``TypeError``.\n\n If *ensure_ascii* is false, then the some chunks written to ``fp``\n may be ``unicode`` instances, subject to normal Python ``str`` to\n ``unicode`` coercion rules. Unless ``fp.write()`` explicitly\n understands ``unicode`` (as in ``codecs.getwriter()``) this is likely\n to cause an error.\n\n If *check_circular* is false, then the circular reference check\n for container types will be skipped and a circular reference will\n result in an ``OverflowError`` (or worse).\n\n If *allow_nan* is false, then it will be a ``ValueError`` to\n serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)\n in strict compliance of the original JSON specification, instead of using\n the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). See\n *ignore_nan* for ECMA-262 compliant behavior.\n\n If *indent* is a string, then JSON array elements and object members\n will be pretty-printed with a newline followed by that string repeated\n for each level of nesting. ``None`` (the default) selects the most compact\n representation without any newlines. For backwards compatibility with\n versions of simplejson earlier than 2.1.0, an integer is also accepted\n and is converted to a string with that many spaces.\n\n If specified, *separators* should be an\n ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``\n if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most\n compact JSON representation, you should specify ``(',', ':')`` to eliminate\n whitespace.\n\n *encoding* is the character encoding for str instances, default is UTF-8.\n\n *default(obj)* is a function that should return a serializable version\n of obj or raise ``TypeError``. The default simply raises ``TypeError``.\n\n If *use_decimal* is true (default: ``True``) then decimal.Decimal\n will be natively serialized to JSON with full precision.\n\n If *namedtuple_as_object* is true (default: ``True``),\n :class:`tuple` subclasses with ``_asdict()`` methods will be encoded\n as JSON objects.\n\n If *tuple_as_array* is true (default: ``True``),\n :class:`tuple` (and subclasses) will be encoded as JSON arrays.\n\n If *iterable_as_array* is true (default: ``False``),\n any object not in the above table that implements ``__iter__()``\n will be encoded as a JSON array.\n\n If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher\n or lower than -2**53 will be encoded as strings. This is to avoid the\n rounding that happens in Javascript otherwise. Note that this is still a\n lossy operation that will not round-trip correctly and should be used\n sparingly.\n\n If *int_as_string_bitcount* is a positive number (n), then int of size\n greater than or equal to 2**n or lower than or equal to -2**n will be\n encoded as strings.\n\n If specified, *item_sort_key* is a callable used to sort the items in\n each dictionary. This is useful if you want to sort items other than\n in alphabetical order by key. This option takes precedence over\n *sort_keys*.\n\n If *sort_keys* is true (default: ``False``), the output of dictionaries\n will be sorted by item.\n\n If *for_json* is true (default: ``False``), objects with a ``for_json()``\n method will use the return value of that method for encoding as JSON\n instead of the object.\n\n If *ignore_nan* is true (default: ``False``), then out of range\n :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as\n ``null`` in compliance with the ECMA-262 specification. If true, this will\n override *allow_nan*.\n\n To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n ``.default()`` method to serialize additional types), specify it with\n the ``cls`` kwarg. NOTE: You should use *default* or *for_json* instead\n of subclassing whenever possible.\n\n \"\"\"\n if not skipkeys and ensure_ascii and check_circular and allow_nan and (cls is None) and (indent is None) and (separators is None) and (encoding == 'utf-8') and (default is None) and use_decimal and namedtuple_as_object and tuple_as_array and (not iterable_as_array) and (not bigint_as_string) and (not sort_keys) and (not item_sort_key) and (not for_json) and (not ignore_nan) and (int_as_string_bitcount is None) and (not kw):\n iterable = _default_encoder.iterencode(obj)\n else:\n if cls is None:\n cls = JSONEncoder\n iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, iterable_as_array=iterable_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, int_as_string_bitcount=int_as_string_bitcount, **kw).iterencode(obj)\n for chunk in iterable:\n fp.write(chunk)", "context": "def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef _import_OrderedDict(): ...\ndef _import_c_make_encoder(): ...\ndef dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): ...\ndef loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): ...\ndef _toggle_speedups(enabled): ...\ndef simple_first(kv): ...\n", "repository": "gladed/zenchart", "test_name": "test_namedtuple_dump", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001750.py"} {"focal_file": "acmapi/resources.py", "focal_class": null, "focal_method": "post", "tests": "import unittest\n\nclass Test_post(unittest.TestCase):\n @freeze_time('2012-01-14 12:00:01')\n def test_add_valid_post(self):\n with self.app.test_client() as client:\n response = client.post('http://localhost:5000/people/', headers=HEADERS, data={'username': 'bob', 'name': 'Bob Billy', 'email': 'bbob@example.com', 'website': 'http://bbob.example.com', 'password': 'password1234'})\n response = client.post('http://localhost:5000/posts/', headers=HEADERS, data={'title': 'Title A', 'description': 'Description A', 'content': 'This is Post 1 content'})\n self.assertEqual(json.loads(response.data), {'title': 'Title A', 'description': 'Description A', 'content': 'This is Post 1 content', 'edited_at': '2012-01-14 12:00:01.000000', 'editor': 'http://localhost:5000/people/1', 'editor_id': 1, 'hidden': False, 'post_id': 1, 'revision': 1})\n\n @freeze_time('2012-01-14 12:00:01')\n def test_edit_valid_post(self):\n with self.app.test_client() as client:\n response = client.post('http://localhost:5000/people/', headers=HEADERS, data={'username': 'bob', 'name': 'Bob Billy', 'email': 'bbob@example.com', 'website': 'http://bbob.example.com', 'password': 'password1234'})\n response = client.post('http://localhost:5000/posts/', headers=HEADERS, data={'title': 'Title A', 'description': 'Description A', 'content': 'This is Post 1 content'})\n response = client.put('http://localhost:5000/posts/1', headers=HEADERS, data={'title': 'Title B', 'description': 'Description B', 'content': 'This is Post 1 content'})\n self.assertEqual(json.loads(response.data), {'title': 'Title B', 'description': 'Description B', 'content': 'This is Post 1 content', 'edited_at': '2012-01-14 12:00:01.000000', 'editor': 'http://localhost:5000/people/1', 'editor_id': 1, 'hidden': False, 'post_id': 1, 'revision': 2})\n response = client.get('http://localhost:5000/posts/1', data={'title': 'Title B', 'description': 'Description B', 'content': 'This is Post 1 content'})\n self.assertEqual(json.loads(response.data), {'page': 1, 'pagesize': 10, 'nextpage': None, 'posts': [{'title': 'Title A', 'description': 'Description A', 'content': 'This is Post 1 content', 'edited_at': '2012-01-14 12:00:01.000000', 'editor': 'http://localhost:5000/people/1', 'editor_id': 1, 'hidden': False, 'post_id': 1, 'revision': 1}, {'title': 'Title B', 'description': 'Description B', 'content': 'This is Post 1 content', 'edited_at': '2012-01-14 12:00:01.000000', 'editor': 'http://localhost:5000/people/1', 'editor_id': 1, 'hidden': False, 'post_id': 1, 'revision': 2}]})\n", "method_code": " def post(self):\n \"\"\" To add a resource \"\"\"\n DB.create_all()\n parser = reqparse.RequestParser(argument_class=CustomArgument)\n parser.add_argument('title', type=str)\n parser.add_argument('description', type=str)\n parser.add_argument('location', type=str)\n parser.add_argument('hidden', type=bool, default=False)\n parser.add_argument('canceled', type=bool, default=False)\n parser.add_argument('speaker', type=str)\n parser.add_argument('location', type=str)\n parser.add_argument('start', type=datetime_type, required=True)\n parser.add_argument('end', type=datetime_type, required=True)\n parser.add_argument('page', type=int, default=1)\n parser.add_argument('pagesize', type=int)\n args = parser.parse_args()\n list_id, = DB.session.query(sqlalchemy.func.max(models.Event.list)).first()\n event = models.Event.create(title=args.title, description=args.description, location=args.location, speaker=args.speaker, hidden=args.hidden, canceled=args.canceled, start=args.start, end=args.end, editor=flask.g.person, edited_datetime=datetime.datetime.now(), index=1, list=list_id + 1 if list_id else 1)\n DB.session.add(event)\n DB.session.commit()\n return marshal(event, fields.event_fields)\n ", "context": "class Events(restful.Resource):\n @AUTH.login_required\n def post(self): ...\n def get(self, event_id=None): ...\n def put(self, event_id): ...\n", "repository": "pdxacm/acmapi", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001751.py"} {"focal_file": "acmapi/resources.py", "focal_class": null, "focal_method": "delete", "tests": "import unittest\n\nclass Test_delete(unittest.TestCase):\n @freeze_time('2012-01-14 12:00:01')\n def test_invalid_delete(self):\n with self.app.test_client() as client:\n response = client.delete('http://localhost:5000/people/', headers=HEADERS)\n self.assertEqual(json.loads(response.data), {u'exception': u'LookupError', u'message': u'person not found'})\n response = client.get('http://localhost:5000/people/')\n self.assertEqual(json.loads(response.data), {'page': 1, 'pagesize': 10, 'nextpage': None, 'people': [{'id': 1, 'username': 'root', 'name': None, 'email': None, 'website': None, 'gravatar_email': None, 'gravatar_id': None, 'avatar_url': None}]})\n", "method_code": " def delete(self, person_id=None, username=None):\n DB.create_all()\n if person_id or username:\n if person_id:\n person = queries.person_id(person_id)\n else:\n person = queries.person_username(username)\n else:\n person = None\n if person:\n DB.session.delete(person)\n DB.session.commit()\n return {'message': 'delete successful'}\n else:\n _handle_error(LookupError('person not found'))\n ", "context": "class People(restful.Resource):\n @AUTH.login_required\n def delete(self, person_id=None, username=None): ...\n def get(self, person_id=None, username=None): ...\n def post(self): ...\n def put(self, person_id=None, username=None): ...\n", "repository": "pdxacm/acmapi", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001752.py"} {"focal_file": "pybold/sequence.py", "focal_class": null, "focal_method": "get_process_ids", "tests": "import unittest\n\nclass Test_get_process_ids(unittest.TestCase):\n def test_get_process_ids(self):\n self.sequences_client.get(ids='|'.join(self.process_ids))\n process_ids = self.sequences_client.get_process_ids()\n self.assertIsInstance(process_ids, list, 'SequencesClient.get_process_ids should return a list of process ids')\n for process_id in process_ids:\n self.assertIn(process_id, self.process_ids, 'Returned sequence process_id ({}) was not part of original search criteria'.format(process_id))\n", "method_code": " def get_process_ids(self):\n \"\"\"Return a list of process IDs for the fetched sequences\"\"\"\n ids = []\n for sequence in self.sequence_list:\n ids.append(sequence.process_id)\n return ids\n ", "context": "class SequencesClient(Endpoint):\n def get_process_ids(self): ...\n def __init__(self, base_url=PUBLIC_API_URL): ...\n def get(self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, marker=None, timeout=5): ...\n def get_specimens(self): ...\n def get_tracefiles(self): ...\n\n self.base_url = base_url\n self.sequence_list = []\n\n ENDPOINT_NAME = 'sequence'\n", "repository": "AAFC-BICoE/pybold", "test_name": "test_get_process_ids", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001753.py"} {"focal_file": "pybold/sequence.py", "focal_class": null, "focal_method": "get_specimens", "tests": "import unittest\n\nclass Test_get_specimens(unittest.TestCase):\n def test_get_specimens(self):\n self.sequences_client.get(ids='|'.join(self.process_ids))\n specimen_list = self.sequences_client.get_specimens()\n self.assertIsInstance(specimen_list, list, 'SequencesClient.get_specimens() should return a list of Specimen.')\n for specimen in specimen_list:\n self.assertIsInstance(specimen, pybold.specimen.Specimen, 'SequencesClient.get_specimens() should return a list of Specimen.')\n", "method_code": " def get_specimens(self):\n \"\"\"Lookup and return Specimen objects for fetched sequences based on the process IDs\"\"\"\n ids_query = '|'.join(self.get_process_ids())\n return pybold.specimen.SpecimensClient(self.base_url).get(ids=ids_query)\n ", "context": "class SequencesClient(Endpoint):\n def get_specimens(self): ...\n def __init__(self, base_url=PUBLIC_API_URL): ...\n def get(self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, marker=None, timeout=5): ...\n def get_process_ids(self): ...\n def get_tracefiles(self): ...\n\n self.base_url = base_url\n self.sequence_list = []\n\n ENDPOINT_NAME = 'sequence'\n", "repository": "AAFC-BICoE/pybold", "test_name": "test_get_specimens", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001754.py"} {"focal_file": "pybold/sequence.py", "focal_class": null, "focal_method": "get_tracefiles", "tests": "import unittest\n\nclass Test_get_tracefiles(unittest.TestCase):\n def test_get_tracefiles(self):\n self.sequences_client.get(ids='|'.join(self.process_ids))\n tracefiles = self.sequences_client.get_tracefiles()\n self.assertIsInstance(tracefiles, list, 'SequencesClient.get_tracefiles() should return a list of Tracefile.')\n for tracefile in tracefiles:\n self.assertIsInstance(tracefile, pybold.tracefile.Tracefile, 'SequencesClient.get_tracefiles() should return a list of Tracefile.')\n", "method_code": " def get_tracefiles(self):\n \"\"\"Lookup and return Tracefile objects for fetched sequences based on the process IDs\"\"\"\n ids_query = '|'.join(self.get_process_ids())\n return pybold.tracefile.TracefilesClient(self.base_url).get(ids=ids_query)\n ", "context": "class SequencesClient(Endpoint):\n def get_tracefiles(self): ...\n def __init__(self, base_url=PUBLIC_API_URL): ...\n def get(self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, marker=None, timeout=5): ...\n def get_process_ids(self): ...\n def get_specimens(self): ...\n\n self.base_url = base_url\n self.sequence_list = []\n\n ENDPOINT_NAME = 'sequence'\n", "repository": "AAFC-BICoE/pybold", "test_name": "test_get_tracefiles", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001755.py"} {"focal_file": "pybold/specimen.py", "focal_class": null, "focal_method": "get_taxonomies", "tests": "import unittest\n\nclass Test_get_taxonomies(unittest.TestCase):\n def test_get_taxonomies(self):\n self.specimen_client.get(ids='|'.join(self.process_ids))\n specimen_taxonomies = self.specimen_client.get_taxonomies()\n self.assertIsInstance(specimen_taxonomies, dict, 'SpecimensClient.get_taxonomies() should return a dictionary with process ID keys and taxonomy dictionary values.')\n for process_id, taxonomy in specimen_taxonomies.iteritems():\n self.assertIn(process_id, self.process_ids, 'Process ID {} was not in the dictionary returned by SpecimensClient.get_taxonomies().'.format(process_id))\n self.assertIsInstance(taxonomy, dict, \"The dictionary's values returned by SpecimensClient.get_taxonomies() are not dictionaries.\")\n", "method_code": " def get_taxonomies(self):\n \"\"\"Return list of taxonomies of fetched specimen\"\"\"\n taxonomies = {}\n for specimen in self.specimen_list:\n taxonomies[specimen.process_id] = specimen.taxonomy\n return taxonomies\n ", "context": "class SpecimensClient(Endpoint):\n def get_taxonomies(self): ...\n def __init__(self, base_url=PUBLIC_API_URL): ...\n def get(self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, timeout=5): ...\n def get_record_ids(self): ...\n def get_process_ids(self): ...\n def get_sequences(self): ...\n def get_tracefiles(self): ...\n\n self.base_url = base_url\n self.specimen_list = []\n\n ENDPOINT_NAME = 'specimen'\n", "repository": "AAFC-BICoE/pybold", "test_name": "test_get_taxonomies", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001756.py"} {"focal_file": "pybold/specimen.py", "focal_class": null, "focal_method": "get_record_ids", "tests": "import unittest\n\nclass Test_get_record_ids(unittest.TestCase):\n def test_get_record_ids(self):\n self.specimen_client.get(ids='|'.join(self.process_ids))\n record_ids = self.specimen_client.get_record_ids()\n self.assertIsInstance(record_ids, list, 'SpecimensClient.get_record_ids() should return a list of record ids.')\n", "method_code": " def get_record_ids(self):\n \"\"\"Return list of record IDs of fetched specimen\"\"\"\n ids = []\n for specimen in self.specimen_list:\n ids.append(specimen.record_id)\n return ids\n ", "context": "class SpecimensClient(Endpoint):\n def get_record_ids(self): ...\n def __init__(self, base_url=PUBLIC_API_URL): ...\n def get(self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, timeout=5): ...\n def get_taxonomies(self): ...\n def get_process_ids(self): ...\n def get_sequences(self): ...\n def get_tracefiles(self): ...\n\n self.base_url = base_url\n self.specimen_list = []\n\n ENDPOINT_NAME = 'specimen'\n", "repository": "AAFC-BICoE/pybold", "test_name": "test_get_record_ids", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001757.py"} {"focal_file": "pybold/specimen.py", "focal_class": null, "focal_method": "get_process_ids", "tests": "import unittest\n\nclass Test_get_process_ids(unittest.TestCase):\n def test_get_process_ids(self):\n self.specimen_client.get(ids='|'.join(self.process_ids))\n process_ids = self.specimen_client.get_process_ids()\n self.assertIsInstance(process_ids, list, 'SpecimensClient.get_process_ids() should return a list of process ids.')\n for process_id in process_ids:\n self.assertIn(process_id, self.process_ids, 'Returned specimen process_id ({}) was not part of original search criteria'.format(process_id))\n\n def test_get_process_ids(self):\n self.tracefiles_client.get(ids='|'.join(self.process_ids))\n process_ids = self.tracefiles_client.get_process_ids()\n for process_id in process_ids:\n self.assertIn(process_id, self.process_ids, 'Returned tracefile process_id ({}) was not part of original search criteria'.format(process_id))\n", "method_code": " def get_process_ids(self):\n \"\"\"Return list of process IDs of fetched specimen\"\"\"\n ids = []\n for specimen in self.specimen_list:\n ids.append(specimen.process_id)\n return ids\n ", "context": "class SpecimensClient(Endpoint):\n def get_process_ids(self): ...\n def __init__(self, base_url=PUBLIC_API_URL): ...\n def get(self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, timeout=5): ...\n def get_taxonomies(self): ...\n def get_record_ids(self): ...\n def get_sequences(self): ...\n def get_tracefiles(self): ...\n\n self.base_url = base_url\n self.specimen_list = []\n\n ENDPOINT_NAME = 'specimen'\n", "repository": "AAFC-BICoE/pybold", "test_name": "test_get_process_ids", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001758.py"} {"focal_file": "pybold/specimen.py", "focal_class": null, "focal_method": "get_sequences", "tests": "import unittest\n\nclass Test_get_sequences(unittest.TestCase):\n def test_sequences(self):\n self.specimen_client.get(ids='|'.join(self.process_ids))\n sequences = self.specimen_client.get_sequences()\n self.assertIsInstance(sequences, list, 'SpecimensClient.get_sequences() should return a list of Sequence.')\n for sequence in sequences:\n self.assertIsInstance(sequence, pybold.sequence.Sequence, 'SpecimensClient.get_sequences() should return a list of Sequence.')\n\n def test_get_sequences(self):\n self.tracefiles_client.get(ids='|'.join(self.process_ids))\n sequences = self.tracefiles_client.get_sequences()\n self.assertIsInstance(sequences, list, 'TracefilesClient.get_sequences() should return a list of Sequence.')\n for sequence in sequences:\n self.assertIsInstance(sequence, pybold.sequence.Sequence, 'TracefilesClient.get_sequences() should return a list of Sequence.')\n", "method_code": " def get_sequences(self):\n \"\"\"Return Sequence objects for fetched specimen based on the process IDs\"\"\"\n ids_query = '|'.join(self.get_process_ids())\n return pybold.sequence.SequencesClient(self.base_url).get(ids=ids_query)\n ", "context": "class SpecimensClient(Endpoint):\n def get_sequences(self): ...\n def __init__(self, base_url=PUBLIC_API_URL): ...\n def get(self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, timeout=5): ...\n def get_taxonomies(self): ...\n def get_record_ids(self): ...\n def get_process_ids(self): ...\n def get_tracefiles(self): ...\n\n self.base_url = base_url\n self.specimen_list = []\n\n ENDPOINT_NAME = 'specimen'\n", "repository": "AAFC-BICoE/pybold", "test_name": "test_sequences", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001759.py"} {"focal_file": "pybold/specimen.py", "focal_class": null, "focal_method": "get_tracefiles", "tests": "import unittest\n\nclass Test_get_tracefiles(unittest.TestCase):\n def test_get_tracefiles(self):\n self.specimen_client.get(ids='|'.join(self.process_ids))\n tracefiles = self.specimen_client.get_tracefiles()\n self.assertIsInstance(tracefiles, list, 'SpecimensClient.get_tracefiles() should return a list of Tracefile.')\n for tracefile in tracefiles:\n self.assertIsInstance(tracefile, pybold.tracefile.Tracefile, 'SpecimensClient.get_tracefiles() should return a list of Tracefile.')\n", "method_code": " def get_tracefiles(self):\n \"\"\"Return Tracefile objects for fetched specimen based on the process IDs\"\"\"\n ids_query = '|'.join(self.get_process_ids())\n return pybold.tracefile.TracefilesClient(self.base_url).get(ids=ids_query)\n ", "context": "class SpecimensClient(Endpoint):\n def get_tracefiles(self): ...\n def __init__(self, base_url=PUBLIC_API_URL): ...\n def get(self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, timeout=5): ...\n def get_taxonomies(self): ...\n def get_record_ids(self): ...\n def get_process_ids(self): ...\n def get_sequences(self): ...\n\n self.base_url = base_url\n self.specimen_list = []\n\n ENDPOINT_NAME = 'specimen'\n", "repository": "AAFC-BICoE/pybold", "test_name": "test_get_tracefiles", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001760.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "get_asg_tag", "tests": "import unittest\n\nclass Test_get_asg_tag(unittest.TestCase):\n def test_get_asg_tag(self):\n tags = [{'ResourceId': 'string', 'ResourceType': 'string', 'Key': 'eks-rolling-update:desired_capacity', 'Value': '6', 'PropagateAtLaunch': True}]\n response = get_asg_tag(tags, 'eks-rolling-update:desired_capacity')\n self.assertEqual(response, tags[0])\n\n def test_get_asg_tag_fail(self):\n tags = [{'ResourceId': 'string', 'ResourceType': 'string', 'Key': 'eks-rolling-update:desired_capacity', 'Value': '6', 'PropagateAtLaunch': True}]\n response = get_asg_tag(tags, 'foo')\n self.assertEqual(response, {})\n", "method_code": "def get_asg_tag(tags, tag_name):\n \"\"\"\n Returns a tag on a list of asg tags\n \"\"\"\n result = {}\n for tag in tags:\n for key, val in tag.items():\n if val == tag_name:\n result = tag\n return result", "context": "def get_asg_tag(tags, tag_name): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_get_asg_tag", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001761.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "instance_outdated_launchconfiguration", "tests": "import unittest\n\nclass Test_instance_outdated_launchconfiguration(unittest.TestCase):\n def test_is_instance_outdated(self):\n client = boto3.client('autoscaling')\n response = client.describe_auto_scaling_groups(AutoScalingGroupNames=['mock-asg'])\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n self.assertFalse(instance_outdated_launchconfiguration(instances[0], 'mock-lc-01'))\n\n def test_is_instance_outdated_fail(self):\n response = self.aws_response_mock_unhealthy\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n self.assertTrue(instance_outdated_launchconfiguration(instances[0], 'mock-lc-01'))\n", "method_code": "def instance_outdated_launchconfiguration(instance_obj, asg_lc_name):\n \"\"\"\n Checks that the launch configuration on an instance matches a given string\n \"\"\"\n lc_name = instance_obj.get('LaunchConfigurationName')\n instance_id = instance_obj['InstanceId']\n if lc_name != asg_lc_name:\n logger.info(\"Instance id {} launch config of '{}' does not match asg launch config of '{}'\".format(instance_id, lc_name, asg_lc_name))\n return True\n else:\n logger.info('Instance id {} : OK '.format(instance_id))\n return False", "context": "def instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_is_instance_outdated", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001762.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "count_all_cluster_instances", "tests": "import unittest\n\nclass Test_count_all_cluster_instances(unittest.TestCase):\n def test_count_all_cluster_instances(self):\n count = count_all_cluster_instances('mock-cluster')\n self.assertEqual(count, 3)\n\n def test_count_all_cluster_instances_fail(self):\n count = count_all_cluster_instances('foo-bar')\n self.assertEqual(count, 0)\n", "method_code": "def count_all_cluster_instances(cluster_name, predictive=False):\n \"\"\"\n Returns the total number of ec2 instances in a k8s cluster\n \"\"\"\n count = 0\n asgs = get_all_asgs(cluster_name)\n for asg in asgs:\n if predictive:\n count += asg['DesiredCapacity']\n else:\n count += len(asg['Instances'])\n logger.info('{} asg instance count in cluster is: {}. K8s node count should match this number'.format('*** Predicted' if predictive else 'Current', count))\n return count", "context": "def count_all_cluster_instances(cluster_name, predictive=False): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_count_all_cluster_instances", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001763.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "is_asg_healthy", "tests": "import unittest\n\nclass Test_is_asg_healthy(unittest.TestCase):\n def test_is_asg_healthy(self):\n result = is_asg_healthy('mock-asg', 2, 1)\n self.assertTrue(result)\n\n def test_is_asg_healthy_fail(self):\n with patch('eksrollup.lib.aws.client.describe_auto_scaling_groups') as describe_auto_scaling_groups_mock:\n describe_auto_scaling_groups_mock.return_value = self.aws_response_mock_unhealthy\n result = is_asg_healthy('mock-asg', 2, 1)\n self.assertFalse(result)\n", "method_code": "def is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']):\n \"\"\"\n Checks that all instances in an ASG have a HealthStatus of healthy. Returns False if not\n \"\"\"\n retry_count = 1\n asg_healthy = False\n while retry_count < max_retry:\n asg_healthy = True\n retry_count += 1\n logger.info('Checking asg {} instance health...'.format(asg_name))\n response = client.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name], MaxRecords=1)\n instances = response['AutoScalingGroups'][0]['Instances']\n for instance in instances:\n logger.info('Instance {} - {}'.format(instance['InstanceId'], instance['HealthStatus']))\n if instance['HealthStatus'] != 'Healthy':\n asg_healthy = False\n if asg_healthy:\n break\n time.sleep(wait)\n else:\n logger.info('asg {} - Healthy.'.format(asg_name))\n return asg_healthy", "context": "def is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_is_asg_healthy", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001764.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "is_asg_scaled", "tests": "import unittest\n\nclass Test_is_asg_scaled(unittest.TestCase):\n def test_is_asg_scaled(self):\n self.assertTrue(is_asg_scaled('mock-asg', 3))\n", "method_code": "def is_asg_scaled(asg_name, desired_capacity):\n \"\"\"\n Checks that the number of EC2 instances in an ASG matches desired capacity\n \"\"\"\n logger.info('Checking asg {} instance count...'.format(asg_name))\n response = client.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name], MaxRecords=1)\n actual_instances = response['AutoScalingGroups'][0]['Instances']\n if len(actual_instances) != desired_capacity:\n logger.info('Asg {} does not have enough running instances to proceed'.format(asg_name))\n logger.info('Actual instances: {} Desired instances: {}'.format(len(actual_instances), desired_capacity))\n is_scaled = False\n else:\n logger.info('Asg {} scaled OK'.format(asg_name))\n logger.info('Actual instances: {} Desired instances: {}'.format(len(actual_instances), desired_capacity))\n is_scaled = True\n return is_scaled", "context": "def is_asg_scaled(asg_name, desired_capacity): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_is_asg_scaled", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001765.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "modify_aws_autoscaling", "tests": "import unittest\n\nclass Test_modify_aws_autoscaling(unittest.TestCase):\n def test_modify_aws_autoscaling_suspend(self):\n response = modify_aws_autoscaling('mock-asg', 'suspend')\n status_code = response['ResponseMetadata']['HTTPStatusCode']\n self.assertEqual(status_code, 200)\n\n def test_modify_aws_autoscaling_fail(self):\n with self.assertRaises(Exception):\n modify_aws_autoscaling('mock-asg', 'foo')\n", "method_code": "def modify_aws_autoscaling(asg_name, action):\n \"\"\"\n Suspends or resumes ASG autoscaling\n \"\"\"\n logger.info('Modifying asg {} autoscaling to {} ...'.format(asg_name, action))\n if not app_config['DRY_RUN']:\n if action == 'suspend':\n response = client.suspend_processes(AutoScalingGroupName=asg_name, ScalingProcesses=['Launch', 'ReplaceUnhealthy'])\n elif action == 'resume':\n response = client.resume_processes(AutoScalingGroupName=asg_name, ScalingProcesses=['Launch', 'ReplaceUnhealthy'])\n else:\n logger.info('Invalid scaling option')\n raise Exception('Invalid scaling option')\n if response['ResponseMetadata']['HTTPStatusCode'] != requests.codes.ok:\n logger.info('AWS asg modification operation did not succeed. Exiting.')\n raise Exception('AWS asg modification operation did not succeed. Exiting.')\n else:\n logger.info('Skipping asg modification due to dry run flag set')\n response = {'message': 'dry run only'}\n return response", "context": "def modify_aws_autoscaling(asg_name, action): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_modify_aws_autoscaling_suspend", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001766.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "save_asg_tags", "tests": "import unittest\n\nclass Test_save_asg_tags(unittest.TestCase):\n def test_save_asg_tags(self):\n response = save_asg_tags('mock-asg', 'foo', 'bar')\n status_code = response['ResponseMetadata']['HTTPStatusCode']\n self.assertEqual(status_code, 200)\n", "method_code": "def save_asg_tags(asg_name, key, value):\n \"\"\"\n Adds a tag to asg for later retrieval\n \"\"\"\n logger.info('Saving tag to asg key: {}, value : {}...'.format(key, value))\n if not app_config['DRY_RUN']:\n response = client.create_or_update_tags(Tags=[{'Key': key, 'Value': str(value), 'ResourceId': asg_name, 'ResourceType': 'auto-scaling-group', 'PropagateAtLaunch': False}])\n if response['ResponseMetadata']['HTTPStatusCode'] != requests.codes.ok:\n logger.info('AWS asg tag modification operation did not succeed. Exiting.')\n raise Exception('AWS asg tag modification operation did not succeed. Exiting.')\n else:\n logger.info('Skipping asg tag modification due to dry run flag set')\n response = {'message': 'dry run only'}\n return response", "context": "def save_asg_tags(asg_name, key, value): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_save_asg_tags", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001767.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "delete_asg_tags", "tests": "import unittest\n\nclass Test_delete_asg_tags(unittest.TestCase):\n def test_delete_asg_tags(self):\n with self.assertRaises(NotImplementedError):\n delete_asg_tags('mock-asg', 'foo')\n", "method_code": "def delete_asg_tags(asg_name, key):\n \"\"\"\n Deletes a tag from asg\n \"\"\"\n logger.info('Deleting tag from asg key: {}...'.format(key))\n if not app_config['DRY_RUN']:\n response = client.delete_tags(Tags=[{'Key': key, 'ResourceId': asg_name, 'ResourceType': 'auto-scaling-group'}])\n if response['ResponseMetadata']['HTTPStatusCode'] != requests.codes.ok:\n logger.info('AWS asg tag modification operation did not succeed. Exiting.')\n raise Exception('AWS asg tag modification operation did not succeed. Exiting.')\n else:\n logger.info('Skipping asg tag modification due to dry run flag set')\n response = {'message': 'dry run only'}\n return response", "context": "def delete_asg_tags(asg_name, key): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_delete_asg_tags", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001768.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "instance_terminated", "tests": "import unittest\n\nclass Test_instance_terminated(unittest.TestCase):\n def test_instance_terminated(self):\n with patch('eksrollup.lib.aws.ec2_client.describe_instances') as describe_instances_mock:\n describe_instances_mock.return_value = self.aws_response_mock_terminated\n self.assertTrue(instance_terminated(self.instance_id, 2, 1))\n\n def test_instance_shutting_down(self):\n with patch('eksrollup.lib.aws.ec2_client.describe_instances') as describe_instances_mock:\n describe_instances_mock.return_value = self.aws_response_mock_shutting_down\n self.assertTrue(instance_terminated(self.instance_id, 2, 1, True))\n\n def test_instance_terminated_fail(self):\n self.assertFalse(instance_terminated(self.instance_id, 2, 1))\n", "method_code": "def instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']):\n \"\"\"\n Checks that an ec2 instance is terminated or stopped given an InstanceID\n Overridable to detect shutting-down or stopped states\n \"\"\"\n retry_count = 1\n is_instance_terminated = False\n while retry_count < max_retry:\n logger.info('Checking instance {} is terminated...'.format(instance_id))\n retry_count += 1\n response = ec2_client.describe_instances(InstanceIds=[instance_id])\n state = response['Reservations'][0]['Instances'][0]['State']\n stop_states = ['terminated', 'stopped']\n stopping_states = ['shutting-down', 'stopping']\n if state['Name'] in stop_states or (wait_for_stopping and state['Name'] in stopping_states):\n logger.info('Instance {} {}!'.format(instance_id, state['Name']))\n is_instance_terminated = True\n break\n else:\n is_instance_terminated = False\n logger.info('Instance {} is {}, checking again...'.format(instance_id, state['Name']))\n time.sleep(wait)\n return is_instance_terminated", "context": "def instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_instance_terminated", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001769.py"} {"focal_file": "eksrollup/lib/aws.py", "focal_class": null, "focal_method": "instance_outdated_launchtemplate", "tests": "import unittest\n\nclass Test_instance_outdated_launchtemplate(unittest.TestCase):\n def test_is_instance_outdated(self):\n response = self.aws_response_mock\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n self.assertFalse(instance_outdated_launchtemplate(instances[0], 'mock-lt-01', '2'))\n\n def test_is_instance_outdated_fail_name(self):\n response = self.aws_response_mock\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n self.assertTrue(instance_outdated_launchtemplate(instances[1], 'mock-lt-01', '2'))\n\n def test_is_instance_outdated_fail_version_number(self):\n response = self.aws_response_mock\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n self.assertTrue(instance_outdated_launchtemplate(instances[2], 'mock-lt-01', '2'))\n\n def test_is_instance_outdated_fail_version_default(self):\n response = self.aws_response_mock_default\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n with patch('eksrollup.lib.aws.get_launch_template') as get_launch_template_mock:\n get_launch_template_mock.return_value = self.mock_get_launch_template\n self.assertTrue(instance_outdated_launchtemplate(instances[0], 'mock-lt-01', '$Default'))\n\n def test_is_instance_outdated_pass_version_default(self):\n response = self.aws_response_mock_default\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n with patch('eksrollup.lib.aws.get_launch_template') as get_launch_template_mock:\n get_launch_template_mock.return_value = self.mock_get_launch_template\n self.assertFalse(instance_outdated_launchtemplate(instances[2], 'mock-lt-01', '$Default'))\n\n def test_is_instance_outdated_pass_version_latest(self):\n response = self.aws_response_mock_latest\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n with patch('eksrollup.lib.aws.get_launch_template') as get_launch_template_mock:\n get_launch_template_mock.return_value = self.mock_get_launch_template\n self.assertFalse(instance_outdated_launchtemplate(instances[0], 'mock-lt-01', '$Latest'))\n\n def test_is_instance_outdated_fail_version_latest(self):\n response = self.aws_response_mock_latest\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n with patch('eksrollup.lib.aws.get_launch_template') as get_launch_template_mock:\n get_launch_template_mock.return_value = self.mock_get_launch_template\n self.assertTrue(instance_outdated_launchtemplate(instances[2], 'mock-lt-01', '$Latest'))\n\n def test_is_instance_outdated_fail_no_launch_template(self):\n response = self.aws_response_mock_no_launch_template\n asgs = response['AutoScalingGroups']\n for asg in asgs:\n instances = asg['Instances']\n with patch('eksrollup.lib.aws.get_launch_template') as get_launch_template_mock:\n get_launch_template_mock.return_value = self.mock_get_launch_template\n self.assertTrue(instance_outdated_launchtemplate(instances[0], 'mock-lt-01', '$Latest'))\n", "method_code": "def instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version):\n \"\"\"\n Checks that the launch template on an instance matches a given string and version. This is often configured in the\n auto scaling group as $Latest or $Default which we can resolve to an actual version number through the\n describe_launch_templates boto3 method (wrapped in get_launch_template).\n \"\"\"\n instance_id = instance_obj['InstanceId']\n try:\n lt_name = instance_obj['LaunchTemplate']['LaunchTemplateName']\n lt_version = int(instance_obj['LaunchTemplate']['Version'])\n except KeyError:\n logger.info(\"Instance id {} missing launch template does not match asg launch template of '{}'\".format(instance_id, asg_lt_name))\n return True\n if lt_name != asg_lt_name:\n logger.info(\"Instance id {} launch template of '{}' does not match asg launch template of '{}'\".format(instance_id, lt_name, asg_lt_name))\n return True\n elif asg_lt_version == '$Latest':\n latest_lt_version = get_launch_template(asg_lt_name)['LatestVersionNumber']\n if lt_version != latest_lt_version:\n logger.info(\"Instance id {} launch template version of '{}' does not match asg launch template version of '{}'\".format(instance_id, lt_version, latest_lt_version))\n return True\n elif asg_lt_version == '$Default':\n default_lt_version = get_launch_template(asg_lt_name)['DefaultVersionNumber']\n if lt_version != default_lt_version:\n logger.info(\"Instance id {} launch template version of '{}' does not match asg launch template version of '{}'\".format(instance_id, lt_version, default_lt_version))\n return True\n elif lt_version != int(asg_lt_version):\n logger.info(f'Instance id {instance_id} has a different launch configuration version to the ASG')\n return True\n logger.info('Instance id {} : OK '.format(instance_id))\n return False", "context": "def instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef get_all_asgs(cluster_tag): ...\ndef get_asgs(cluster_tag, asg_names=app_config['ASG_NAMES']): ...\ndef get_launch_template(lt_name): ...\ndef terminate_instance_in_asg(instance_id): ...\ndef is_asg_healthy(asg_name, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef is_asg_scaled(asg_name, desired_capacity): ...\ndef modify_aws_autoscaling(asg_name, action): ...\ndef scale_asg(asg_name, current_desired_capacity, new_desired_capacity, new_max_size): ...\ndef save_asg_tags(asg_name, key, value): ...\ndef delete_asg_tags(asg_name, key): ...\ndef instance_outdated_launchconfiguration(instance_obj, asg_lc_name): ...\ndef instance_outdated_launchtemplate(instance_obj, asg_lt_name, asg_lt_version): ...\ndef instance_outdated_age(instance_id, days_fresh): ...\ndef instance_terminated(instance_id, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT'], wait_for_stopping=app_config['INSTANCE_WAIT_FOR_STOPPING']): ...\ndef plan_asgs(asgs): ...\ndef plan_asgs_older_nodes(asgs): ...\ndef get_asg_tag(tags, tag_name): ...\ndef count_all_cluster_instances(cluster_name, predictive=False): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_is_instance_outdated", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001770.py"} {"focal_file": "eksrollup/lib/k8s.py", "focal_class": null, "focal_method": "ensure_config_loaded", "tests": "import unittest\n\nclass Test_ensure_config_loaded(unittest.TestCase):\n def test_ensure_config_loaded_proxy_default(self):\n ensure_config_loaded()\n self.assertEqual(None, ApiClient().configuration.proxy)\n\n def test_ensure_config_loaded_proxy_prefers_https(self):\n with patch.dict(os.environ, {'HTTPS_PROXY': 'http://localhost:12345', 'HTTP_PROXY': 'http://localhost:6789'}):\n ensure_config_loaded()\n self.assertEqual('http://localhost:12345', ApiClient().configuration.proxy)\n\n def test_ensure_config_loaded_proxy_fallback_to_http(self):\n with patch.dict(os.environ, {'HTTP_PROXY': 'http://localhost:12345'}):\n ensure_config_loaded()\n self.assertEqual('http://localhost:12345', ApiClient().configuration.proxy)\n\n @patch.dict('eksrollup.lib.k8s.app_config', {'K8S_PROXY_BYPASS': True})\n def test_ensure_config_loaded_proxy_not_set_when_no_k8s_set(self):\n with patch.dict(os.environ, {'HTTP_PROXY': 'http://localhost:6789'}):\n ensure_config_loaded()\n self.assertNotEqual('http://localhost:6789', ApiClient().configuration.proxy)\n", "method_code": "def ensure_config_loaded():\n kube_config = os.getenv('KUBECONFIG')\n if kube_config and os.path.isfile(kube_config):\n try:\n config.load_kube_config(context=app_config['K8S_CONTEXT'])\n except config.ConfigException:\n raise Exception('Could not configure kubernetes python client')\n else:\n try:\n config.load_incluster_config()\n except config.ConfigException:\n try:\n config.load_kube_config(context=app_config['K8S_CONTEXT'])\n except config.ConfigException:\n raise Exception('Could not configure kubernetes python client')\n proxy_url = os.getenv('HTTPS_PROXY', os.getenv('HTTP_PROXY', None))\n if proxy_url and (not app_config['K8S_PROXY_BYPASS']):\n logger.info(f'Setting proxy: {proxy_url}')\n client.Configuration._default.proxy = proxy_url", "context": "def ensure_config_loaded(): ...\ndef ensure_config_loaded(): ...\ndef get_k8s_nodes(exclude_node_label_keys=app_config['EXCLUDE_NODE_LABEL_KEYS']): ...\ndef get_node_by_instance_id(k8s_nodes, instance_id): ...\ndef modify_k8s_autoscaler(action): ...\ndef delete_node(node_name): ...\ndef cordon_node(node_name): ...\ndef taint_node(node_name): ...\ndef drain_node(node_name): ...\ndef k8s_nodes_ready(max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef k8s_nodes_count(desired_node_count, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_ensure_config_loaded_proxy_default", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001771.py"} {"focal_file": "eksrollup/lib/k8s.py", "focal_class": null, "focal_method": "k8s_nodes_count", "tests": "import unittest\n\nclass Test_k8s_nodes_count(unittest.TestCase):\n def test_k8s_node_count(self):\n with patch('eksrollup.lib.k8s.get_k8s_nodes') as get_k8s_nodes_mock:\n get_k8s_nodes_mock.return_value = self.k8s_response_mock['items']\n self.assertTrue(k8s_nodes_count(3, 2, 1))\n\n def test_k8s_node_count_fail(self):\n with patch('eksrollup.lib.k8s.get_k8s_nodes') as get_k8s_nodes_mock:\n get_k8s_nodes_mock.return_value = self.k8s_response_mock['items']\n self.assertFalse(k8s_nodes_count(4, 2, 1))\n", "method_code": "def k8s_nodes_count(desired_node_count, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']):\n \"\"\"\n Checks that the number of nodes in k8s cluster matches given desired_node_count\n \"\"\"\n logger.info('Checking k8s expected nodes are online after asg scaled up...')\n retry_count = 1\n nodes_online = False\n while retry_count < max_retry:\n nodes_online = True\n retry_count += 1\n nodes = get_k8s_nodes()\n logger.info('Current k8s node count is {}'.format(len(nodes)))\n if len(nodes) != desired_node_count:\n nodes_online = False\n logger.info('Waiting for k8s nodes to reach count {}...'.format(desired_node_count))\n time.sleep(wait)\n else:\n logger.info('Reached desired k8s node count of {}'.format(len(nodes)))\n break\n return nodes_online", "context": "def k8s_nodes_count(desired_node_count, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef ensure_config_loaded(): ...\ndef get_k8s_nodes(exclude_node_label_keys=app_config['EXCLUDE_NODE_LABEL_KEYS']): ...\ndef get_node_by_instance_id(k8s_nodes, instance_id): ...\ndef modify_k8s_autoscaler(action): ...\ndef delete_node(node_name): ...\ndef cordon_node(node_name): ...\ndef taint_node(node_name): ...\ndef drain_node(node_name): ...\ndef k8s_nodes_ready(max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef k8s_nodes_count(desired_node_count, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_k8s_node_count", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001772.py"} {"focal_file": "eksrollup/lib/k8s.py", "focal_class": null, "focal_method": "get_node_by_instance_id", "tests": "import unittest\n\nclass Test_get_node_by_instance_id(unittest.TestCase):\n def test_get_node_by_instance_id_fail(self):\n with patch('eksrollup.lib.k8s.get_k8s_nodes') as get_k8s_nodes_mock:\n get_k8s_nodes_mock.return_value = self.k8s_response_mock['items']\n with self.assertRaises(Exception):\n get_node_by_instance_id(get_k8s_nodes_mock, 'i-0a000b00000000cdee')\n", "method_code": "def get_node_by_instance_id(k8s_nodes, instance_id):\n \"\"\"\n Returns a K8S node name given an instance id. Expects the output of\n list_nodes as in input\n \"\"\"\n node_name = ''\n logger.info('Searching for k8s node name by instance id...')\n for k8s_node in k8s_nodes:\n if instance_id in k8s_node.spec.provider_id:\n logger.info('InstanceId {} is node {} in kubernetes land'.format(instance_id, k8s_node.metadata.name))\n node_name = k8s_node.metadata.name\n if not node_name:\n logger.info('Could not find a k8s node name for that instance id. Exiting')\n raise Exception('Could not find a k8s node name for that instance id. Exiting')\n return node_name", "context": "def get_node_by_instance_id(k8s_nodes, instance_id): ...\ndef ensure_config_loaded(): ...\ndef get_k8s_nodes(exclude_node_label_keys=app_config['EXCLUDE_NODE_LABEL_KEYS']): ...\ndef get_node_by_instance_id(k8s_nodes, instance_id): ...\ndef modify_k8s_autoscaler(action): ...\ndef delete_node(node_name): ...\ndef cordon_node(node_name): ...\ndef taint_node(node_name): ...\ndef drain_node(node_name): ...\ndef k8s_nodes_ready(max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef k8s_nodes_count(desired_node_count, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_get_node_by_instance_id_fail", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001773.py"} {"focal_file": "eksrollup/lib/k8s.py", "focal_class": null, "focal_method": "k8s_nodes_ready", "tests": "import unittest\n\nclass Test_k8s_nodes_ready(unittest.TestCase):\n def test_k8s_nodes_ready(self):\n with patch('eksrollup.lib.k8s.get_k8s_nodes') as get_k8s_nodes_mock:\n box = Box(self.k8s_response_mock, ordered_box=True)\n get_k8s_nodes_mock.return_value = box['items']\n self.assertTrue(k8s_nodes_ready(2, 1), True)\n\n def test_k8s_nodes_ready_fail(self):\n with patch('eksrollup.lib.k8s.get_k8s_nodes') as get_k8s_nodes_mock:\n box = Box(self.k8s_response_mock_unhealthy, ordered_box=True)\n get_k8s_nodes_mock.return_value = box['items']\n self.assertFalse(k8s_nodes_ready(2, 1), False)\n", "method_code": "def k8s_nodes_ready(max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']):\n \"\"\"\n Checks that all nodes in a cluster are Ready\n \"\"\"\n logger.info('Checking k8s nodes health status...')\n retry_count = 1\n healthy_nodes = False\n while retry_count < max_retry:\n healthy_nodes = True\n retry_count += 1\n nodes = get_k8s_nodes()\n for node in nodes:\n conditions = node.status.conditions\n for condition in conditions:\n if condition.type == 'Ready' and condition.status == 'False':\n logger.info('Node {} is not healthy - Ready: {}'.format(node.metadata.name, condition.status))\n healthy_nodes = False\n elif condition.type == 'Ready' and condition.status == 'True':\n logger.info('Node {}: Ready'.format(node.metadata.name))\n if healthy_nodes:\n logger.info('All k8s nodes are healthy')\n break\n logger.info('Retrying node health...')\n time.sleep(wait)\n return healthy_nodes", "context": "def k8s_nodes_ready(max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef ensure_config_loaded(): ...\ndef get_k8s_nodes(exclude_node_label_keys=app_config['EXCLUDE_NODE_LABEL_KEYS']): ...\ndef get_node_by_instance_id(k8s_nodes, instance_id): ...\ndef modify_k8s_autoscaler(action): ...\ndef delete_node(node_name): ...\ndef cordon_node(node_name): ...\ndef taint_node(node_name): ...\ndef drain_node(node_name): ...\ndef k8s_nodes_ready(max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\ndef k8s_nodes_count(desired_node_count, max_retry=app_config['GLOBAL_MAX_RETRY'], wait=app_config['GLOBAL_HEALTH_WAIT']): ...\n", "repository": "hellofresh/eks-rolling-update", "test_name": "test_k8s_nodes_ready", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001774.py"} {"focal_file": "src/functions.py", "focal_class": null, "focal_method": "log", "tests": "import unittest\n\nclass Test_log(unittest.TestCase):\n def test_log(self):\n self.assertEqual(log('TAG', sys.stdout, 'spam'), '[TAG] spam')\n self.assertEqual(log('TAG', sys.stdout, 'hoge'), '[TAG] hoge')\n", "method_code": "def log(tag, out, obj):\n string = '%-10s %s' % ('[' + tag + ']', str(obj))\n (print >> out, string)\n out.flush()\n return string", "context": "def log(tag, out, obj): ...\ndef fail(error, *args): ...\ndef log(tag, out, obj): ...\n", "repository": "0ncorhynchus/omero_importer", "test_name": "test_log", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001775.py"} {"focal_file": "src/functions.py", "focal_class": null, "focal_method": "fail", "tests": "import unittest\n\nclass Test_fail(unittest.TestCase):\n def test_fail(self):\n with self.assertRaises(IOError) as cm:\n fail(IOError, 36, 'exception message')\n the_exception = cm.exception\n self.assertEqual(the_exception.errno, 36)\n", "method_code": "def fail(error, *args):\n raise error(*args)", "context": "def fail(error, *args): ...\ndef fail(error, *args): ...\ndef log(tag, out, obj): ...\n", "repository": "0ncorhynchus/omero_importer", "test_name": "test_fail", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001776.py"} {"focal_file": "oscars_gae/lib/simplejson/__init__.py", "focal_class": null, "focal_method": "dumps", "tests": "import unittest\n\nclass Test_dumps(unittest.TestCase):\n def test_namedtuple_dumps(self):\n for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:\n d = v._asdict()\n self.assertEqual(d, json.loads(json.dumps(v)))\n self.assertEqual(d, json.loads(json.dumps(v, namedtuple_as_object=True)))\n self.assertEqual(d, json.loads(json.dumps(v, tuple_as_array=False)))\n self.assertEqual(d, json.loads(json.dumps(v, namedtuple_as_object=True, tuple_as_array=False)))\n\n def test_asdict_not_callable_dumps(self):\n for f in CONSTRUCTORS:\n self.assertRaises(TypeError, json.dumps, f(DeadDuck()), namedtuple_as_object=True)\n self.assertEqual(json.dumps(f({})), json.dumps(f(DeadDict()), namedtuple_as_object=True))\n\n def test_tuple_array_dumps(self):\n t = (1, 2, 3)\n expect = json.dumps(list(t))\n self.assertEqual(expect, json.dumps(t))\n self.assertEqual(expect, json.dumps(t, tuple_as_array=True))\n self.assertRaises(TypeError, json.dumps, t, tuple_as_array=False)\n self.assertEqual(expect, json.dumps(t, default=repr))\n self.assertEqual(expect, json.dumps(t, tuple_as_array=True, default=repr))\n self.assertEqual(json.dumps(repr(t)), json.dumps(t, tuple_as_array=False, default=repr))\n", "method_code": "def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw):\n \"\"\"Serialize ``obj`` to a JSON formatted ``str``.\n\n If ``skipkeys`` is false then ``dict`` keys that are not basic types\n (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\n will be skipped instead of raising a ``TypeError``.\n\n If ``ensure_ascii`` is false, then the return value will be a\n ``unicode`` instance subject to normal Python ``str`` to ``unicode``\n coercion rules instead of being escaped to an ASCII ``str``.\n\n If ``check_circular`` is false, then the circular reference check\n for container types will be skipped and a circular reference will\n result in an ``OverflowError`` (or worse).\n\n If ``allow_nan`` is false, then it will be a ``ValueError`` to\n serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in\n strict compliance of the JSON specification, instead of using the\n JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n\n If ``indent`` is a string, then JSON array elements and object members\n will be pretty-printed with a newline followed by that string repeated\n for each level of nesting. ``None`` (the default) selects the most compact\n representation without any newlines. For backwards compatibility with\n versions of simplejson earlier than 2.1.0, an integer is also accepted\n and is converted to a string with that many spaces.\n\n If specified, ``separators`` should be an\n ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``\n if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most\n compact JSON representation, you should specify ``(',', ':')`` to eliminate\n whitespace.\n\n ``encoding`` is the character encoding for str instances, default is UTF-8.\n\n ``default(obj)`` is a function that should return a serializable version\n of obj or raise TypeError. The default simply raises TypeError.\n\n If *use_decimal* is true (default: ``True``) then decimal.Decimal\n will be natively serialized to JSON with full precision.\n\n If *namedtuple_as_object* is true (default: ``True``),\n :class:`tuple` subclasses with ``_asdict()`` methods will be encoded\n as JSON objects.\n\n If *tuple_as_array* is true (default: ``True``),\n :class:`tuple` (and subclasses) will be encoded as JSON arrays.\n\n If *iterable_as_array* is true (default: ``False``),\n any object not in the above table that implements ``__iter__()``\n will be encoded as a JSON array.\n\n If *bigint_as_string* is true (not the default), ints 2**53 and higher\n or lower than -2**53 will be encoded as strings. This is to avoid the\n rounding that happens in Javascript otherwise.\n\n If *int_as_string_bitcount* is a positive number (n), then int of size\n greater than or equal to 2**n or lower than or equal to -2**n will be\n encoded as strings.\n\n If specified, *item_sort_key* is a callable used to sort the items in\n each dictionary. This is useful if you want to sort items other than\n in alphabetical order by key. This option takes precendence over\n *sort_keys*.\n\n If *sort_keys* is true (default: ``False``), the output of dictionaries\n will be sorted by item.\n\n If *for_json* is true (default: ``False``), objects with a ``for_json()``\n method will use the return value of that method for encoding as JSON\n instead of the object.\n\n If *ignore_nan* is true (default: ``False``), then out of range\n :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as\n ``null`` in compliance with the ECMA-262 specification. If true, this will\n override *allow_nan*.\n\n To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n ``.default()`` method to serialize additional types), specify it with\n the ``cls`` kwarg. NOTE: You should use *default* instead of subclassing\n whenever possible.\n\n \"\"\"\n if not skipkeys and ensure_ascii and check_circular and allow_nan and (cls is None) and (indent is None) and (separators is None) and (encoding == 'utf-8') and (default is None) and use_decimal and namedtuple_as_object and tuple_as_array and (not iterable_as_array) and (not bigint_as_string) and (not sort_keys) and (not item_sort_key) and (not for_json) and (not ignore_nan) and (int_as_string_bitcount is None) and (not kw):\n return _default_encoder.encode(obj)\n if cls is None:\n cls = JSONEncoder\n return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, iterable_as_array=iterable_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, int_as_string_bitcount=int_as_string_bitcount, **kw).encode(obj)", "context": "def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef _import_OrderedDict(): ...\ndef _import_c_make_encoder(): ...\ndef dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): ...\ndef loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): ...\ndef _toggle_speedups(enabled): ...\ndef simple_first(kv): ...\n", "repository": "0x0ece/oscars2016", "test_name": "test_namedtuple_dumps", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001777.py"} {"focal_file": "oscars_gae/lib/simplejson/__init__.py", "focal_class": null, "focal_method": "dump", "tests": "import unittest\n\nclass Test_dump(unittest.TestCase):\n def test_namedtuple_dump(self):\n for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:\n d = v._asdict()\n sio = StringIO()\n json.dump(v, sio)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, namedtuple_as_object=True)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, tuple_as_array=False)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, namedtuple_as_object=True, tuple_as_array=False)\n self.assertEqual(d, json.loads(sio.getvalue()))\n\n def test_asdict_not_callable_dump(self):\n for f in CONSTRUCTORS:\n self.assertRaises(TypeError, json.dump, f(DeadDuck()), StringIO(), namedtuple_as_object=True)\n sio = StringIO()\n json.dump(f(DeadDict()), sio, namedtuple_as_object=True)\n self.assertEqual(json.dumps(f({})), sio.getvalue())\n\n def test_tuple_array_dump(self):\n t = (1, 2, 3)\n expect = json.dumps(list(t))\n sio = StringIO()\n json.dump(t, sio)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=True)\n self.assertEqual(expect, sio.getvalue())\n self.assertRaises(TypeError, json.dump, t, StringIO(), tuple_as_array=False)\n sio = StringIO()\n json.dump(t, sio, default=repr)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=True, default=repr)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=False, default=repr)\n self.assertEqual(json.dumps(repr(t)), sio.getvalue())\n", "method_code": "def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw):\n \"\"\"Serialize ``obj`` as a JSON formatted stream to ``fp`` (a\n ``.write()``-supporting file-like object).\n\n If *skipkeys* is true then ``dict`` keys that are not basic types\n (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\n will be skipped instead of raising a ``TypeError``.\n\n If *ensure_ascii* is false, then the some chunks written to ``fp``\n may be ``unicode`` instances, subject to normal Python ``str`` to\n ``unicode`` coercion rules. Unless ``fp.write()`` explicitly\n understands ``unicode`` (as in ``codecs.getwriter()``) this is likely\n to cause an error.\n\n If *check_circular* is false, then the circular reference check\n for container types will be skipped and a circular reference will\n result in an ``OverflowError`` (or worse).\n\n If *allow_nan* is false, then it will be a ``ValueError`` to\n serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)\n in strict compliance of the original JSON specification, instead of using\n the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). See\n *ignore_nan* for ECMA-262 compliant behavior.\n\n If *indent* is a string, then JSON array elements and object members\n will be pretty-printed with a newline followed by that string repeated\n for each level of nesting. ``None`` (the default) selects the most compact\n representation without any newlines. For backwards compatibility with\n versions of simplejson earlier than 2.1.0, an integer is also accepted\n and is converted to a string with that many spaces.\n\n If specified, *separators* should be an\n ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``\n if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most\n compact JSON representation, you should specify ``(',', ':')`` to eliminate\n whitespace.\n\n *encoding* is the character encoding for str instances, default is UTF-8.\n\n *default(obj)* is a function that should return a serializable version\n of obj or raise ``TypeError``. The default simply raises ``TypeError``.\n\n If *use_decimal* is true (default: ``True``) then decimal.Decimal\n will be natively serialized to JSON with full precision.\n\n If *namedtuple_as_object* is true (default: ``True``),\n :class:`tuple` subclasses with ``_asdict()`` methods will be encoded\n as JSON objects.\n\n If *tuple_as_array* is true (default: ``True``),\n :class:`tuple` (and subclasses) will be encoded as JSON arrays.\n\n If *iterable_as_array* is true (default: ``False``),\n any object not in the above table that implements ``__iter__()``\n will be encoded as a JSON array.\n\n If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher\n or lower than -2**53 will be encoded as strings. This is to avoid the\n rounding that happens in Javascript otherwise. Note that this is still a\n lossy operation that will not round-trip correctly and should be used\n sparingly.\n\n If *int_as_string_bitcount* is a positive number (n), then int of size\n greater than or equal to 2**n or lower than or equal to -2**n will be\n encoded as strings.\n\n If specified, *item_sort_key* is a callable used to sort the items in\n each dictionary. This is useful if you want to sort items other than\n in alphabetical order by key. This option takes precedence over\n *sort_keys*.\n\n If *sort_keys* is true (default: ``False``), the output of dictionaries\n will be sorted by item.\n\n If *for_json* is true (default: ``False``), objects with a ``for_json()``\n method will use the return value of that method for encoding as JSON\n instead of the object.\n\n If *ignore_nan* is true (default: ``False``), then out of range\n :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as\n ``null`` in compliance with the ECMA-262 specification. If true, this will\n override *allow_nan*.\n\n To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n ``.default()`` method to serialize additional types), specify it with\n the ``cls`` kwarg. NOTE: You should use *default* or *for_json* instead\n of subclassing whenever possible.\n\n \"\"\"\n if not skipkeys and ensure_ascii and check_circular and allow_nan and (cls is None) and (indent is None) and (separators is None) and (encoding == 'utf-8') and (default is None) and use_decimal and namedtuple_as_object and tuple_as_array and (not iterable_as_array) and (not bigint_as_string) and (not sort_keys) and (not item_sort_key) and (not for_json) and (not ignore_nan) and (int_as_string_bitcount is None) and (not kw):\n iterable = _default_encoder.iterencode(obj)\n else:\n if cls is None:\n cls = JSONEncoder\n iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, iterable_as_array=iterable_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, int_as_string_bitcount=int_as_string_bitcount, **kw).iterencode(obj)\n for chunk in iterable:\n fp.write(chunk)", "context": "def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef _import_OrderedDict(): ...\ndef _import_c_make_encoder(): ...\ndef dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): ...\ndef loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): ...\ndef _toggle_speedups(enabled): ...\ndef simple_first(kv): ...\n", "repository": "0x0ece/oscars2016", "test_name": "test_namedtuple_dump", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001778.py"} {"focal_file": "voicesep/separators/neural/network/__init__.py", "focal_class": null, "focal_method": "train", "tests": "import unittest\n\nclass Test_train(unittest.TestCase):\n def test_train(self):\n path = os.path.dirname(os.path.abspath(__file__))\n score = vs.Score(f'{path}/test.musicxml')\n dataset = vs_network.Dataset(f'{path}/test', writer='note_level', mode='w')\n dataset.write(score, beat_horizon=4, one_to_many=True)\n network = vs_network.Network()\n count = vs_network.Features.count(vs_network.Features.Level.PAIR)\n network.build(dimensions=(count, 150, 1), hidden_activations='relu', output_activation='sigmoid')\n network.compile(cost_type='binary_crossentropy', cost_args=(), gradient_type='adadelta', gradient_args=(), L2_reg=0.01)\n network.train(dataset, epochs=200, batch_size=10)\n x, y = dataset[:]\n os.remove(f'{path}/test.hdf5')\n y_hat = network.predict([x])\n result = sum((y_hat > 0.7) == y) / len(y)\n self.assertGreater(result, 0.89)\n", "method_code": " def train(self, dataset, epochs, batch_size, verbosity=0):\n for layer in self.layers:\n layer.random_weights()\n batch_count = (len(dataset) - 1) // batch_size + 1\n checkpoint = time.time()\n for epoch in range(1, epochs + 1):\n cost = 0\n for i in range(batch_count):\n cost += self.train_function(*dataset[i * batch_size:(i + 1) * batch_size])\n if verbosity and int(time.time() - checkpoint) > verbosity:\n logger.info(f'epoch {epoch}/{epochs} | cost={cost / batch_count}')\n checkpoint = time.time()\n ", "context": "class Network():\n def train(self, dataset, epochs, batch_size, verbosity=0): ...\n def __init__(self): ...\n def build(self, dimensions, hidden_activations, output_activation): ...\n def compile(self, cost_type, cost_args, gradient_type, gradient_args, L2_reg): ...\n def predict(self, X): ...\n def read(self, name): ...\n def write(self, name): ...\n\n self.X_vars = []\n self.dimensions = ()\n self.hidden_activations = None\n self.output_activation = None\n self.layers = []\n self.train_function = None\n self.predict_function = None\n", "repository": "pgray91/voicesep", "test_name": "test_train", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001779.py"} {"focal_file": "voicesep/separators/neural/network/__init__.py", "focal_class": null, "focal_method": "read", "tests": "import unittest\n\nclass Test_read(unittest.TestCase):\n def test_write_read(self):\n network_file = f'{os.path.splitext(os.path.abspath(__file__))[0]}.test_write_read.npy'\n network = vs_network.Network()\n network.build(dimensions=((10, 15, 4), 10, 20, 1), hidden_activations='relu', output_activation='sigmoid')\n for layer in network.layers:\n layer.random_weights()\n write_dimensions = network.dimensions\n write_hidden_activations = network.hidden_activations\n write_output_activation = network.output_activation\n write_params = []\n for layer in network.layers:\n write_params.extend(map(str, layer.get_weights()))\n network.write(network_file)\n network = vs_network.Network()\n network.read(network_file)\n os.remove(network_file)\n read_dimensions = network.dimensions\n read_hidden_activations = network.hidden_activations\n read_output_activation = network.output_activation\n read_params = []\n for layer in network.layers:\n read_params.extend(map(str, layer.get_weights()))\n with self.subTest('dimensions'):\n self.assertEqual(read_dimensions, write_dimensions)\n with self.subTest('hidden activations'):\n self.assertEqual(read_hidden_activations, write_hidden_activations)\n with self.subTest('output activation'):\n self.assertEqual(read_output_activation, write_output_activation)\n with self.subTest('params'):\n self.assertEqual(read_params, write_params)\n", "method_code": " def read(self, name):\n with open(name, 'rb') as fp:\n dimensions = tuple(np.load(fp, allow_pickle=True))\n hidden_activations = str(np.load(fp, allow_pickle=True))\n output_activation = str(np.load(fp, allow_pickle=True))\n self.build(dimensions, hidden_activations, output_activation)\n for layer in self.layers:\n W = np.load(fp, allow_pickle=True)\n b = np.load(fp, allow_pickle=True)\n layer.set_weights(W, b)\n y_hat_var = self.layers[-1].y_hat_var\n self.predict_function = theano.function(inputs=self.X_vars, outputs=y_hat_var)\n ", "context": "class Network():\n def read(self, name): ...\n def __init__(self): ...\n def build(self, dimensions, hidden_activations, output_activation): ...\n def compile(self, cost_type, cost_args, gradient_type, gradient_args, L2_reg): ...\n def train(self, dataset, epochs, batch_size, verbosity=0): ...\n def predict(self, X): ...\n def write(self, name): ...\n\n self.X_vars = []\n self.dimensions = ()\n self.hidden_activations = None\n self.output_activation = None\n self.layers = []\n self.train_function = None\n self.predict_function = None\n", "repository": "pgray91/voicesep", "test_name": "test_write_read", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001780.py"} {"focal_file": "xos/synchronizer/event_steps/kubernetes_event.py", "focal_class": null, "focal_method": "process_event", "tests": "import unittest\n\nclass Test_process_event(unittest.TestCase):\n def test_process_event(self):\n with patch.object(VOLTService.objects, 'get_items') as fcservice_objects, patch.object(Service.objects, 'get_items') as service_objects, patch.object(VOLTServiceInstance, 'save', autospec=True) as fcsi_save:\n fcservice_objects.return_value = [self.fcservice]\n service_objects.return_value = [self.onos, self.fcservice]\n event_dict = {'status': 'created', 'labels': {'xos_service': 'myonos'}}\n event = Mock()\n event.value = json.dumps(event_dict)\n step = self.event_step(model_accessor=self.model_accessor, log=self.log)\n step.process_event(event)\n self.assertEqual(self.fcsi1.backend_code, 0)\n self.assertEqual(self.fcsi1.backend_status, 'resynchronize due to kubernetes event')\n self.assertEqual(self.fcsi2.backend_code, 0)\n self.assertEqual(self.fcsi2.backend_status, 'resynchronize due to kubernetes event')\n fcsi_save.assert_has_calls([call(self.fcsi1, update_fields=['updated', 'backend_code', 'backend_status'], always_update_timestamp=True), call(self.fcsi2, update_fields=['updated', 'backend_code', 'backend_status'], always_update_timestamp=True)])\n\n def test_process_event_unknownstatus(self):\n with patch.object(VOLTService.objects, 'get_items') as fcservice_objects, patch.object(Service.objects, 'get_items') as service_objects, patch.object(VOLTServiceInstance, 'save') as fcsi_save:\n fcservice_objects.return_value = [self.fcservice]\n service_objects.return_value = [self.onos, self.fcservice]\n event_dict = {'status': 'something_else', 'labels': {'xos_service': 'myonos'}}\n event = Mock()\n event.value = json.dumps(event_dict)\n step = self.event_step(model_accessor=self.model_accessor, log=self.log)\n step.process_event(event)\n self.assertEqual(self.fcsi1.backend_code, 1)\n self.assertEqual(self.fcsi1.backend_status, 'succeeded')\n self.assertEqual(self.fcsi2.backend_code, 1)\n self.assertEqual(self.fcsi2.backend_status, 'succeeded')\n fcsi_save.assert_not_called()\n\n def test_process_event_unknownservice(self):\n with patch.object(VOLTService.objects, 'get_items') as fcservice_objects, patch.object(Service.objects, 'get_items') as service_objects, patch.object(VOLTServiceInstance, 'save') as fcsi_save:\n fcservice_objects.return_value = [self.fcservice]\n service_objects.return_value = [self.onos, self.fcservice]\n event_dict = {'status': 'created', 'labels': {'xos_service': 'something_else'}}\n event = Mock()\n event.value = json.dumps(event_dict)\n step = self.event_step(model_accessor=self.model_accessor, log=self.log)\n step.process_event(event)\n self.assertEqual(self.fcsi1.backend_code, 1)\n self.assertEqual(self.fcsi1.backend_status, 'succeeded')\n self.assertEqual(self.fcsi2.backend_code, 1)\n self.assertEqual(self.fcsi2.backend_status, 'succeeded')\n fcsi_save.assert_not_called()\n\n def test_process_event_nolabels(self):\n with patch.object(VOLTService.objects, 'get_items') as fcservice_objects, patch.object(Service.objects, 'get_items') as service_objects, patch.object(VOLTServiceInstance, 'save') as fcsi_save:\n fcservice_objects.return_value = [self.fcservice]\n service_objects.return_value = [self.onos, self.fcservice]\n event_dict = {'status': 'created'}\n event = Mock()\n event.value = json.dumps(event_dict)\n step = self.event_step(model_accessor=self.model_accessor, log=self.log)\n step.process_event(event)\n self.assertEqual(self.fcsi1.backend_code, 1)\n self.assertEqual(self.fcsi1.backend_status, 'succeeded')\n self.assertEqual(self.fcsi2.backend_code, 1)\n self.assertEqual(self.fcsi2.backend_status, 'succeeded')\n fcsi_save.assert_not_called()\n", "method_code": " def process_event(self, event):\n value = json.loads(event.value)\n if value.get('status') != 'created':\n return\n if 'labels' not in value:\n return\n xos_service = value['labels'].get('xos_service')\n if not xos_service:\n return\n for service in VOLTService.objects.all():\n onos = Helpers.get_onos_service_name(service)\n if onos.lower() != xos_service.lower():\n continue\n for service_instance in service.service_instances.all():\n log.info('Dirtying VOLTServiceInstance', service_instance=service_instance)\n service_instance.backend_code = 0\n service_instance.backend_status = 'resynchronize due to kubernetes event'\n service_instance.save(update_fields=['updated', 'backend_code', 'backend_status'], always_update_timestamp=True)\n ", "context": "class KubernetesPodDetailsEventStep(EventStep):\n def process_event(self, event): ...\n def __init__(self, *args, **kwargs): ...\n\n topics = ['xos.kubernetes.pod-details']\n technology = 'kafka'\n", "repository": "opencord/olt-service", "test_name": "test_process_event", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001781.py"} {"focal_file": "services/formatters.py", "focal_class": null, "focal_method": "text_response", "tests": "import unittest\n\nclass Test_text_response(unittest.TestCase):\n def test_response_conversions(self):\n data = {'some': 'data'}\n resp = text_response(data)\n self.assertEquals(resp.body, \"{'some': 'data'}\")\n self.assertEquals(resp.content_type, 'text/plain')\n data = 'abc'\n resp = whoisi_response(data)\n self.assertEquals(resp.body, '\\x00\\x00\\x00\\x03\"a\"\\x00\\x00\\x00\\x03\"b\"\\x00\\x00\\x00\\x03\"c\"')\n self.assertEquals(resp.content_type, 'application/whoisi')\n request = Request({})\n request.accept = 'application/whoisi'\n resp = convert_response(request, data)\n self.assertEquals(resp.body, '\\x00\\x00\\x00\\x03\"a\"\\x00\\x00\\x00\\x03\"b\"\\x00\\x00\\x00\\x03\"c\"')\n self.assertEquals(resp.content_type, 'application/whoisi')\n resp = newlines_response(data)\n self.assertEquals(resp.body, '\"a\"\\n\"b\"\\n\"c\"\\n')\n self.assertEquals(resp.content_type, 'application/newlines')\n request = Request({})\n request.accept = 'application/newlines'\n resp = convert_response(request, data)\n self.assertEquals(resp.body, '\"a\"\\n\"b\"\\n\"c\"\\n')\n self.assertEquals(resp.content_type, 'application/newlines')\n data = {'some': 'data'}\n resp = json_response(data)\n self.assertEquals(resp.body, '{\"some\": \"data\"}')\n self.assertEquals(resp.content_type, 'application/json')\n request = Request({})\n resp = convert_response(request, data)\n self.assertEquals(resp.body, '{\"some\": \"data\"}')\n self.assertEquals(resp.content_type, 'application/json')\n", "method_code": "def text_response(data, **kw):\n \"\"\"Returns Response containing a plain text\"\"\"\n return Response(str(data), content_type='text/plain', **kw)", "context": "def text_response(data, **kw): ...\ndef text_response(data, **kw): ...\ndef json_response(data, **kw): ...\ndef html_response(data, **kw): ...\ndef newlines_response(lines, **kw): ...\ndef whoisi_response(lines, **kw): ...\ndef convert_response(request, lines, **kw): ...\n", "repository": "mozilla-services/server-core", "test_name": "test_response_conversions", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001782.py"} {"focal_file": "services/wsgiauth.py", "focal_class": null, "focal_method": "acknowledge", "tests": "import unittest\n\nclass Test_acknowledge(unittest.TestCase):\n def test_acknowledge_method(self):\n config = self.make_config()\n auth = self.auth_class(config)\n req = make_request('/1.0/tarek/info/collections')\n resp = Response(status='200 OK', request=req)\n auth.acknowledge(req, resp)\n req = make_request('/1.0/tarek/info/collections')\n self.set_credentials(req, 'user', 'goodpwd')\n auth.check(req, {'auth': 'True'})\n resp = Response(status='200 OK', request=req)\n auth.acknowledge(req, resp)\n", "method_code": " def acknowledge(self, request, response):\n \"\"\"Acknowledges successful auth back to the user.\n \n This method might send a HTTP Authentication-Info header or set a\n cookie allowing the client to remember its login session.\n \"\"\"\n pass\n ", "context": "class Authentication(object):\n def acknowledge(self, request, response): ...\n def __init__(self, config): ...\n def _log_cef(self, name, severity, environ, config=None, username='none', signature=AUTH_FAILURE, **kw): ...\n def check(self, request, match): ...\n def authenticate_user(self, request, config, username=None): ...\n\n self.config = config\n self.backend = load_and_configure(self.config, 'auth')\n self.logger = CLIENT_HOLDER.default_client\n", "repository": "mozilla-services/server-core", "test_name": "test_acknowledge_method", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001783.py"} {"focal_file": "services/wsgiauth.py", "focal_class": null, "focal_method": "authenticate_user", "tests": "import unittest\n\nclass Test_authenticate_user(unittest.TestCase):\n def test_authenticate_user(self):\n config = self.make_config()\n auth = self.auth_class(config)\n token = 'Basic ' + base64.b64encode('tarek:tarek')\n req = make_request('/1.0/tarek/info/collections', {})\n res = auth.authenticate_user(req, {})\n self.assertEquals(res, None)\n req = make_request('/1.0/tarek/info/collections', {'HTTP_AUTHORIZATION': token})\n res = auth.authenticate_user(req, {})\n self.assertEquals(res, 1)\n bad_token1 = 'Basic ' + base64.b64encode('tarektarek')\n bad_token2 = 'Basic' + base64.b64encode('tarek:tarek')\n req = make_request('/1.0/tarek/info/collections', {'HTTP_AUTHORIZATION': bad_token1})\n self.assertRaises(HTTPUnauthorized, auth.authenticate_user, req, config)\n req = make_request('/1.0/tarek/info/collections', {'HTTP_AUTHORIZATION': bad_token2})\n self.assertRaises(HTTPUnauthorized, auth.authenticate_user, req, config)\n req = make_request('/1.0/tarekbad', {'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode('tarekbad:tarek'), 'REQUEST_METHOD': 'TEST', 'PATH_INFO': 'TEST'})\n self.assertRaises(HTTPUnauthorized, auth.authenticate_user, req, config)\n", "method_code": " def authenticate_user(self, request, config, username=None):\n \"\"\"Authenticates a user and returns his id.\n \n \"request\" is the request received.\n The function makes sure that the user name found in the headers\n is compatible with the username if provided.\n \n It returns the user id from the database, if the password is the right\n one.\n \"\"\"\n environ = request.environ\n if 'REMOTE_USER' in environ:\n msg = 'The webserver appears to have handled authentication internally, which is not compatible with this product.'\n raise HTTPServerError(msg)\n auth = environ.get('HTTP_AUTHORIZATION')\n if auth is not None:\n if not auth.startswith('Basic '):\n self._log_cef('Authorization header contains unknown protocol', 7, environ)\n raise HTTPUnauthorized('Invalid token')\n auth = auth[len('Basic '):].strip()\n try:\n user_name, password = base64.decodestring(auth).split(':', 1)\n except (binascii.Error, ValueError):\n self._log_cef('Authorization header is badly encoded', 7, environ)\n raise HTTPUnauthorized('Invalid token')\n if username is not None and user_name != username:\n self._log_cef('Username Does Not Match URL', 7, environ, config, user_name, AUTH_FAILURE)\n raise HTTPUnauthorized()\n remote_user_original = user_name\n try:\n user_name = extract_username(user_name)\n except UnicodeError:\n self._log_cef('Username contains invalid characters', 7, environ)\n raise HTTPBadRequest('Invalid characters specified in ' + 'username', {}, 'Username must be BIDI ' + 'compliant UTF-8')\n try:\n password = password.decode('utf8')\n except UnicodeDecodeError:\n self._log_cef('Password is not utf-8 encoded', 7, environ)\n raise HTTPUnauthorized()\n if hasattr(self.backend, 'generate_reset_code'):\n if hasattr(self.backend, 'check_node') and self.backend.check_node:\n user_id = self.backend.authenticate_user(user_name, password, environ.get('HTTP_HOST'))\n else:\n user_id = self.backend.authenticate_user(user_name, password)\n request.user = User(user_name, user_id)\n else:\n user = User(user_name)\n credentials = {'username': user_name, 'password': password}\n attrs = []\n check_node = self.config.get('auth.check_node')\n if check_node:\n attrs.append('syncNode')\n user_id = self.backend.authenticate_user(user, credentials, attrs)\n if not user_id:\n user_id = None\n user = None\n elif check_node and user.get('syncNode') != environ.get('HTTP_HOST'):\n self._log_cef('User authenticated to wrong node', 7, environ)\n user_id = None\n user = None\n request.user = user\n if user_id is None:\n err_user = user_name\n if remote_user_original is not None and user_name != remote_user_original:\n err_user += ' (%s)' % remote_user_original\n self._log_cef('User Authentication Failed', 5, environ, config, err_user, AUTH_FAILURE)\n raise HTTPUnauthorized()\n request.remote_user = environ['REMOTE_USER'] = user_name\n request.user_password = password\n request._authorization = environ['HTTP_AUTHORIZATION']\n del environ['HTTP_AUTHORIZATION']\n return user_id\n ", "context": "class Authentication(object):\n def authenticate_user(self, request, config, username=None): ...\n def __init__(self, config): ...\n def _log_cef(self, name, severity, environ, config=None, username='none', signature=AUTH_FAILURE, **kw): ...\n def check(self, request, match): ...\n def acknowledge(self, request, response): ...\n\n self.config = config\n self.backend = load_and_configure(self.config, 'auth')\n self.logger = CLIENT_HOLDER.default_client\n", "repository": "mozilla-services/server-core", "test_name": "test_authenticate_user", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001784.py"} {"focal_file": "services/auth/dummy.py", "focal_class": null, "focal_method": "authenticate_user", "tests": "import unittest\n\nclass Test_authenticate_user(unittest.TestCase):\n def test_authenticate_user(self):\n tarek_id = self.auth.authenticate_user('tarek', 'tarek')\n self.assertNotEquals(self.auth.authenticate_user('tarek2', 'tarek'), tarek_id)\n self.assertEquals(self.auth.authenticate_user('tarek', 'tarek'), tarek_id)\n", "method_code": " def authenticate_user(self, user_name, password):\n \"\"\"Authenticates a user given a username and password.\n \n Returns the user id in case of success. Returns None otherwise.\"\"\"\n if user_name not in self._users:\n self.create_user(user_name, password, '')\n return self._users[user_name]\n ", "context": "class DummyAuth(object):\n def authenticate_user(self, user_name, password): ...\n def __init__(self, **kw): ...\n def create_user(self, user_name, password, email): ...\n def get_user_id(self, user_name): ...\n def generate_reset_code(self, user_id, overwrite=False): ...\n def verify_reset_code(self, user_id, code): ...\n def clear_reset_code(self, user_id): ...\n def get_user_info(self, user_id): ...\n def update_email(self, user_id, email): ...\n def delete_user(self, user_id, password=None): ...\n def get_total_size(self, user_id): ...\n def get_user_node(self, user_id, assign=True): ...\n def update_password(self, user_id, new_password, old_password): ...\n def admin_update_password(self, user_id, new_password, key): ...\n\n self._users = {}\n", "repository": "mozilla-services/server-core", "test_name": "test_authenticate_user", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001785.py"} {"focal_file": "services/auth/sql.py", "focal_class": null, "focal_method": "authenticate_user", "tests": "import unittest\n\nclass Test_authenticate_user(unittest.TestCase):\n def test_authenticate_user(self):\n if not isinstance(self.auth, SQLAuth):\n return\n self.assertEquals(self.auth.authenticate_user('tarek', 'xxx'), None)\n user_id = self.auth.authenticate_user('tarek', 'tarek')\n self.assertEquals(user_id, self.user_id)\n", "method_code": " def authenticate_user(self, user_name, password):\n \"\"\"Authenticates a user given a user_name and password.\n \n Returns the user id in case of success. Returns None otherwise.\"\"\"\n user = safe_execute(self._engine, _USER_AUTH, user_name=user_name).fetchone()\n if user is None:\n return None\n if user.status != 1:\n return None\n if validate_password(password, user.password_hash):\n return user.id\n ", "context": "class SQLAuth(ResetCodeManager):\n def authenticate_user(self, user_name, password): ...\n def __init__(self, sqluri=_SQLURI, pool_size=20, pool_recycle=60, create_tables=False, no_pool=False, **kw): ...\n def _get_username(self, uid): ...\n def get_user_id(self, user_name): ...\n def create_user(self, user_name, password, email): ...\n def get_user_info(self, user_id): ...\n def update_email(self, user_id, email, password=None): ...\n def update_password(self, user_id, password, old_password): ...\n def admin_update_password(self, user_id, password, key): ...\n def delete_user(self, user_id, password=None): ...\n def get_user_node(self, user_id, assign=True): ...\n def clear_reset_code(self, user_id): ...\n def _get_reset_code(self, user_id): ...\n def _set_reset_code(self, user_id): ...\n\n self.sqluri = sqluri\n self.logger = CLIENT_HOLDER.default_client\n", "repository": "mozilla-services/server-core", "test_name": "test_authenticate_user", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001786.py"} {"focal_file": "services/config.py", "focal_class": "Config", "focal_method": "merge", "tests": "import unittest\n\nclass Test_Config_merge(unittest.TestCase):\n def test_config_merge(self):\n config = Config(cfgfile=self.file_four)\n global_ = {'foo': 'bar', 'baz': 'bawlp'}\n self.assertEqual(config.get_section(''), dict())\n self.assertEqual(config.get_section('global'), global_)\n self.assertEqual(config['auth.a'], 'b')\n self.assertEqual(config['auth.c'], 'd')\n self.assertEqual(config.get_section('auth'), {'a': 'b', 'c': 'd'})\n storage = {'e': 'f', 'g': 'h'}\n self.assertEqual(config['storage.e'], 'f')\n self.assertEqual(config['storage.g'], 'h')\n self.assertEqual(config.get_section('storage'), storage)\n storage_once = {'i': 'j', 'k': 'l'}\n storage_once.update(storage)\n once_merged = config.merge('multi:once')\n self.assertEqual(once_merged.get_section('storage'), storage_once)\n storage_thrice = {'i': 'jjj', 'k': 'lll'}\n storage_thrice.update(storage)\n thrice_merged = config.merge('multi:thrice')\n self.assertEqual(thrice_merged.get_section('storage'), storage_thrice)\n config['storage.m'] = 'n'\n config['multi:thrice.storage.o'] = 'ppp'\n thrice_merged = config.merge('multi:thrice')\n self.assertEqual(thrice_merged.get_section('storage'), storage_thrice)\n config.clear_merge_cache()\n thrice_merged = config.merge('multi:thrice')\n self.assertNotEqual(thrice_merged.get_section('storage'), storage_thrice)\n storage_thrice.update(dict(m='n', o='ppp'))\n self.assertEqual(thrice_merged.get_section('storage'), storage_thrice)\n", "method_code": " def merge(self, *sections):\n \"\"\"\n Merge settings from the specified sections into other sections as\n determined by the splitchar prefix in the specified sections.\n \"\"\"\n if sections in self._merge_cache:\n return self._merge_cache[sections]\n ret = copy(self)\n for section in sections:\n section_map = self.get_section(section)\n for k, v in section_map.items():\n if self.splitchar not in k:\n continue\n ret[k] = v\n self._merge_cache[sections] = ret\n return ret\n ", "context": "class Config(dict):\n def merge(self, *sections): ...\n def __init__(self, cfgdict=None, cfgfile=None): ...\n def load_config(self, cfgdict): ...\n def load_from_file(self, path): ...\n def get_section(self, section): ...\n def clear_merge_cache(self): ...\n\n self._merge_cache = dict()\n\n splitchar = '.'\n", "repository": "mozilla-services/server-core", "test_name": "test_config_merge", "smells": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001787.py"} {"focal_file": "bamp/bamp.py", "focal_class": null, "focal_method": "get_prefix_suffix", "tests": "import unittest\n\nclass Test_get_prefix_suffix(unittest.TestCase):\n def test_get_prefix_suffix(self):\n \"\"\"\n Should return the prefix and suffix of the given line if it contains the given version, else\n returns None, None.\n \"\"\"\n version = '1.2.3'\n data = (('This is the first line', (None, None)), ('version = 1.2.3', ('version = ', '')), ('The version is 1.2.3 right now', ('The version is ', ' right now')))\n for inpt, outpt in data:\n self.assertEqual(bamp.get_prefix_suffix(version, inpt), outpt)\n", "method_code": "def get_prefix_suffix(version, line):\n \"\"\"\n If the version is in the given line, return the prefix and suffix, else None, None.\n \"\"\"\n match = re.match('(.*)%s(.*)' % re.escape(version), line)\n if match is None:\n return (None, None)\n return match.groups()", "context": "def get_prefix_suffix(version, line): ...\ndef get_prefix_suffix(version, line): ...\ndef get_version_lines(version, lines, first_line_number=0): ...\ndef replace_versions(newversion, lines, vlines): ...\n", "repository": "0x07Ltd/bamp", "test_name": "test_get_prefix_suffix", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001788.py"} {"focal_file": "bamp/bamp.py", "focal_class": null, "focal_method": "get_version_lines", "tests": "import unittest\n\nclass Test_get_version_lines(unittest.TestCase):\n def test_get_version_lines(self):\n \"\"\"\n Should find all occurences of the version number in the given list of strings and return the\n prefixes and suffixes as a dictionary of tuples with the (0 based) line numbers as keys.\n \"\"\"\n version = '1.2.3'\n lines = ['This is the first line', 'This is the second line', 'version = 1.2.3', 'The version is 1.2.3 right now', 'This is the fifth line']\n vlines = bamp.get_version_lines(version, lines)\n self.assertEqual(vlines, {2: ('version = ', ''), 3: ('The version is ', ' right now')})\n\n def test_get_version_lines_first_line_number(self):\n \"\"\"\n Should return line numbers starting from the supplied `first_line_number`.\n \"\"\"\n version = '1.2.3'\n lines = ['This is the first line', 'This is the second line', 'version = 1.2.3', 'The version is 1.2.3 right now', 'This is the fifth line']\n vlines = bamp.get_version_lines(version, lines, first_line_number=10)\n self.assertEqual(vlines, {12: ('version = ', ''), 13: ('The version is ', ' right now')})\n", "method_code": "def get_version_lines(version, lines, first_line_number=0):\n \"\"\"\n Finds all occurences of the version number in the given list of strings and return the\n prefixes and suffixes as a dictionary of tuples with the line numbers as keys.\n \"\"\"\n ret = {}\n for i, line in enumerate(lines, first_line_number):\n pre_suf = get_prefix_suffix(version, line)\n if not any([x is None for x in pre_suf]):\n ret[i] = pre_suf\n return ret", "context": "def get_version_lines(version, lines, first_line_number=0): ...\ndef get_prefix_suffix(version, line): ...\ndef get_version_lines(version, lines, first_line_number=0): ...\ndef replace_versions(newversion, lines, vlines): ...\n", "repository": "0x07Ltd/bamp", "test_name": "test_get_version_lines", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001789.py"} {"focal_file": "bamp/bamp.py", "focal_class": null, "focal_method": "replace_versions", "tests": "import unittest\n\nclass Test_replace_versions(unittest.TestCase):\n def test_replace_versions(self):\n \"\"\"\n Should replace all occurences of the old version with `newversion` in `lines`.\n \"\"\"\n version = '1.2.3'\n newversion = '1.2.4'\n lines = ['This is the first line', 'This is the second line', 'version = 1.2.3', 'The version is 1.2.3 right now', 'This is the fifth line']\n vlines = bamp.get_version_lines(version, lines)\n replaced = list(bamp.replace_versions(newversion, lines, vlines))\n self.assertEqual(replaced[2], 'version = %s' % newversion)\n self.assertEqual(replaced[3], 'The version is %s right now' % newversion)\n", "method_code": "def replace_versions(newversion, lines, vlines):\n \"\"\"\n Replaces all occurences of the old version with `newversion` in `lines` list.\n \"\"\"\n for i, line in enumerate(lines):\n if i in vlines:\n prefix, suffix = vlines[i]\n yield ('%s%s%s' % (prefix, newversion, suffix))\n else:\n yield line", "context": "def replace_versions(newversion, lines, vlines): ...\ndef get_prefix_suffix(version, line): ...\ndef get_version_lines(version, lines, first_line_number=0): ...\ndef replace_versions(newversion, lines, vlines): ...\n", "repository": "0x07Ltd/bamp", "test_name": "test_replace_versions", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001790.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/blob_download.py", "focal_class": null, "focal_method": "_get_blob_storage", "tests": "import unittest\n\nclass Test_get_blob_storage(unittest.TestCase):\n def test_get_blob_storage(self):\n \"\"\"Test getting blob storage from datastore stub.\"\"\"\n blob_storage = blob_download._get_blob_storage()\n self.assertEquals(self.blobstore_stub.storage, blob_storage)\n", "method_code": "def _get_blob_storage():\n \"\"\"Gets the BlobStorage instance from the API proxy stub map.\n\n Returns:\n The BlobStorage instance as registered with blobstore API in stub map.\n \"\"\"\n return apiproxy_stub_map.apiproxy.GetStub('blobstore').storage", "context": "def _get_blob_storage(): ...\ndef _get_blob_storage(): ...\ndef _parse_range_header(range_header): ...\ndef _get_blob_metadata(blob_key): ...\ndef blobstore_download_rewriter(state): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_blob_storage", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001791.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/blob_download.py", "focal_class": null, "focal_method": "_parse_range_header", "tests": "import unittest\n\nclass Test_parse_range_header(unittest.TestCase):\n def test_parse_range_header(self):\n \"\"\"Test ParseRangeHeader function.\"\"\"\n self.assertEquals((None, None), blob_download._parse_range_header(''))\n self.assertEquals((None, None), blob_download._parse_range_header('invalid'))\n self.assertEquals((1, None), blob_download._parse_range_header('bytes=1-'))\n self.assertEquals((10, 21), blob_download._parse_range_header('bytes=10-20'))\n self.assertEquals((-30, None), blob_download._parse_range_header('bytes=-30'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=-30-'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=-30-40'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=0-1,2-3'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=-0'))\n self.assertEquals((None, None), blob_download._parse_range_header('bits=0-20'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=a-20'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=0-a'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=0--'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=--10'))\n self.assertEquals((None, None), blob_download._parse_range_header('bytes=0--10'))\n", "method_code": "def _parse_range_header(range_header):\n \"\"\"Parse HTTP Range header.\n\n Args:\n range_header: A str representing the value of a range header as retrived\n from Range or X-AppEngine-BlobRange.\n\n Returns:\n Tuple (start, end):\n start: Start index of blob to retrieve. May be negative index.\n end: None or end index. End index is exclusive.\n (None, None) if there is a parse error.\n \"\"\"\n if not range_header:\n return (None, None)\n try:\n range_type, ranges = range_header.split('=', 1)\n if range_type != 'bytes':\n return (None, None)\n ranges = ranges.lstrip()\n if ',' in ranges:\n return (None, None)\n end = None\n if ranges.startswith('-'):\n start = int(ranges)\n if start == 0:\n return (None, None)\n else:\n split_range = ranges.split('-', 1)\n start = int(split_range[0])\n if len(split_range) == 2 and split_range[1].strip():\n end = int(split_range[1]) + 1\n if start > end:\n return (None, None)\n return (start, end)\n except ValueError:\n return (None, None)", "context": "def _parse_range_header(range_header): ...\ndef _get_blob_storage(): ...\ndef _parse_range_header(range_header): ...\ndef _get_blob_metadata(blob_key): ...\ndef blobstore_download_rewriter(state): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_parse_range_header", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001792.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "get_module_names", "tests": "import unittest\n\nclass Test_get_module_names(unittest.TestCase):\n def test_get_module_names(self):\n self.assertItemsEqual(['default', 'other', 'another'], self.dispatcher.get_module_names())\n", "method_code": " def get_module_names(self):\n \"\"\"Returns a list of module names.\"\"\"\n return list(self._module_name_to_module)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def get_module_names(self): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_module_names", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001793.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "get_hostname", "tests": "import unittest\n\nclass Test_get_hostname(unittest.TestCase):\n def test_get_hostname(self):\n self.assertEqual('localhost:1', self.dispatcher.get_hostname('default', 'version'))\n self.assertEqual('localhost:2', self.dispatcher.get_hostname('other', 'version2'))\n self.assertRaises(request_info.VersionDoesNotExistError, self.dispatcher.get_hostname, 'default', 'fake')\n self.assertRaises(request_info.NotSupportedWithAutoScalingError, self.dispatcher.get_hostname, 'default', 'version', '0')\n self.assertEqual('localhost:1000', self.dispatcher.get_hostname('other', 'version2', '0'))\n self.assertRaises(request_info.InvalidInstanceIdError, self.dispatcher.get_hostname, 'other', 'version2', 'invalid')\n self.assertRaises(request_info.ModuleDoesNotExistError, self.dispatcher.get_hostname, 'nomodule', 'version2', None)\n self.assertEqual('%s:3' % socket.gethostname(), self.dispatcher.get_hostname('another', 'version3'))\n self.assertEqual('%s:1000' % socket.gethostname(), self.dispatcher.get_hostname('another', 'version3', '0'))\n", "method_code": " def get_hostname(self, module_name, version, instance_id=None):\n \"\"\"Returns the hostname for a (module, version, instance_id) tuple.\n \n If instance_id is set, this will return a hostname for that particular\n instances. Otherwise, it will return the hostname for load-balancing.\n Returning 0.0.0.0 is modified to be a more useful address to the user.\n \n Args:\n module_name: A str containing the name of the module.\n version: A str containing the version.\n instance_id: An optional str containing the instance ID.\n \n Returns:\n A str containing the hostname.\n \n Raises:\n request_info.ModuleDoesNotExistError: The module does not exist.\n request_info.VersionDoesNotExistError: The version does not exist.\n request_info.InvalidInstanceIdError: The instance ID is not valid for the\n module/version or the module/version uses automatic scaling.\n \"\"\"\n _module = self._get_module(module_name, version)\n if instance_id is None:\n hostname = _module.balanced_address\n else:\n hostname = _module.get_instance_address(instance_id)\n parts = hostname.split(':')\n try:\n if socket.inet_aton(parts[0]) == '\\x00\\x00\\x00\\x00':\n hostname = ':'.join([socket.gethostname()] + parts[1:])\n except socket.error:\n pass\n return hostname\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def get_hostname(self, module_name, version, instance_id=None): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_hostname", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001794.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "get_module_by_name", "tests": "import unittest\n\nclass Test_get_module_by_name(unittest.TestCase):\n def test_get_module_by_name(self):\n self.assertEqual(self.module1, self.dispatcher.get_module_by_name('default'))\n self.assertEqual(self.module2, self.dispatcher.get_module_by_name('other'))\n self.assertRaises(request_info.ModuleDoesNotExistError, self.dispatcher.get_module_by_name, 'fake')\n", "method_code": " def get_module_by_name(self, _module):\n \"\"\"Returns the module with the given name.\n \n Args:\n _module: A str containing the name of the module.\n \n Returns:\n The module.Module with the provided name.\n \n Raises:\n request_info.ModuleDoesNotExistError: The module does not exist.\n \"\"\"\n try:\n return self._module_name_to_module[_module]\n except KeyError:\n raise request_info.ModuleDoesNotExistError(_module)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def get_module_by_name(self, _module): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_module_by_name", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001795.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "get_versions", "tests": "import unittest\n\nclass Test_get_versions(unittest.TestCase):\n def test_get_versions(self):\n self.assertEqual(['version'], self.dispatcher.get_versions('default'))\n self.assertEqual(['version2'], self.dispatcher.get_versions('other'))\n self.assertRaises(request_info.ModuleDoesNotExistError, self.dispatcher.get_versions, 'fake')\n", "method_code": " def get_versions(self, _module):\n \"\"\"Returns a list of versions for a module.\n \n Args:\n _module: A str containing the name of the module.\n \n Returns:\n A list of str containing the versions for the specified module.\n \n Raises:\n request_info.ModuleDoesNotExistError: The module does not exist.\n \"\"\"\n if _module in self._module_configurations:\n return [self._module_configurations[_module].major_version]\n else:\n raise request_info.ModuleDoesNotExistError(_module)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def get_versions(self, _module): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_versions", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001796.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "get_default_version", "tests": "import unittest\n\nclass Test_get_default_version(unittest.TestCase):\n def test_get_default_version(self):\n self.assertEqual('version', self.dispatcher.get_default_version('default'))\n self.assertEqual('version2', self.dispatcher.get_default_version('other'))\n self.assertRaises(request_info.ModuleDoesNotExistError, self.dispatcher.get_default_version, 'fake')\n", "method_code": " def get_default_version(self, _module):\n \"\"\"Returns the default version for a module.\n \n Args:\n _module: A str containing the name of the module.\n \n Returns:\n A str containing the default version for the specified module.\n \n Raises:\n request_info.ModuleDoesNotExistError: The module does not exist.\n \"\"\"\n if _module in self._module_configurations:\n return self._module_configurations[_module].major_version\n else:\n raise request_info.ModuleDoesNotExistError(_module)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def get_default_version(self, _module): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_default_version", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001797.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "add_event", "tests": "import unittest\n\nclass Test_add_event(unittest.TestCase):\n def test_add_event(self):\n self.mox.StubOutWithMock(scheduled_executor.ScheduledExecutor, 'add_event')\n runnable = object()\n scheduled_executor.ScheduledExecutor.add_event(runnable, 123, ('foo', 'bar'))\n scheduled_executor.ScheduledExecutor.add_event(runnable, 124, None)\n self.mox.ReplayAll()\n self.dispatcher.add_event(runnable, 123, 'foo', 'bar')\n self.dispatcher.add_event(runnable, 124)\n self.mox.VerifyAll()\n", "method_code": " def add_event(self, runnable, eta, service=None, event_id=None):\n \"\"\"Add a callable to be run at the specified time.\n \n Args:\n runnable: A callable object to call at the specified time.\n eta: An int containing the time to run the event, in seconds since the\n epoch.\n service: A str containing the name of the service that owns this event.\n This should be set if event_id is set.\n event_id: A str containing the id of the event. If set, this can be passed\n to update_event to change the time at which the event should run.\n \"\"\"\n if service is not None and event_id is not None:\n key = (service, event_id)\n else:\n key = None\n self._executor.add_event(runnable, eta, key)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_add_event", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001798.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "update_event", "tests": "import unittest\n\nclass Test_update_event(unittest.TestCase):\n def test_update_event(self):\n self.mox.StubOutWithMock(scheduled_executor.ScheduledExecutor, 'update_event')\n scheduled_executor.ScheduledExecutor.update_event(123, ('foo', 'bar'))\n self.mox.ReplayAll()\n self.dispatcher.update_event(123, 'foo', 'bar')\n self.mox.VerifyAll()\n", "method_code": " def update_event(self, eta, service, event_id):\n \"\"\"Update the eta of a scheduled event.\n \n Args:\n eta: An int containing the time to run the event, in seconds since the\n epoch.\n service: A str containing the name of the service that owns this event.\n event_id: A str containing the id of the event to update.\n \"\"\"\n self._executor.update_event(eta, (service, event_id))\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def update_event(self, eta, service, event_id): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_update_event", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001799.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "add_async_request", "tests": "import unittest\n\nclass Test_add_async_request(unittest.TestCase):\n def test_add_async_request(self):\n dummy_environ = object()\n self.mox.StubOutWithMock(dispatcher._THREAD_POOL, 'submit')\n self.dispatcher._module_name_to_module['default'].build_request_environ('PUT', '/foo?bar=baz', [('Header', 'Value'), ('Other', 'Values')], 'body', '1.2.3.4', 1).AndReturn(dummy_environ)\n dispatcher._THREAD_POOL.submit(self.dispatcher._handle_request, dummy_environ, mox.IgnoreArg(), self.dispatcher._module_name_to_module['default'], None, catch_and_log_exceptions=True)\n self.mox.ReplayAll()\n self.dispatcher.add_async_request('PUT', '/foo?bar=baz', [('Header', 'Value'), ('Other', 'Values')], 'body', '1.2.3.4')\n self.mox.VerifyAll()\n\n def test_add_async_request_specific_module(self):\n dummy_environ = object()\n self.mox.StubOutWithMock(dispatcher._THREAD_POOL, 'submit')\n self.dispatcher._module_name_to_module['other'].build_request_environ('PUT', '/foo?bar=baz', [('Header', 'Value'), ('Other', 'Values')], 'body', '1.2.3.4', 2).AndReturn(dummy_environ)\n dispatcher._THREAD_POOL.submit(self.dispatcher._handle_request, dummy_environ, mox.IgnoreArg(), self.dispatcher._module_name_to_module['other'], None, catch_and_log_exceptions=True)\n self.mox.ReplayAll()\n self.dispatcher.add_async_request('PUT', '/foo?bar=baz', [('Header', 'Value'), ('Other', 'Values')], 'body', '1.2.3.4', module_name='other')\n self.mox.VerifyAll()\n\n def test_add_async_request_soft_routing(self):\n \"\"\"Tests add_async_request with soft routing.\"\"\"\n dummy_environ = object()\n self.mox.StubOutWithMock(dispatcher._THREAD_POOL, 'submit')\n self.dispatcher._module_name_to_module['default'].build_request_environ('PUT', '/foo?bar=baz', [('Header', 'Value'), ('Other', 'Values')], 'body', '1.2.3.4', 1).AndReturn(dummy_environ)\n dispatcher._THREAD_POOL.submit(self.dispatcher._handle_request, dummy_environ, mox.IgnoreArg(), self.dispatcher._module_name_to_module['default'], None, catch_and_log_exceptions=True)\n self.mox.ReplayAll()\n self.dispatcher.add_async_request('PUT', '/foo?bar=baz', [('Header', 'Value'), ('Other', 'Values')], 'body', '1.2.3.4', module_name='nomodule')\n self.mox.VerifyAll()\n", "method_code": " def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None):\n \"\"\"Dispatch an HTTP request asynchronously.\n \n Args:\n method: A str containing the HTTP method of the request.\n relative_url: A str containing path and query string of the request.\n headers: A list of (key, value) tuples where key and value are both str.\n body: A str containing the request body.\n source_ip: The source ip address for the request.\n module_name: An optional str containing the module name to service this\n request. If unset, the request will be dispatched to the default\n module.\n version: An optional str containing the version to service this request.\n If unset, the request will be dispatched to the default version.\n instance_id: An optional str containing the instance_id of the instance to\n service this request. If unset, the request will be dispatched to\n according to the load-balancing for the module and version.\n \"\"\"\n if module_name:\n _module = self._get_module_with_soft_routing(module_name, version)\n else:\n _module = self._module_for_request(urlparse.urlsplit(relative_url).path)\n inst = _module.get_instance(instance_id) if instance_id else None\n port = _module.get_instance_port(instance_id) if instance_id else _module.balanced_port\n environ = _module.build_request_environ(method, relative_url, headers, body, source_ip, port)\n _THREAD_POOL.submit(self._handle_request, environ, start_response_utils.null_start_response, _module, inst, catch_and_log_exceptions=True)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_add_async_request", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001800.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "add_request", "tests": "import unittest\n\nclass Test_add_request(unittest.TestCase):\n def test_add_request(self):\n dummy_environ = object()\n self.mox.StubOutWithMock(self.dispatcher, '_resolve_target')\n self.mox.StubOutWithMock(self.dispatcher, '_handle_request')\n self.dispatcher._resolve_target(None, '/foo').AndReturn((self.dispatcher._module_name_to_module['default'], None))\n self.dispatcher._module_name_to_module['default'].build_request_environ('PUT', '/foo?bar=baz', [('Header', 'Value'), ('Other', 'Values')], 'body', '1.2.3.4', 1, fake_login=True).AndReturn(dummy_environ)\n self.dispatcher._handle_request(dummy_environ, mox.IgnoreArg(), self.dispatcher._module_name_to_module['default'], None).AndReturn(['Hello World'])\n self.mox.ReplayAll()\n response = self.dispatcher.add_request('PUT', '/foo?bar=baz', [('Header', 'Value'), ('Other', 'Values')], 'body', '1.2.3.4', fake_login=True)\n self.mox.VerifyAll()\n self.assertEqual('Hello World', response.content)\n", "method_code": " def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False):\n \"\"\"Process an HTTP request.\n \n Args:\n method: A str containing the HTTP method of the request.\n relative_url: A str containing path and query string of the request.\n headers: A list of (key, value) tuples where key and value are both str.\n body: A str containing the request body.\n source_ip: The source ip address for the request.\n module_name: An optional str containing the module name to service this\n request. If unset, the request will be dispatched according to the\n host header and relative_url.\n version: An optional str containing the version to service this request.\n If unset, the request will be dispatched according to the host header\n and relative_url.\n instance_id: An optional str containing the instance_id of the instance to\n service this request. If unset, the request will be dispatched\n according to the host header and relative_url and, if applicable, the\n load-balancing for the module and version.\n fake_login: A bool indicating whether login checks should be bypassed,\n i.e. \"login: required\" should be ignored for this request.\n \n Returns:\n A request_info.ResponseTuple containing the response information for the\n HTTP request.\n \"\"\"\n if module_name:\n _module = self._get_module_with_soft_routing(module_name, version)\n inst = _module.get_instance(instance_id) if instance_id else None\n else:\n headers_dict = wsgiref.headers.Headers(headers)\n _module, inst = self._resolve_target(headers_dict['Host'], urlparse.urlsplit(relative_url).path)\n if inst:\n try:\n port = _module.get_instance_port(inst.instance_id)\n except request_info.NotSupportedWithAutoScalingError:\n port = _module.balanced_port\n else:\n port = _module.balanced_port\n environ = _module.build_request_environ(method, relative_url, headers, body, source_ip, port, fake_login=fake_login)\n start_response = start_response_utils.CapturingStartResponse()\n response = self._handle_request(environ, start_response, _module, inst)\n merged = start_response.merged_response(response)\n return request_info.ResponseTuple(start_response.status, start_response.response_headers, merged)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_add_request", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001801.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "_handle_request", "tests": "import unittest\n\nclass Test_handle_request(unittest.TestCase):\n def test_handle_request(self):\n start_response = object()\n servr = self.dispatcher._module_name_to_module['other']\n self.mox.StubOutWithMock(servr, '_handle_request')\n servr._handle_request({'foo': 'bar'}, start_response, inst=None, request_type=3).AndReturn(['body'])\n self.mox.ReplayAll()\n self.dispatcher._handle_request({'foo': 'bar'}, start_response, servr, None, request_type=3)\n self.mox.VerifyAll()\n\n def test_handle_request_reraise_exception(self):\n start_response = object()\n servr = self.dispatcher._module_name_to_module['other']\n self.mox.StubOutWithMock(servr, '_handle_request')\n servr._handle_request({'foo': 'bar'}, start_response).AndRaise(Exception)\n self.mox.ReplayAll()\n self.assertRaises(Exception, self.dispatcher._handle_request, {'foo': 'bar'}, start_response, servr, None)\n self.mox.VerifyAll()\n", "method_code": " def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False):\n \"\"\"Dispatch a WSGI request.\n \n Args:\n environ: An environ dict for the request as defined in PEP-333.\n start_response: A function with semantics defined in PEP-333.\n _module: The module to dispatch this request to.\n inst: The instance to service this request. If None, the module will\n be left to choose the instance to serve this request.\n request_type: The request_type of this request. See instance.*_REQUEST\n module constants.\n catch_and_log_exceptions: A bool containing whether to catch and log\n exceptions in handling the request instead of leaving it for the\n caller to handle.\n \n Returns:\n An iterable over the response to the request as defined in PEP-333.\n \"\"\"\n try:\n return _module._handle_request(environ, start_response, inst=inst, request_type=request_type)\n except:\n if catch_and_log_exceptions:\n logging.exception('Internal error while handling request.')\n else:\n raise\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_handle_request", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001802.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "_module_for_request", "tests": "import unittest\n\nclass Test_module_for_request(unittest.TestCase):\n def test_module_for_request(self):\n\n class FakeDict(dict):\n\n def __contains__(self, key):\n return True\n\n def __getitem__(self, key):\n return key\n self.dispatcher._module_name_to_module = FakeDict()\n self.dispatch_config.dispatch = [(dispatchinfo.ParsedURL('*/path'), '1'), (dispatchinfo.ParsedURL('*/other_path/*'), '2'), (dispatchinfo.ParsedURL('*/other_path/'), '3'), (dispatchinfo.ParsedURL('*/other_path'), '3')]\n self.assertEqual('1', self.dispatcher._module_for_request('/path'))\n self.assertEqual('2', self.dispatcher._module_for_request('/other_path/'))\n self.assertEqual('2', self.dispatcher._module_for_request('/other_path/a'))\n self.assertEqual('3', self.dispatcher._module_for_request('/other_path'))\n self.assertEqual('default', self.dispatcher._module_for_request('/undispatched'))\n", "method_code": " def _module_for_request(self, path):\n dispatch = self._configuration.dispatch\n if dispatch and self._should_use_dispatch_config(path):\n for url, module_name in dispatch.dispatch:\n if url.path_exact and path == url.path or (not url.path_exact and path.startswith(url.path)):\n return self._get_module_with_soft_routing(module_name, None)\n return self._get_module_with_soft_routing(None, None)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def _module_for_request(self, path): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_module_for_request", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001803.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "_should_use_dispatch_config", "tests": "import unittest\n\nclass Test_should_use_dispatch_config(unittest.TestCase):\n def test_should_use_dispatch_config(self):\n \"\"\"Tests the _should_use_dispatch_config method.\"\"\"\n self.assertTrue(self.dispatcher._should_use_dispatch_config('/'))\n self.assertTrue(self.dispatcher._should_use_dispatch_config('/foo/'))\n self.assertTrue(self.dispatcher._should_use_dispatch_config('/_ah/queue/deferred'))\n self.assertTrue(self.dispatcher._should_use_dispatch_config('/_ah/queue/deferred/blah'))\n self.assertFalse(self.dispatcher._should_use_dispatch_config('/_ah/'))\n self.assertFalse(self.dispatcher._should_use_dispatch_config('/_ah/foo/'))\n self.assertFalse(self.dispatcher._should_use_dispatch_config('/_ah/foo/bar/'))\n self.assertFalse(self.dispatcher._should_use_dispatch_config('/_ah/queue/'))\n", "method_code": " def _should_use_dispatch_config(self, path):\n \"\"\"Determines whether or not to use the dispatch config.\n \n Args:\n path: The request path.\n Returns:\n A Boolean indicating whether or not to use the rules in dispatch config.\n \"\"\"\n if not path.startswith('/_ah/') or any((path.startswith(wl) for wl in DISPATCH_AH_URL_PATH_PREFIX_WHITELIST)):\n return True\n else:\n logging.warning('Skipping dispatch.yaml rules because %s is not a dispatchable path.', path)\n return False\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def _should_use_dispatch_config(self, path): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_should_use_dispatch_config", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001804.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "_resolve_target", "tests": "import unittest\n\nclass Test_resolve_target(unittest.TestCase):\n def test_resolve_target(self):\n servr = object()\n inst = object()\n self.dispatcher._port_registry.add(8080, servr, inst)\n self.mox.StubOutWithMock(self.dispatcher, '_module_for_request')\n self.mox.ReplayAll()\n self.assertEqual((servr, inst), self.dispatcher._resolve_target('localhost:8080', '/foo'))\n self.mox.VerifyAll()\n\n def test_resolve_target_no_hostname(self):\n self.mox.StubOutWithMock(self.dispatcher, '_module_for_request')\n servr = object()\n self.dispatcher._module_for_request('/foo').AndReturn(servr)\n self.mox.ReplayAll()\n self.assertEqual((servr, None), self.dispatcher._resolve_target(None, '/foo'))\n self.mox.VerifyAll()\n\n def test_resolve_target_dispatcher_port(self):\n self.dispatcher._port_registry.add(80, None, None)\n self.mox.StubOutWithMock(self.dispatcher, '_module_for_request')\n servr = object()\n self.dispatcher._module_for_request('/foo').AndReturn(servr)\n self.mox.ReplayAll()\n self.assertEqual((servr, None), self.dispatcher._resolve_target('localhost', '/foo'))\n self.mox.VerifyAll()\n\n def test_resolve_target_module_prefix(self):\n self.mox.StubOutWithMock(self.dispatcher, '_module_for_request')\n self.mox.StubOutWithMock(self.dispatcher, '_get_module_with_soft_routing')\n servr = object()\n self.dispatcher._get_module_with_soft_routing('backend', None).AndReturn(servr)\n self.mox.ReplayAll()\n self.assertEqual((servr, None), self.dispatcher._resolve_target('backend.localhost:1', '/foo'))\n self.mox.VerifyAll()\n", "method_code": " def _resolve_target(self, hostname, path):\n \"\"\"Returns the module and instance that should handle this request.\n \n Args:\n hostname: A string containing the value of the host header in the request\n or None if one was not present.\n path: A string containing the path of the request.\n \n Returns:\n A tuple (_module, inst) where:\n _module: The module.Module that should handle this request.\n inst: The instance.Instance that should handle this request or None if\n the module's load balancing should decide on the instance.\n \n Raises:\n request_info.ModuleDoesNotExistError: if hostname is not known.\n \"\"\"\n if self._port == 80:\n default_address = self.host\n else:\n default_address = '%s:%s' % (self.host, self._port)\n if not hostname or hostname == default_address:\n return (self._module_for_request(path), None)\n default_address_offset = hostname.find(default_address)\n if default_address_offset > 0:\n prefix = hostname[:default_address_offset - 1]\n if '.' in prefix:\n logging.warning('Ignoring instance/version in %s; multiple versions are not supported in devappserver.', prefix)\n module_name = prefix.split('.')[-1]\n return (self._get_module_with_soft_routing(module_name, None), None)\n else:\n if ':' in hostname:\n port = int(hostname.split(':', 1)[1])\n else:\n port = 80\n try:\n _module, inst = self._port_registry.get(port)\n except KeyError:\n raise request_info.ModuleDoesNotExistError(hostname)\n if not _module:\n _module = self._module_for_request(path)\n return (_module, inst)\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def _resolve_target(self, hostname, path): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_resolve_target", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001805.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "_get_module", "tests": "import unittest\n\nclass Test_get_module(unittest.TestCase):\n def test_get_module_non_default(self):\n \"\"\"Tests the _get_module method with a non-default module.\"\"\"\n self.dispatcher._module_name_to_module = {'default': self.module1, 'other': self.module2}\n self.assertEqual(self.dispatcher._get_module('other', None), self.module2)\n self.dispatcher._module_configurations['default'] = MODULE_CONFIGURATIONS[0]\n self.dispatcher._module_configurations['other'] = MODULE_CONFIGURATIONS[1]\n self.assertEqual(self.dispatcher._get_module('other', 'version2'), self.module2)\n self.assertRaises(request_info.VersionDoesNotExistError, self.dispatcher._get_module, 'other', 'version3')\n\n def test_get_module_no_default(self):\n \"\"\"Tests the _get_module method with no default module.\"\"\"\n self.dispatcher._module_name_to_module = {'other': self.module1}\n self.assertEqual(self.dispatcher._get_module('other', None), self.module1)\n self.assertRaises(request_info.ModuleDoesNotExistError, self.dispatcher._get_module, None, None)\n self.dispatcher._module_configurations['other'] = MODULE_CONFIGURATIONS[0]\n self.assertEqual(self.dispatcher._get_module('other', 'version'), self.module1)\n self.assertRaises(request_info.VersionDoesNotExistError, self.dispatcher._get_module, 'other', 'version2')\n", "method_code": " def _get_module(self, module_name, version):\n \"\"\"Attempts to find the specified module.\n \n Args:\n module_name: The name of the module.\n version: The version id.\n Returns:\n Module object.\n Raises:\n request_info.ModuleDoesNotExistError: The module doesn't exist.\n request_info.VersionDoesNotExistError: The version doesn't exist.\n \"\"\"\n if not module_name:\n module_name = appinfo.DEFAULT_MODULE\n if module_name not in self._module_name_to_module:\n raise request_info.ModuleDoesNotExistError()\n if version is not None and version != self._module_configurations[module_name].major_version:\n raise request_info.VersionDoesNotExistError()\n return self._module_name_to_module[module_name]\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def _get_module(self, module_name, version): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_module_non_default", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001806.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "_get_module_with_soft_routing", "tests": "import unittest\n\nclass Test_get_module_with_soft_routing(unittest.TestCase):\n def test_get_module_soft_routing_default_module(self):\n \"\"\"Tests the _get_module_soft_routing method with a default module.\"\"\"\n self.dispatcher._module_name_to_module = {'default': self.module1}\n self.assertEqual(self.dispatcher._get_module_with_soft_routing(None, None), self.module1)\n self.dispatcher._module_name_to_module['other'] = self.module2\n self.assertEqual(self.dispatcher._get_module_with_soft_routing(None, None), self.module1)\n self.dispatcher._module_name_to_module = {'default': self.module1}\n self.assertEqual(self.dispatcher._get_module_with_soft_routing('other', None), self.module1)\n self.dispatcher._module_configurations['default'] = MODULE_CONFIGURATIONS[0]\n self.assertEqual(self.dispatcher._get_module_with_soft_routing('other', 'version'), self.module1)\n self.assertEqual(self.dispatcher._get_module_with_soft_routing('default', 'version'), self.module1)\n self.assertRaises(request_info.VersionDoesNotExistError, self.dispatcher._get_module_with_soft_routing, 'default', 'version2')\n self.assertRaises(request_info.VersionDoesNotExistError, self.dispatcher._get_module_with_soft_routing, 'other', 'version2')\n\n def test_get_module_soft_routing_non_default(self):\n \"\"\"Tests the _get_module_soft_routing method with a non-default module.\"\"\"\n self.dispatcher._module_name_to_module = {'default': self.module1, 'other': self.module2}\n self.assertEqual(self.dispatcher._get_module_with_soft_routing('other', None), self.module2)\n self.dispatcher._module_configurations['default'] = MODULE_CONFIGURATIONS[0]\n self.dispatcher._module_configurations['other'] = MODULE_CONFIGURATIONS[1]\n self.assertEqual(self.dispatcher._get_module_with_soft_routing('other', 'version2'), self.module2)\n self.assertRaises(request_info.VersionDoesNotExistError, self.dispatcher._get_module_with_soft_routing, 'other', 'version3')\n\n def test_get_module_soft_routing_no_default(self):\n \"\"\"Tests the _get_module_soft_routing method with no default module.\"\"\"\n self.dispatcher._module_name_to_module = {'other': self.module1}\n self.assertEqual(self.dispatcher._get_module_with_soft_routing('other', None), self.module1)\n self.assertEqual(self.dispatcher._get_module_with_soft_routing('other', None), self.module1)\n self.dispatcher._module_configurations['other'] = MODULE_CONFIGURATIONS[0]\n self.assertEqual(self.dispatcher._get_module_with_soft_routing('other', 'version'), self.module1)\n self.assertRaises(request_info.VersionDoesNotExistError, self.dispatcher._get_module_with_soft_routing, 'other', 'version2')\n", "method_code": " def _get_module_with_soft_routing(self, module_name, version):\n \"\"\"Uses soft-routing to find the specified module.\n \n Soft-routing is an attempt to match the production resolution order, which\n is slightly more permissive than the Modules API behavior. Here are the\n rules allowed:\n 1. If a module is requested that doesn't exist, use the default module.\n 2. If a module is requested that doesn't exist, and there is no default\n module, use any module.\n \n Args:\n module_name: The name of the module.\n version: The version id.\n Returns:\n Module object.\n Raises:\n request_info.ModuleDoesNotExistError: The module doesn't exist.\n request_info.VersionDoesNotExistError: The version doesn't exist.\n \"\"\"\n if not module_name or module_name not in self._module_name_to_module:\n if appinfo.DEFAULT_MODULE in self._module_name_to_module:\n module_name = appinfo.DEFAULT_MODULE\n elif self._module_name_to_module:\n module_name = self._module_name_to_module.keys()[0]\n else:\n raise request_info.ModuleDoesNotExistError(module_name)\n if version is not None and version != self._module_configurations[module_name].major_version:\n raise request_info.VersionDoesNotExistError()\n return self._module_name_to_module[module_name]\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def _get_module_with_soft_routing(self, module_name, version): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def quit(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_module_soft_routing_default_module", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001807.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/environ_utils.py", "focal_class": null, "focal_method": "propagate_environs", "tests": "import unittest\n\nclass Test_propagate_environs(unittest.TestCase):\n def test_propagate_environs(self):\n src = {'LALA': 'will not propagate', 'HTTP_LALA': 'will propagate', 'HTTP_X_APPENGINE_USER_ID': '12345', 'HTTP_X_APPENGINE_DEV_MYENV': 'will not propagate either'}\n dst = {}\n environ_utils.propagate_environs(src, dst)\n self.assertEqual(dst, {'HTTP_LALA': 'will propagate', 'USER_ID': '12345'})\n", "method_code": "def propagate_environs(src, dst):\n \"\"\"Propagates environment variables to the request handlers.\n\n Propagation rules:\n Environs that do not start with HTTP_ do not propagate.\n Environs formatted like APPENGINE_HEADER_PREFIX + name, where name is one\n of ENVIRONS_TO_PROPAGATE set have APPENGINE_HEADER_PREFIX cut out.\n Internal Dev AppServer environs starting with APPENGINE_DEV_ENVIRON_PREFIX\n do not propagate.\n\n Args:\n src: source environ dict.\n dst: destination environ dict.\n \"\"\"\n for key, value in src.iteritems():\n if key in _ENVIRONS_TO_PROPAGATE_FULL_NAMES:\n dst[key[len(http_runtime_constants.APPENGINE_ENVIRON_PREFIX):]] = value\n elif key.startswith('HTTP_') and (not key.startswith(http_runtime_constants.APPENGINE_DEV_ENVIRON_PREFIX)):\n dst[key] = value", "context": "def propagate_environs(src, dst): ...\ndef propagate_environs(src, dst): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_propagate_environs", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001808.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/instance.py", "focal_class": "google.appengine.tools.devappserver2.instance.Instance", "focal_method": "handle", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_instance_Instance_handle(unittest.TestCase):\n def test_handle(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5)\n self.mox.StubOutWithMock(inst._condition, 'notify')\n self.proxy.start()\n self.environ = {}\n self.request_data.set_request_instance(self.request_id, inst)\n self.proxy.handle(self.environ, self.start_response, self.url_map, self.match, self.request_id, instance.NORMAL_REQUEST).AndReturn(self.response)\n inst._condition.notify()\n self.mox.ReplayAll()\n now = time.time()\n inst._request_history.append((now - 100, now - 80))\n inst.start()\n self.assertTrue(inst.can_accept_requests)\n self.assertEqual(self.response, list(inst.handle(self.environ, self.start_response, self.url_map, self.match, self.request_id, instance.NORMAL_REQUEST)))\n self.mox.VerifyAll()\n self.assertEqual(1, len(inst._request_history))\n self.assertEqual(1, inst.total_requests)\n self.assertEqual(5, inst.remaining_request_capacity)\n self.assertEqual(0, inst.num_outstanding_requests)\n self.assertTrue(0 < inst.get_qps_60s())\n", "method_code": " def handle(self, environ, start_response, url_map, match, request_id, request_type):\n \"\"\"Serves this request by forwarding it to the runtime process.\n \n Args:\n environ: An environ dict for the request as defined in PEP-333.\n start_response: A function with semantics defined in PEP-333.\n url_map: An appinfo.URLMap instance containing the configuration for the\n handler matching this request.\n match: A re.MatchObject containing the result of the matched URL pattern.\n request_id: A unique string id associated with the request.\n request_type: The type of the request. See instance.*_REQUEST module\n constants.\n \n Yields:\n A sequence of strings containing the body of the HTTP response.\n \"\"\"\n raise NotImplementedError()\n ", "context": "class RuntimeProxy(object):\n def handle(self, environ, start_response, url_map, match, request_id, request_type): ...\n def start(self): ...\n def quit(self): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_handle", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001809.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/instance.py", "focal_class": "google.appengine.tools.devappserver2.instance.Instance", "focal_method": "quit", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_instance_Instance_quit(unittest.TestCase):\n def test_handle_after_quit(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5)\n self.mox.StubOutWithMock(inst._condition, 'notify')\n self.mox.StubOutWithMock(inst._condition, 'notify_all')\n self.proxy.start()\n self.proxy.quit()\n inst._condition.notify_all()\n self.mox.ReplayAll()\n inst.start()\n inst.quit()\n self.assertRaises(instance.CannotAcceptRequests, inst.handle, self.environ, self.start_response, self.url_map, self.match, self.request_id, instance.NORMAL_REQUEST)\n self.mox.VerifyAll()\n\n def test_quit(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5)\n self.mox.StubOutWithMock(inst._condition, 'notify_all')\n self.proxy.start()\n self.proxy.quit()\n inst._condition.notify_all()\n self.mox.ReplayAll()\n inst.start()\n self.assertTrue(inst.can_accept_requests)\n inst.quit()\n self.mox.VerifyAll()\n self.assertFalse(inst.can_accept_requests)\n", "method_code": " def quit(self):\n \"\"\"Terminates the runtime process.\"\"\"\n raise NotImplementedError()\n ", "context": "class RuntimeProxy(object):\n def quit(self): ...\n def handle(self, environ, start_response, url_map, match, request_id, request_type): ...\n def start(self): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_handle_after_quit", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001810.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/instance.py", "focal_class": "google.appengine.tools.devappserver2.instance.Instance", "focal_method": "reserve_background_thread", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_instance_Instance_reserve_background_thread(unittest.TestCase):\n def test_reserve_background_thread_success(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5, max_background_threads=2)\n inst._started = True\n self.mox.ReplayAll()\n self.assertEqual(2, inst.remaining_background_thread_capacity)\n inst.reserve_background_thread()\n self.assertEqual(1, inst.remaining_background_thread_capacity)\n self.mox.VerifyAll()\n\n def test_reserve_background_thread_quitting(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5, max_background_threads=2)\n inst._started = True\n inst._quitting = True\n self.mox.ReplayAll()\n self.assertEqual(2, inst.remaining_background_thread_capacity)\n inst.reserve_background_thread()\n self.assertEqual(1, inst.remaining_background_thread_capacity)\n self.mox.VerifyAll()\n\n def test_reserve_background_thread_not_ready(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5, max_background_threads=2, expect_ready_request=True)\n inst._started = True\n self.mox.ReplayAll()\n self.assertEqual(2, inst.remaining_background_thread_capacity)\n inst.reserve_background_thread()\n self.mox.VerifyAll()\n self.assertEqual(1, inst.remaining_background_thread_capacity)\n", "method_code": " def reserve_background_thread(self):\n \"\"\"Reserves a background thread slot.\n \n Raises:\n CannotAcceptRequests: if the Instance is already handling the maximum\n permissible number of background threads or is not in a state where it\n can handle background threads.\n \"\"\"\n with self._condition:\n if self._quit:\n raise CannotAcceptRequests('Instance has been quit')\n if not self._started:\n raise CannotAcceptRequests('Instance has not started')\n if not self.remaining_background_thread_capacity:\n raise CannotAcceptRequests('Instance has no additional background thread capacity')\n self._num_running_background_threads += 1\n ", "context": "class Instance(object):\n def reserve_background_thread(self): ...\n def __init__(self, request_data, instance_id, runtime_proxy, max_concurrent_requests, max_background_threads=0, expect_ready_request=False): ...\n def __repr__(self): ...\n def instance_id(self): ...\n def total_requests(self): ...\n def remaining_request_capacity(self): ...\n def remaining_background_thread_capacity(self): ...\n def num_outstanding_requests(self): ...\n def idle_seconds(self): ...\n def handling_ready_request(self): ...\n def get_latency_60s(self): ...\n def get_qps_60s(self): ...\n def has_quit(self): ...\n def can_accept_requests(self): ...\n def _trim_request_history_to_60s(self): ...\n def start(self): ...\n def quit(self, allow_async=False, force=False, expect_shutdown=False): ...\n def handle(self, environ, start_response, url_map, match, request_id, request_type): ...\n def wait(self, timeout_time): ...\n def set_health(self, health): ...\n def healthy(self): ...\n\n self._request_data = request_data\n self._instance_id = instance_id\n self._max_concurrent_requests = max_concurrent_requests\n self._max_background_threads = max_background_threads\n self._runtime_proxy = runtime_proxy\n self._condition = threading.Condition()\n self._num_outstanding_requests = 0\n self._num_running_background_threads = 0\n self._total_requests = 0\n self._started = False\n self._quitting = False\n self._quit = False\n self._last_request_end_time = time.time()\n self._expecting_ready_request = expect_ready_request\n self._expecting_shutdown_request = False\n self._healthy = True\n self._request_history = collections.deque()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_reserve_background_thread_success", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001811.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/instance.py", "focal_class": "google.appengine.tools.devappserver2.instance.Instance", "focal_method": "set_health", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_instance_Instance_set_health(unittest.TestCase):\n def test_health(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5)\n self.mox.StubOutWithMock(inst._condition, 'notify_all')\n self.proxy.start()\n self.proxy.quit()\n inst._condition.notify_all()\n self.mox.ReplayAll()\n inst.start()\n self.assertTrue(inst.can_accept_requests)\n inst.set_health(False)\n self.assertFalse(inst.can_accept_requests)\n inst.set_health(True)\n self.assertTrue(inst.can_accept_requests)\n", "method_code": " def set_health(self, health):\n self._healthy = health\n ", "context": "class Instance(object):\n def set_health(self, health): ...\n def __init__(self, request_data, instance_id, runtime_proxy, max_concurrent_requests, max_background_threads=0, expect_ready_request=False): ...\n def __repr__(self): ...\n def instance_id(self): ...\n def total_requests(self): ...\n def remaining_request_capacity(self): ...\n def remaining_background_thread_capacity(self): ...\n def num_outstanding_requests(self): ...\n def idle_seconds(self): ...\n def handling_ready_request(self): ...\n def get_latency_60s(self): ...\n def get_qps_60s(self): ...\n def has_quit(self): ...\n def can_accept_requests(self): ...\n def _trim_request_history_to_60s(self): ...\n def start(self): ...\n def quit(self, allow_async=False, force=False, expect_shutdown=False): ...\n def reserve_background_thread(self): ...\n def handle(self, environ, start_response, url_map, match, request_id, request_type): ...\n def wait(self, timeout_time): ...\n def healthy(self): ...\n\n self._request_data = request_data\n self._instance_id = instance_id\n self._max_concurrent_requests = max_concurrent_requests\n self._max_background_threads = max_background_threads\n self._runtime_proxy = runtime_proxy\n self._condition = threading.Condition()\n self._num_outstanding_requests = 0\n self._num_running_background_threads = 0\n self._total_requests = 0\n self._started = False\n self._quitting = False\n self._quit = False\n self._last_request_end_time = time.time()\n self._expecting_ready_request = expect_ready_request\n self._expecting_shutdown_request = False\n self._healthy = True\n self._request_history = collections.deque()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_health", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001812.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/instance.py", "focal_class": "google.appengine.tools.devappserver2.instance.Instance", "focal_method": "get_latency_60s", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_instance_Instance_get_latency_60s(unittest.TestCase):\n def test_get_latency_60s(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5)\n now = time.time()\n inst._request_history = [(now, now + 1), (now + 2, now + 4)]\n self.assertEqual(1.5, inst.get_latency_60s())\n", "method_code": " def get_latency_60s(self):\n \"\"\"Returns the average request latency over the last 60s in seconds.\"\"\"\n with self._condition:\n self._trim_request_history_to_60s()\n if not self._request_history:\n return 0.0\n else:\n total_latency = sum((end - start for start, end in self._request_history))\n return total_latency / len(self._request_history)\n ", "context": "class Instance(object):\n def get_latency_60s(self): ...\n def __init__(self, request_data, instance_id, runtime_proxy, max_concurrent_requests, max_background_threads=0, expect_ready_request=False): ...\n def __repr__(self): ...\n def instance_id(self): ...\n def total_requests(self): ...\n def remaining_request_capacity(self): ...\n def remaining_background_thread_capacity(self): ...\n def num_outstanding_requests(self): ...\n def idle_seconds(self): ...\n def handling_ready_request(self): ...\n def get_qps_60s(self): ...\n def has_quit(self): ...\n def can_accept_requests(self): ...\n def _trim_request_history_to_60s(self): ...\n def start(self): ...\n def quit(self, allow_async=False, force=False, expect_shutdown=False): ...\n def reserve_background_thread(self): ...\n def handle(self, environ, start_response, url_map, match, request_id, request_type): ...\n def wait(self, timeout_time): ...\n def set_health(self, health): ...\n def healthy(self): ...\n\n self._request_data = request_data\n self._instance_id = instance_id\n self._max_concurrent_requests = max_concurrent_requests\n self._max_background_threads = max_background_threads\n self._runtime_proxy = runtime_proxy\n self._condition = threading.Condition()\n self._num_outstanding_requests = 0\n self._num_running_background_threads = 0\n self._total_requests = 0\n self._started = False\n self._quitting = False\n self._quit = False\n self._last_request_end_time = time.time()\n self._expecting_ready_request = expect_ready_request\n self._expecting_shutdown_request = False\n self._healthy = True\n self._request_history = collections.deque()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_latency_60s", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001813.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/instance.py", "focal_class": "google.appengine.tools.devappserver2.instance.Instance", "focal_method": "get_qps_60s", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_instance_Instance_get_qps_60s(unittest.TestCase):\n def test_get_qps_60s(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5)\n now = time.time()\n inst._request_history = [(now, now + 1)] * 120\n self.assertEqual(2.0, inst.get_qps_60s())\n", "method_code": " def get_qps_60s(self):\n \"\"\"Returns the average queries-per-second over the last 60 seconds.\"\"\"\n with self._condition:\n self._trim_request_history_to_60s()\n if not self._request_history:\n return 0.0\n else:\n return len(self._request_history) / 60.0\n ", "context": "class Instance(object):\n def get_qps_60s(self): ...\n def __init__(self, request_data, instance_id, runtime_proxy, max_concurrent_requests, max_background_threads=0, expect_ready_request=False): ...\n def __repr__(self): ...\n def instance_id(self): ...\n def total_requests(self): ...\n def remaining_request_capacity(self): ...\n def remaining_background_thread_capacity(self): ...\n def num_outstanding_requests(self): ...\n def idle_seconds(self): ...\n def handling_ready_request(self): ...\n def get_latency_60s(self): ...\n def has_quit(self): ...\n def can_accept_requests(self): ...\n def _trim_request_history_to_60s(self): ...\n def start(self): ...\n def quit(self, allow_async=False, force=False, expect_shutdown=False): ...\n def reserve_background_thread(self): ...\n def handle(self, environ, start_response, url_map, match, request_id, request_type): ...\n def wait(self, timeout_time): ...\n def set_health(self, health): ...\n def healthy(self): ...\n\n self._request_data = request_data\n self._instance_id = instance_id\n self._max_concurrent_requests = max_concurrent_requests\n self._max_background_threads = max_background_threads\n self._runtime_proxy = runtime_proxy\n self._condition = threading.Condition()\n self._num_outstanding_requests = 0\n self._num_running_background_threads = 0\n self._total_requests = 0\n self._started = False\n self._quitting = False\n self._quit = False\n self._last_request_end_time = time.time()\n self._expecting_ready_request = expect_ready_request\n self._expecting_shutdown_request = False\n self._healthy = True\n self._request_history = collections.deque()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_qps_60s", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001814.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/instance.py", "focal_class": "google.appengine.tools.devappserver2.instance.Instance", "focal_method": "_trim_request_history_to_60s", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_instance_Instance_trim_request_history_to_60s(unittest.TestCase):\n def test__trim_request_history_to_60s(self):\n inst = instance.Instance(self.request_data, 'name', self.proxy, max_concurrent_requests=5)\n inst._request_history.append((0, 100))\n inst._request_history.append((1.0, 101))\n inst._request_history.append((1.2, 102))\n inst._request_history.append((2.5, 103))\n now = time.time()\n inst._request_history.append((now, 42))\n inst._request_history.append((now + 1, 43))\n inst._request_history.append((now + 3, 44))\n inst._request_history.append((now + 4, 45))\n inst._trim_request_history_to_60s()\n self.assertEqual([(now, 42), (now + 1, 43), (now + 3, 44), (now + 4, 45)], list(inst._request_history))\n", "method_code": " def _trim_request_history_to_60s(self):\n \"\"\"Removes obsolete entries from _outstanding_request_history.\"\"\"\n window_start = time.time() - 60\n with self._condition:\n while self._request_history:\n t, _ = self._request_history[0]\n if t < window_start:\n self._request_history.popleft()\n else:\n break\n ", "context": "class Instance(object):\n def _trim_request_history_to_60s(self): ...\n def __init__(self, request_data, instance_id, runtime_proxy, max_concurrent_requests, max_background_threads=0, expect_ready_request=False): ...\n def __repr__(self): ...\n def instance_id(self): ...\n def total_requests(self): ...\n def remaining_request_capacity(self): ...\n def remaining_background_thread_capacity(self): ...\n def num_outstanding_requests(self): ...\n def idle_seconds(self): ...\n def handling_ready_request(self): ...\n def get_latency_60s(self): ...\n def get_qps_60s(self): ...\n def has_quit(self): ...\n def can_accept_requests(self): ...\n def start(self): ...\n def quit(self, allow_async=False, force=False, expect_shutdown=False): ...\n def reserve_background_thread(self): ...\n def handle(self, environ, start_response, url_map, match, request_id, request_type): ...\n def wait(self, timeout_time): ...\n def set_health(self, health): ...\n def healthy(self): ...\n\n self._request_data = request_data\n self._instance_id = instance_id\n self._max_concurrent_requests = max_concurrent_requests\n self._max_background_threads = max_background_threads\n self._runtime_proxy = runtime_proxy\n self._condition = threading.Condition()\n self._num_outstanding_requests = 0\n self._num_running_background_threads = 0\n self._total_requests = 0\n self._started = False\n self._quitting = False\n self._quit = False\n self._last_request_end_time = time.time()\n self._expecting_ready_request = expect_ready_request\n self._expecting_shutdown_request = False\n self._healthy = True\n self._request_history = collections.deque()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test__trim_request_history_to_60s", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001815.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/login.py", "focal_class": null, "focal_method": "_get_user_info_from_dict", "tests": "import unittest\n\nclass Test_get_user_info_from_dict(unittest.TestCase):\n def test_get_user_info_from_dict_admin(self):\n \"\"\"Tests the get_user_info function when the admin field is True.\"\"\"\n cookie_value = '%s:True:%s' % (EMAIL, USER_ID)\n cookie_dict = {'one': 'two', COOKIE_NAME: cookie_value, 'three': 'four'}\n email, admin, user_id = login._get_user_info_from_dict(cookie_dict, cookie_name=COOKIE_NAME)\n self.assertEqual(EMAIL, email)\n self.assertTrue(admin)\n self.assertEqual(USER_ID, user_id)\n\n def test_get_user_info_from_dict_not_admin(self):\n \"\"\"Tests the get_user_info function when the admin field is False.\"\"\"\n cookie_value = '%s:False:%s' % (EMAIL, USER_ID)\n cookie_dict = {'one': 'two', COOKIE_NAME: cookie_value, 'three': 'four'}\n email, admin, user_id = login._get_user_info_from_dict(cookie_dict, cookie_name=COOKIE_NAME)\n self.assertEqual(EMAIL, email)\n self.assertFalse(admin)\n self.assertEqual(USER_ID, user_id)\n", "method_code": "def _get_user_info_from_dict(cookie_dict, cookie_name=_COOKIE_NAME):\n \"\"\"Gets the requestor's user info from a cookie dictionary.\n\n Args:\n cookie_dict: A dictionary mapping cookie names onto values.\n cookie_name: The name of the cookie that stores the user info.\n\n Returns:\n A tuple (email, admin, user_id) where:\n email: The user's email address, if any.\n admin: True if the user is an admin; False otherwise.\n user_id: The user ID, if any.\n \"\"\"\n cookie_value = cookie_dict.get(cookie_name, '')\n email, admin, user_id = (cookie_value.split(':') + ['', '', ''])[:3]\n if '@' not in email:\n if email:\n logging.warning('Ignoring invalid login cookie: %s', cookie_value)\n return ('', False, '')\n return (email, admin == 'True', user_id)", "context": "def _get_user_info_from_dict(cookie_dict, cookie_name=_COOKIE_NAME): ...\ndef get_user_info(http_cookie, cookie_name=_COOKIE_NAME): ...\ndef _get_user_info_from_dict(cookie_dict, cookie_name=_COOKIE_NAME): ...\ndef _create_cookie_data(email, admin): ...\ndef _set_user_info_cookie(email, admin, cookie_name=_COOKIE_NAME): ...\ndef _clear_user_info_cookie(cookie_name=_COOKIE_NAME): ...\ndef _render_login_template(login_url, continue_url, email, admin): ...\ndef login_redirect(application_url, continue_url, start_response): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_user_info_from_dict_admin", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001816.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/login.py", "focal_class": null, "focal_method": "_set_user_info_cookie", "tests": "import unittest\n\nclass Test_set_user_info_cookie(unittest.TestCase):\n def test_set_user_info_cookie(self):\n \"\"\"Tests the set_user_info_cookie function.\"\"\"\n cookie_value = '%s:True:%s' % (EMAIL, USER_ID)\n expected_result = '%s=\"%s\"; Path=/' % (COOKIE_NAME, cookie_value)\n result = login._set_user_info_cookie(EMAIL, True, cookie_name=COOKIE_NAME)\n self.assertEqual(expected_result, result)\n", "method_code": "def _set_user_info_cookie(email, admin, cookie_name=_COOKIE_NAME):\n \"\"\"Creates a cookie to set the user information for the requestor.\n\n Args:\n email: The email to set for the user.\n admin: True if the user should be admin; False otherwise.\n cookie_name: The name of the cookie that stores the user info.\n\n Returns:\n Set-Cookie value for setting the user info of the requestor.\n \"\"\"\n cookie_value = _create_cookie_data(email, admin)\n cookie = Cookie.SimpleCookie()\n cookie[cookie_name] = cookie_value\n cookie[cookie_name]['path'] = '/'\n return cookie[cookie_name].OutputString()", "context": "def _set_user_info_cookie(email, admin, cookie_name=_COOKIE_NAME): ...\ndef get_user_info(http_cookie, cookie_name=_COOKIE_NAME): ...\ndef _get_user_info_from_dict(cookie_dict, cookie_name=_COOKIE_NAME): ...\ndef _create_cookie_data(email, admin): ...\ndef _set_user_info_cookie(email, admin, cookie_name=_COOKIE_NAME): ...\ndef _clear_user_info_cookie(cookie_name=_COOKIE_NAME): ...\ndef _render_login_template(login_url, continue_url, email, admin): ...\ndef login_redirect(application_url, continue_url, start_response): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_set_user_info_cookie", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001817.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/login.py", "focal_class": null, "focal_method": "_clear_user_info_cookie", "tests": "import unittest\n\nclass Test_clear_user_info_cookie(unittest.TestCase):\n def test_clear_user_info_cookie(self):\n \"\"\"Tests the clear_user_info_cookie function.\"\"\"\n expected_result = '%s=; Max-Age=0; Path=/' % COOKIE_NAME\n result = login._clear_user_info_cookie(cookie_name=COOKIE_NAME)\n self.assertEqual(expected_result, result)\n", "method_code": "def _clear_user_info_cookie(cookie_name=_COOKIE_NAME):\n \"\"\"Clears the user info cookie from the requestor, logging them out.\n\n Args:\n cookie_name: The name of the cookie that stores the user info.\n\n Returns:\n A Set-Cookie value for clearing the user info of the requestor.\n \"\"\"\n cookie = Cookie.SimpleCookie()\n cookie[cookie_name] = ''\n cookie[cookie_name]['path'] = '/'\n cookie[cookie_name]['max-age'] = '0'\n return cookie[cookie_name].OutputString()", "context": "def _clear_user_info_cookie(cookie_name=_COOKIE_NAME): ...\ndef get_user_info(http_cookie, cookie_name=_COOKIE_NAME): ...\ndef _get_user_info_from_dict(cookie_dict, cookie_name=_COOKIE_NAME): ...\ndef _create_cookie_data(email, admin): ...\ndef _set_user_info_cookie(email, admin, cookie_name=_COOKIE_NAME): ...\ndef _clear_user_info_cookie(cookie_name=_COOKIE_NAME): ...\ndef _render_login_template(login_url, continue_url, email, admin): ...\ndef login_redirect(application_url, continue_url, start_response): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_clear_user_info_cookie", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001818.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/shutdown.py", "focal_class": null, "focal_method": "async_quit", "tests": "import unittest\n\nclass Test_async_quit(unittest.TestCase):\n def test_async_quit(self):\n self.mox.ReplayAll()\n shutdown.async_quit()\n self.assertTrue(shutdown._shutting_down)\n self.mox.VerifyAll()\n", "method_code": "def async_quit():\n \"\"\"Quits the development server asynchronously in an organized fashion.\n\n Requests in progress may be dropped.\n \"\"\"\n global _shutting_down\n _shutting_down = True", "context": "def async_quit(): ...\ndef async_quit(): ...\ndef _async_terminate(*_): ...\ndef wait_until_shutdown(): ...\ndef install_signal_handlers(): ...\ndef shutting_down(): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_async_quit", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001819.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/shutdown.py", "focal_class": null, "focal_method": "_async_terminate", "tests": "import unittest\n\nclass Test_async_terminate(unittest.TestCase):\n def test_async_terminate(self):\n self.mox.ReplayAll()\n shutdown._async_terminate()\n self.assertTrue(shutdown._shutting_down)\n shutdown._async_terminate()\n self.mox.VerifyAll()\n", "method_code": "def _async_terminate(*_):\n async_quit()\n global _num_terminate_requests\n _num_terminate_requests += 1\n if _num_terminate_requests == 1:\n logging.info('Shutting down.')\n if _num_terminate_requests >= 3:\n logging.error('Received third interrupt signal. Terminating.')\n os.abort()", "context": "def _async_terminate(*_): ...\ndef async_quit(): ...\ndef _async_terminate(*_): ...\ndef wait_until_shutdown(): ...\ndef install_signal_handlers(): ...\ndef shutting_down(): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_async_terminate", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001820.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/shutdown.py", "focal_class": null, "focal_method": "install_signal_handlers", "tests": "import unittest\n\nclass Test_install_signal_handlers(unittest.TestCase):\n def test_install_signal_handlers(self):\n shutdown.install_signal_handlers()\n self.assertEqual(shutdown._async_terminate, signal.getsignal(signal.SIGINT))\n self.assertEqual(shutdown._async_terminate, signal.getsignal(signal.SIGTERM))\n", "method_code": "def install_signal_handlers():\n \"\"\"Installs a signal handler for SIGTERM and SIGINT to do orderly shutdown.\"\"\"\n signal.signal(signal.SIGTERM, _async_terminate)\n signal.signal(signal.SIGINT, _async_terminate)", "context": "def install_signal_handlers(): ...\ndef async_quit(): ...\ndef _async_terminate(*_): ...\ndef wait_until_shutdown(): ...\ndef install_signal_handlers(): ...\ndef shutting_down(): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_install_signal_handlers", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001821.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/shutdown.py", "focal_class": null, "focal_method": "wait_until_shutdown", "tests": "import unittest\n\nclass Test_wait_until_shutdown(unittest.TestCase):\n def test_wait_until_shutdown(self):\n self.mox.StubOutWithMock(time, 'sleep')\n time.sleep(1).WithSideEffects(lambda _: shutdown.async_quit())\n self.mox.ReplayAll()\n shutdown.wait_until_shutdown()\n self.mox.VerifyAll()\n", "method_code": "def wait_until_shutdown():\n while not _shutting_down:\n try:\n time.sleep(1)\n except IOError:\n pass", "context": "def wait_until_shutdown(): ...\ndef async_quit(): ...\ndef _async_terminate(*_): ...\ndef wait_until_shutdown(): ...\ndef install_signal_handlers(): ...\ndef shutting_down(): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_wait_until_shutdown", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001822.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/start_response_utils.py", "focal_class": "google.appengine.tools.devappserver2.start_response_utils.CapturingStartResponse", "focal_method": "merged_response", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_start_response_utils_CapturingStartResponse_merged_response(unittest.TestCase):\n def test_merged_response(self):\n start_response = start_response_utils.CapturingStartResponse()\n stream = start_response('200 OK', [('header1', 'value1')])\n stream.write('Hello World!')\n self.assertEqual('Hello World! Goodbye World!', start_response.merged_response([' Goodbye ', 'World!']))\n", "method_code": " def merged_response(self, response):\n \"\"\"Merge the response stream and the values returned by the WSGI app.\"\"\"\n return self.response_stream.getvalue() + ''.join(response)\n ", "context": "class CapturingStartResponse(object):\n def merged_response(self, response): ...\n def __init__(self): ...\n def __call__(self, status, response_headers, exc_info=None): ...\n\n self.status = None\n self.response_headers = None\n self.exc_info = None\n self.response_stream = cStringIO.StringIO()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_merged_response", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001823.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/url_handler.py", "focal_class": "google.appengine.tools.devappserver2.url_handler.URLHandler", "focal_method": "match", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_url_handler_URLHandler_match(unittest.TestCase):\n def test_match(self):\n handler = url_handler.URLHandler(re.compile('/(foo|bar).*'))\n self.assertTrue(handler.match('/foo'))\n self.assertTrue(handler.match('/bar'))\n self.assertTrue(handler.match('/foo/baz'))\n self.assertTrue(handler.match('/bar/baz'))\n self.assertFalse(handler.match('/baz'))\n self.assertFalse(handler.match('/baz/baz'))\n", "method_code": " def match(self, url):\n \"\"\"Tests whether a given URL string matches this handler.\n \n Args:\n url: A URL string to match.\n Returns:\n A re.MatchObject containing the result of the match, if the URL string\n matches this handler. None, otherwise.\n \"\"\"\n return self._url_pattern.match(url)\n ", "context": "class URLHandler(object):\n def match(self, url): ...\n def __init__(self, url_pattern): ...\n def handle_authorization(self, environ, start_response): ...\n def handle(self, match, environ, start_response): ...\n\n self._url_pattern = url_pattern\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_match", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001824.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/util.py", "focal_class": null, "focal_method": "get_headers_from_environ", "tests": "import unittest\n\nclass Test_get_headers_from_environ(unittest.TestCase):\n def test_get_headers_from_environ(self):\n environ = {'SERVER_PORT': '42', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', 'CONTENT_TYPE': 'application/json', 'HTTP_CONTENT_LENGTH': '0', 'HTTP_X_USER_IP': '127.0.0.1'}\n headers = util.get_headers_from_environ(environ)\n self.assertEqual(len(headers), 3)\n self.assertEqual(headers['Content-Type'], 'application/json')\n self.assertEqual(headers['Content-Length'], '0')\n self.assertEqual(headers['X-User-IP'], '127.0.0.1')\n", "method_code": "def get_headers_from_environ(environ):\n \"\"\"Get a wsgiref.headers.Headers object with headers from the environment.\n\n Headers in environ are prefixed with 'HTTP_', are all uppercase, and have\n had dashes replaced with underscores. This strips the HTTP_ prefix and\n changes underscores back to dashes before adding them to the returned set\n of headers.\n\n Args:\n environ: An environ dict for the request as defined in PEP-333.\n\n Returns:\n A wsgiref.headers.Headers object that's been filled in with any HTTP\n headers found in environ.\n \"\"\"\n headers = wsgiref.headers.Headers([])\n for header, value in environ.iteritems():\n if header.startswith('HTTP_'):\n headers[header[5:].replace('_', '-')] = value\n if 'CONTENT_TYPE' in environ:\n headers['CONTENT-TYPE'] = environ['CONTENT_TYPE']\n return headers", "context": "def get_headers_from_environ(environ): ...\ndef get_headers_from_environ(environ): ...\ndef put_headers_in_environ(headers, environ): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_headers_from_environ", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001825.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/util.py", "focal_class": null, "focal_method": "put_headers_in_environ", "tests": "import unittest\n\nclass Test_put_headers_in_environ(unittest.TestCase):\n def test_put_headers_in_environ(self):\n environ = {'SERVER_PORT': '42', 'REQUEST_METHOD': 'GET'}\n headers = wsgiref.headers.Headers([])\n headers['Content-Length'] = '2'\n headers['X-User-IP'] = '127.0.0.1'\n headers['Access-Control-Allow-Origin'] = 'google.com'\n util.put_headers_in_environ(headers.items(), environ)\n self.assertEqual(environ, {'SERVER_PORT': '42', 'REQUEST_METHOD': 'GET', 'HTTP_CONTENT_LENGTH': '2', 'HTTP_X_USER_IP': '127.0.0.1', 'HTTP_ACCESS_CONTROL_ALLOW_ORIGIN': 'google.com'})\n", "method_code": "def put_headers_in_environ(headers, environ):\n \"\"\"Given a list of headers, put them into environ based on PEP-333.\n\n This converts headers to uppercase, prefixes them with 'HTTP_', and\n converts dashes to underscores before adding them to the environ dict.\n\n Args:\n headers: A list of (header, value) tuples. The HTTP headers to add to the\n environment.\n environ: An environ dict for the request as defined in PEP-333.\n \"\"\"\n for key, value in headers:\n environ['HTTP_%s' % key.upper().replace('-', '_')] = value", "context": "def put_headers_in_environ(headers, environ): ...\ndef get_headers_from_environ(environ): ...\ndef put_headers_in_environ(headers, environ): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_put_headers_in_environ", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001826.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_request_info.py", "focal_class": null, "focal_method": "get_request_url", "tests": "import unittest\n\nclass Test_get_request_url(unittest.TestCase):\n def test_get_request_url(self):\n with self.request_info.request(self._create_environ('https', 'machine:8080', '/foo', 'bar=baz'), self._create_module_configuration('default', '1')) as request_id:\n self._assert_request_id(request_id)\n self.assertEqual('https://machine:8080/foo?bar=baz', self.request_info.get_request_url(request_id))\n", "method_code": " def get_request_url(self, request_id):\n \"\"\"Returns the URL the request e.g. 'http://localhost:8080/foo?bar=baz'.\n \n Args:\n request_id: The string id of the request making the API call.\n \n Returns:\n The URL of the request as a string.\n \"\"\"\n with self._lock:\n environ = self._request_wsgi_environ[request_id]\n return wsgiref.util.request_uri(environ)\n ", "context": "class WSGIRequestInfo(request_info.RequestInfo):\n def get_request_url(self, request_id): ...\n def __init__(self, dispatcher): ...\n def request(self, environ, module_configuration): ...\n def start_request(self, environ, module_configuration): ...\n def end_request(self, request_id): ...\n def set_request_instance(self, request_id, instance): ...\n def register_request_id(self, environ, request_id): ...\n def get_request_environ(self, request_id): ...\n def get_dispatcher(self): ...\n def get_module(self, request_id): ...\n def get_version(self, request_id): ...\n def get_instance(self, request_id): ...\n def set_filesapi_used(self, request_id): ...\n def was_filesapi_used(self, request_id): ...\n\n self._request_wsgi_environ = {}\n self._request_id_to_module_configuration = {}\n self._request_id_to_instance = {}\n self._request_id_used_filesapi = set()\n self._lock = threading.Lock()\n self._dispatcher = dispatcher\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_request_url", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001827.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_request_info.py", "focal_class": null, "focal_method": "get_request_environ", "tests": "import unittest\n\nclass Test_get_request_environ(unittest.TestCase):\n def test_get_request_environ(self):\n environ = object()\n with self.request_info.request(environ, self._create_module_configuration('default', '1')) as request_id:\n self._assert_request_id(request_id)\n self.assertIs(environ, self.request_info.get_request_environ(request_id))\n", "method_code": " def get_request_environ(self, request_id):\n \"\"\"Returns a dict containing the WSGI environ for the request.\"\"\"\n with self._lock:\n return self._request_wsgi_environ[request_id]\n ", "context": "class WSGIRequestInfo(request_info.RequestInfo):\n def get_request_environ(self, request_id): ...\n def __init__(self, dispatcher): ...\n def request(self, environ, module_configuration): ...\n def start_request(self, environ, module_configuration): ...\n def end_request(self, request_id): ...\n def set_request_instance(self, request_id, instance): ...\n def get_request_url(self, request_id): ...\n def register_request_id(self, environ, request_id): ...\n def get_dispatcher(self): ...\n def get_module(self, request_id): ...\n def get_version(self, request_id): ...\n def get_instance(self, request_id): ...\n def set_filesapi_used(self, request_id): ...\n def was_filesapi_used(self, request_id): ...\n\n self._request_wsgi_environ = {}\n self._request_id_to_module_configuration = {}\n self._request_id_to_instance = {}\n self._request_id_used_filesapi = set()\n self._lock = threading.Lock()\n self._dispatcher = dispatcher\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_request_environ", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001828.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_request_info.py", "focal_class": null, "focal_method": "get_dispatcher", "tests": "import unittest\n\nclass Test_get_dispatcher(unittest.TestCase):\n def test_get_dispatcher(self):\n with self.request_info.request(self._create_environ('https', 'machine:8080', '/foo', 'bar=baz'), self._create_module_configuration('default', '1')) as request_id:\n self._assert_request_id(request_id)\n self.assertEqual(self.dispatcher, self.request_info.get_dispatcher())\n", "method_code": " def get_dispatcher(self):\n \"\"\"Returns the Dispatcher.\n \n Returns:\n The Dispatcher instance.\n \"\"\"\n return self._dispatcher\n ", "context": "class WSGIRequestInfo(request_info.RequestInfo):\n def get_dispatcher(self): ...\n def __init__(self, dispatcher): ...\n def request(self, environ, module_configuration): ...\n def start_request(self, environ, module_configuration): ...\n def end_request(self, request_id): ...\n def set_request_instance(self, request_id, instance): ...\n def get_request_url(self, request_id): ...\n def register_request_id(self, environ, request_id): ...\n def get_request_environ(self, request_id): ...\n def get_module(self, request_id): ...\n def get_version(self, request_id): ...\n def get_instance(self, request_id): ...\n def set_filesapi_used(self, request_id): ...\n def was_filesapi_used(self, request_id): ...\n\n self._request_wsgi_environ = {}\n self._request_id_to_module_configuration = {}\n self._request_id_to_instance = {}\n self._request_id_used_filesapi = set()\n self._lock = threading.Lock()\n self._dispatcher = dispatcher\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_dispatcher", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001829.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_request_info.py", "focal_class": null, "focal_method": "get_module", "tests": "import unittest\n\nclass Test_get_module(unittest.TestCase):\n def test_get_module(self):\n with self.request_info.request(self._create_environ('https', 'machine:8080', '/foo', 'bar=baz'), self._create_module_configuration('default', '1')) as request_id:\n self._assert_request_id(request_id)\n self.assertEqual('default', self.request_info.get_module(request_id))\n", "method_code": " def get_module(self, request_id):\n \"\"\"Returns the name of the module serving this request.\n \n Args:\n request_id: The string id of the request making the API call.\n \n Returns:\n A str containing the module name.\n \"\"\"\n with self._lock:\n return self._request_id_to_module_configuration[request_id].module_name\n ", "context": "class WSGIRequestInfo(request_info.RequestInfo):\n def get_module(self, request_id): ...\n def __init__(self, dispatcher): ...\n def request(self, environ, module_configuration): ...\n def start_request(self, environ, module_configuration): ...\n def end_request(self, request_id): ...\n def set_request_instance(self, request_id, instance): ...\n def get_request_url(self, request_id): ...\n def register_request_id(self, environ, request_id): ...\n def get_request_environ(self, request_id): ...\n def get_dispatcher(self): ...\n def get_version(self, request_id): ...\n def get_instance(self, request_id): ...\n def set_filesapi_used(self, request_id): ...\n def was_filesapi_used(self, request_id): ...\n\n self._request_wsgi_environ = {}\n self._request_id_to_module_configuration = {}\n self._request_id_to_instance = {}\n self._request_id_used_filesapi = set()\n self._lock = threading.Lock()\n self._dispatcher = dispatcher\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_module", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001830.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_request_info.py", "focal_class": null, "focal_method": "get_version", "tests": "import unittest\n\nclass Test_get_version(unittest.TestCase):\n def test_get_version(self):\n with self.request_info.request(self._create_environ('https', 'machine:8080', '/foo', 'bar=baz'), self._create_module_configuration('default', '1')) as request_id:\n self._assert_request_id(request_id)\n self.assertEqual('1', self.request_info.get_version(request_id))\n", "method_code": " def get_version(self, request_id):\n \"\"\"Returns the version of the module serving this request.\n \n Args:\n request_id: The string id of the request making the API call.\n \n Returns:\n A str containing the version.\n \"\"\"\n with self._lock:\n return self._request_id_to_module_configuration[request_id].major_version\n ", "context": "class WSGIRequestInfo(request_info.RequestInfo):\n def get_version(self, request_id): ...\n def __init__(self, dispatcher): ...\n def request(self, environ, module_configuration): ...\n def start_request(self, environ, module_configuration): ...\n def end_request(self, request_id): ...\n def set_request_instance(self, request_id, instance): ...\n def get_request_url(self, request_id): ...\n def register_request_id(self, environ, request_id): ...\n def get_request_environ(self, request_id): ...\n def get_dispatcher(self): ...\n def get_module(self, request_id): ...\n def get_instance(self, request_id): ...\n def set_filesapi_used(self, request_id): ...\n def was_filesapi_used(self, request_id): ...\n\n self._request_wsgi_environ = {}\n self._request_id_to_module_configuration = {}\n self._request_id_to_instance = {}\n self._request_id_used_filesapi = set()\n self._lock = threading.Lock()\n self._dispatcher = dispatcher\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_version", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001831.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_request_info.py", "focal_class": null, "focal_method": "get_instance", "tests": "import unittest\n\nclass Test_get_instance(unittest.TestCase):\n def test_get_instance_unset(self):\n with self.request_info.request(self._create_environ('https', 'machine:8080', '/foo', 'bar=baz'), self._create_module_configuration('default', '1')) as request_id:\n self._assert_request_id(request_id)\n self.assertIsNone(self.request_info.get_instance(request_id))\n\n def test_get_instance(self):\n with self.request_info.request(self._create_environ('https', 'machine:8080', '/foo', 'bar=baz'), self._create_module_configuration('default', '1')) as request_id:\n instance = object()\n self.request_info.set_request_instance(request_id, instance)\n self._assert_request_id(request_id)\n self.assertEqual(instance, self.request_info.get_instance(request_id))\n", "method_code": " def get_instance(self, request_id):\n \"\"\"Returns the instance serving this request.\n \n Args:\n request_id: The string id of the request making the API call.\n \n Returns:\n The instance.Instance serving this request or None if no instance is\n serving it.\n \"\"\"\n with self._lock:\n return self._request_id_to_instance.get(request_id, None)\n ", "context": "class WSGIRequestInfo(request_info.RequestInfo):\n def get_instance(self, request_id): ...\n def __init__(self, dispatcher): ...\n def request(self, environ, module_configuration): ...\n def start_request(self, environ, module_configuration): ...\n def end_request(self, request_id): ...\n def set_request_instance(self, request_id, instance): ...\n def get_request_url(self, request_id): ...\n def register_request_id(self, environ, request_id): ...\n def get_request_environ(self, request_id): ...\n def get_dispatcher(self): ...\n def get_module(self, request_id): ...\n def get_version(self, request_id): ...\n def set_filesapi_used(self, request_id): ...\n def was_filesapi_used(self, request_id): ...\n\n self._request_wsgi_environ = {}\n self._request_id_to_module_configuration = {}\n self._request_id_to_instance = {}\n self._request_id_used_filesapi = set()\n self._lock = threading.Lock()\n self._dispatcher = dispatcher\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_instance_unset", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001832.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_request_info.py", "focal_class": null, "focal_method": "end_request", "tests": "import unittest\n\nclass Test_end_request(unittest.TestCase):\n def test_concurrent_requests(self):\n request_id1 = self.request_info.start_request(self._create_environ('http', 'machine:8081'), self._create_module_configuration('default', '1'))\n request_id2 = self.request_info.start_request(self._create_environ('http', 'machine:8082'), self._create_module_configuration('default', '2'))\n request_id3 = self.request_info.start_request(self._create_environ('http', 'machine:8083'), self._create_module_configuration('other', '1'))\n self._assert_request_id(request_id1)\n self._assert_request_id(request_id2)\n self._assert_request_id(request_id3)\n self.assertTrue(request_id1 != request_id2 != request_id3)\n self.assertEqual('http://machine:8081/', self.request_info.get_request_url(request_id1))\n self.assertEqual(self.dispatcher, self.request_info.get_dispatcher())\n self.assertEqual('default', self.request_info.get_module(request_id1))\n self.assertEqual('1', self.request_info.get_version(request_id1))\n self.assertEqual('http://machine:8082/', self.request_info.get_request_url(request_id2))\n self.assertEqual(self.dispatcher, self.request_info.get_dispatcher())\n self.assertEqual('default', self.request_info.get_module(request_id2))\n self.assertEqual('2', self.request_info.get_version(request_id2))\n self.request_info.end_request(request_id1)\n self.request_info.end_request(request_id2)\n self.assertEqual('http://machine:8083/', self.request_info.get_request_url(request_id3))\n self.assertEqual(self.dispatcher, self.request_info.get_dispatcher())\n self.assertEqual('other', self.request_info.get_module(request_id3))\n self.assertEqual('1', self.request_info.get_version(request_id3))\n", "method_code": " def end_request(self, request_id):\n \"\"\"Removes the information associated with given request_id.\"\"\"\n with self._lock:\n del self._request_wsgi_environ[request_id]\n del self._request_id_to_module_configuration[request_id]\n if request_id in self._request_id_to_instance:\n del self._request_id_to_instance[request_id]\n self._request_id_used_filesapi.discard(request_id)\n ", "context": "class WSGIRequestInfo(request_info.RequestInfo):\n def end_request(self, request_id): ...\n def __init__(self, dispatcher): ...\n def request(self, environ, module_configuration): ...\n def start_request(self, environ, module_configuration): ...\n def set_request_instance(self, request_id, instance): ...\n def get_request_url(self, request_id): ...\n def register_request_id(self, environ, request_id): ...\n def get_request_environ(self, request_id): ...\n def get_dispatcher(self): ...\n def get_module(self, request_id): ...\n def get_version(self, request_id): ...\n def get_instance(self, request_id): ...\n def set_filesapi_used(self, request_id): ...\n def was_filesapi_used(self, request_id): ...\n\n self._request_wsgi_environ = {}\n self._request_id_to_module_configuration = {}\n self._request_id_to_instance = {}\n self._request_id_used_filesapi = set()\n self._lock = threading.Lock()\n self._dispatcher = dispatcher\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_concurrent_requests", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001833.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "set_app", "tests": "import unittest\n\nclass Test_set_app(unittest.TestCase):\n def test_set_app(self):\n self.server.set_app(self.other_wsgi_application)\n result = urllib2.urlopen('http://localhost:%d/foo?bar=baz' % self.server.port)\n body = result.read()\n self.assertEqual(200, result.code)\n self.assertEqual('Hello World', body)\n", "method_code": " def set_app(self, app):\n \"\"\"Sets the PEP-333 app to use to serve requests.\"\"\"\n with self._lock:\n self._app = app\n ", "context": "class _SingleAddressWsgiServer(wsgiserver.CherryPyWSGIServer):\n def set_app(self, app): ...\n def __init__(self, host, app): ...\n def start(self): ...\n def quit(self): ...\n def port(self): ...\n def set_error(self, error): ...\n def __call__(self, environ, start_response): ...\n\n self._lock = threading.Lock()\n self._app = app\n self._error = None\n self.requests = _SharedCherryPyThreadPool()\n self.software = http_runtime_constants.SERVER_SOFTWARE\n self.request_queue_size = 100\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_set_app", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001834.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "set_error", "tests": "import unittest\n\nclass Test_set_error(unittest.TestCase):\n def test_set_error(self):\n self.server.set_error(204)\n result = urllib2.urlopen('http://localhost:%d/foo?bar=baz' % self.server.port)\n self.assertEqual(204, result.code)\n", "method_code": " def set_error(self, error):\n \"\"\"Sets the HTTP status code to serve for all requests.\"\"\"\n with self._lock:\n self._error = error\n self._app = None\n ", "context": "class _SingleAddressWsgiServer(wsgiserver.CherryPyWSGIServer):\n def set_error(self, error): ...\n def __init__(self, host, app): ...\n def start(self): ...\n def quit(self): ...\n def port(self): ...\n def set_app(self, app): ...\n def __call__(self, environ, start_response): ...\n\n self._lock = threading.Lock()\n self._app = app\n self._error = None\n self.requests = _SharedCherryPyThreadPool()\n self.software = http_runtime_constants.SERVER_SOFTWARE\n self.request_queue_size = 100\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_set_error", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001835.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "put", "tests": "import unittest\n\nclass Test_put(unittest.TestCase):\n def test_put(self):\n connection = object()\n wsgi_server._THREAD_POOL.submit(self.thread_pool._handle, connection)\n self.mox.ReplayAll()\n self.thread_pool.put(connection)\n self.mox.VerifyAll()\n self.assertEqual(set([connection]), self.thread_pool._connections)\n", "method_code": " def put(self, obj):\n with self._condition:\n self._connections.add(obj)\n _THREAD_POOL.submit(self._handle, obj)\n ", "context": "class _SharedCherryPyThreadPool(object):\n def put(self, obj): ...\n def __init__(self): ...\n def stop(self, timeout=5): ...\n def _shutdown_connection(connection): ...\n def _handle(self, obj): ...\n\n self._condition = threading.Condition()\n self._connections = set()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_put", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001836.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "_handle", "tests": "import unittest\n\nclass Test_handle(unittest.TestCase):\n def test_handle(self):\n connection = self.mox.CreateMock(wsgiserver.HTTPConnection)\n self.mox.StubOutWithMock(self.thread_pool._condition, 'notify')\n self.thread_pool._connections.add(connection)\n connection.communicate()\n connection.close()\n self.thread_pool._condition.notify()\n self.mox.ReplayAll()\n self.thread_pool._handle(connection)\n self.mox.VerifyAll()\n self.assertEqual(set(), self.thread_pool._connections)\n", "method_code": " def _handle(self, obj):\n try:\n obj.communicate()\n finally:\n obj.close()\n with self._condition:\n self._connections.remove(obj)\n self._condition.notify()\n ", "context": "class _SharedCherryPyThreadPool(object):\n def _handle(self, obj): ...\n def __init__(self): ...\n def stop(self, timeout=5): ...\n def _shutdown_connection(connection): ...\n def put(self, obj): ...\n\n self._condition = threading.Condition()\n self._connections = set()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_handle", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001837.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "stop", "tests": "import unittest\n\nclass Test_stop(unittest.TestCase):\n def test_stop(self):\n self.mox.ReplayAll()\n self.thread_pool.stop(3)\n self.mox.VerifyAll()\n", "method_code": " def stop(self, timeout=5):\n timeout_time = time.time() + timeout\n with self._condition:\n while self._connections and time.time() < timeout_time:\n self._condition.wait(timeout_time - time.time())\n for connection in self._connections:\n self._shutdown_connection(connection)\n ", "context": "class _SharedCherryPyThreadPool(object):\n def stop(self, timeout=5): ...\n def __init__(self): ...\n def _shutdown_connection(connection): ...\n def put(self, obj): ...\n def _handle(self, obj): ...\n\n self._condition = threading.Condition()\n self._connections = set()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_stop", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001838.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "_shutdown_connection", "tests": "import unittest\n\nclass Test_shutdown_connection(unittest.TestCase):\n def test_stop_with_connections(self):\n connection = self.mox.CreateMock(wsgiserver.HTTPConnection)\n self.thread_pool._connections.add(connection)\n self.mox.StubOutWithMock(self.thread_pool, '_shutdown_connection')\n self.thread_pool._shutdown_connection(connection)\n self.mox.ReplayAll()\n self.thread_pool.stop(1)\n self.mox.VerifyAll()\n\n def test_shutdown_connection(self):\n\n class DummyObect(object):\n pass\n connection = DummyObect()\n connection.rfile = DummyObect()\n connection.rfile.closed = False\n connection.socket = self.mox.CreateMockAnything()\n connection.socket.shutdown(socket.SHUT_RD)\n self.mox.ReplayAll()\n self.thread_pool._shutdown_connection(connection)\n self.mox.VerifyAll()\n\n def test_shutdown_connection_rfile_already_close(self):\n\n class DummyObect(object):\n pass\n connection = DummyObect()\n connection.rfile = DummyObect()\n connection.rfile.closed = True\n connection.socket = self.mox.CreateMockAnything()\n self.mox.ReplayAll()\n self.thread_pool._shutdown_connection(connection)\n self.mox.VerifyAll()\n", "method_code": " def _shutdown_connection(connection):\n if not connection.rfile.closed:\n connection.socket.shutdown(socket.SHUT_RD)\n ", "context": "class _SharedCherryPyThreadPool(object):\n @staticmethod\n def _shutdown_connection(connection): ...\n def __init__(self): ...\n def stop(self, timeout=5): ...\n def put(self, obj): ...\n def _handle(self, obj): ...\n\n self._condition = threading.Condition()\n self._connections = set()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_stop_with_connections", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001839.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "add_socket", "tests": "import unittest\n\nclass Test_add_socket(unittest.TestCase):\n def test_add_socket(self):\n file_descriptors = self.select_thread._file_descriptors\n file_descriptor_to_callback = self.select_thread._file_descriptor_to_callback\n file_descriptors_copy = frozenset(self.select_thread._file_descriptors)\n file_descriptor_to_callback_copy = self.select_thread._file_descriptor_to_callback.copy()\n s = self._MockSocket()\n callback = object()\n self.select_thread.add_socket(s, callback)\n self.assertEqual(file_descriptors_copy, file_descriptors)\n self.assertEqual(file_descriptor_to_callback_copy, file_descriptor_to_callback)\n self.assertEqual(frozenset([s.fileno()]), self.select_thread._file_descriptors)\n self.assertEqual({s.fileno(): callback}, self.select_thread._file_descriptor_to_callback)\n", "method_code": " def add_socket(self, s, callback):\n \"\"\"Add a new socket to watch.\n \n Args:\n s: A socket to select on.\n callback: A callable with no args to be called when s is ready for a read.\n \"\"\"\n with self._lock:\n self._file_descriptors = self._file_descriptors.union([s.fileno()])\n new_file_descriptor_to_callback = self._file_descriptor_to_callback.copy()\n new_file_descriptor_to_callback[s.fileno()] = callback\n self._file_descriptor_to_callback = new_file_descriptor_to_callback\n ", "context": "class SelectThread(object):\n def add_socket(self, s, callback): ...\n def __init__(self): ...\n def start(self): ...\n def remove_socket(self, s): ...\n def _loop_forever(self): ...\n def _select(self): ...\n\n self._lock = threading.Lock()\n self._file_descriptors = frozenset()\n self._file_descriptor_to_callback = {}\n self._select_thread = threading.Thread(target=self._loop_forever, name='WSGI select')\n self._select_thread.daemon = True\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_add_socket", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001840.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "remove_socket", "tests": "import unittest\n\nclass Test_remove_socket(unittest.TestCase):\n def test_remove_socket(self):\n s1 = self._MockSocket()\n callback1 = object()\n s2 = self._MockSocket()\n callback2 = object()\n self.select_thread._file_descriptors = frozenset([s1.fileno(), s2.fileno()])\n self.select_thread._file_descriptor_to_callback = {s1.fileno(): callback1, s2.fileno(): callback2}\n file_descriptors = self.select_thread._file_descriptors\n file_descriptor_to_callback = self.select_thread._file_descriptor_to_callback\n file_descriptors_copy = frozenset(self.select_thread._file_descriptors)\n file_descriptor_to_callback_copy = self.select_thread._file_descriptor_to_callback.copy()\n self.select_thread.remove_socket(s1)\n self.assertEqual(file_descriptors_copy, file_descriptors)\n self.assertEqual(file_descriptor_to_callback_copy, file_descriptor_to_callback)\n self.assertEqual(frozenset([s2.fileno()]), self.select_thread._file_descriptors)\n self.assertEqual({s2.fileno(): callback2}, self.select_thread._file_descriptor_to_callback)\n", "method_code": " def remove_socket(self, s):\n \"\"\"Remove a watched socket.\"\"\"\n with self._lock:\n self._file_descriptors = self._file_descriptors.difference([s.fileno()])\n new_file_descriptor_to_callback = self._file_descriptor_to_callback.copy()\n del new_file_descriptor_to_callback[s.fileno()]\n self._file_descriptor_to_callback = new_file_descriptor_to_callback\n ", "context": "class SelectThread(object):\n def remove_socket(self, s): ...\n def __init__(self): ...\n def start(self): ...\n def add_socket(self, s, callback): ...\n def _loop_forever(self): ...\n def _select(self): ...\n\n self._lock = threading.Lock()\n self._file_descriptors = frozenset()\n self._file_descriptor_to_callback = {}\n self._select_thread = threading.Thread(target=self._loop_forever, name='WSGI select')\n self._select_thread.daemon = True\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_remove_socket", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001841.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "_select", "tests": "import unittest\n\nclass Test_select(unittest.TestCase):\n @unittest.skipUnless(wsgi_server._HAS_POLL, 'requires select.poll')\n def test_select_with_poll(self):\n s = self._MockSocket()\n callback = self.mox.CreateMockAnything()\n poll = self.mox.CreateMockAnything()\n select.poll().AndReturn(poll)\n poll.register(s.fileno(), select.POLLIN)\n poll.poll(1000).AndReturn([(s.fileno(), select.POLLIN)])\n callback()\n self.mox.ReplayAll()\n self.select_thread.add_socket(s, callback)\n self.select_thread._select()\n self.mox.VerifyAll()\n\n def test_select_not_ready_no_poll(self):\n wsgi_server._HAS_POLL = False\n s = self._MockSocket()\n callback = self.mox.CreateMockAnything()\n select.select(frozenset([s.fileno()]), [], [], 1).AndReturn(([], [], []))\n self.mox.ReplayAll()\n self.select_thread.add_socket(s, callback)\n self.select_thread._select()\n self.mox.VerifyAll()\n\n @unittest.skipUnless(wsgi_server._HAS_POLL, 'requires select.poll')\n def test_select_not_ready_with_poll(self):\n s = self._MockSocket()\n callback = self.mox.CreateMockAnything()\n poll = self.mox.CreateMockAnything()\n select.poll().AndReturn(poll)\n poll.register(s.fileno(), select.POLLIN)\n poll.poll(1000).AndReturn([])\n self.mox.ReplayAll()\n self.select_thread.add_socket(s, callback)\n self.select_thread._select()\n self.mox.VerifyAll()\n", "method_code": " def _select(self):\n with self._lock:\n fds = self._file_descriptors\n fd_to_callback = self._file_descriptor_to_callback\n if fds:\n if _HAS_POLL:\n poll = select.poll()\n for fd in fds:\n poll.register(fd, select.POLLIN)\n ready_file_descriptors = [fd for fd, _ in poll.poll(_READINESS_TIMEOUT_SECONDS * _SECONDS_TO_MILLISECONDS)]\n else:\n ready_file_descriptors, _, _ = select.select(fds, [], [], _READINESS_TIMEOUT_SECONDS)\n for fd in ready_file_descriptors:\n fd_to_callback[fd]()\n else:\n time.sleep(_READINESS_TIMEOUT_SECONDS)\n ", "context": "class SelectThread(object):\n def _select(self): ...\n def __init__(self): ...\n def start(self): ...\n def add_socket(self, s, callback): ...\n def remove_socket(self, s): ...\n def _loop_forever(self): ...\n\n self._lock = threading.Lock()\n self._file_descriptors = frozenset()\n self._file_descriptor_to_callback = {}\n self._select_thread = threading.Thread(target=self._loop_forever, name='WSGI select')\n self._select_thread.daemon = True\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001842.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "quit", "tests": "import unittest\n\nclass Test_quit(unittest.TestCase):\n def test_quit(self):\n self.mox.StubOutWithMock(wsgi_server._SELECT_THREAD, 'remove_socket')\n self.server.socket = object()\n self.server.requests = self.mox.CreateMock(wsgi_server._SharedCherryPyThreadPool)\n wsgi_server._SELECT_THREAD.remove_socket(self.server.socket)\n self.server.requests.stop(timeout=1)\n self.mox.ReplayAll()\n self.server.quit()\n self.mox.VerifyAll()\n", "method_code": " def quit(self):\n \"\"\"Quits the _SingleAddressWsgiServer.\"\"\"\n _SELECT_THREAD.remove_socket(self.socket)\n self.requests.stop(timeout=1)\n ", "context": "class _SingleAddressWsgiServer(wsgiserver.CherryPyWSGIServer):\n def quit(self): ...\n def __init__(self, host, app): ...\n def start(self): ...\n def port(self): ...\n def set_app(self, app): ...\n def set_error(self, error): ...\n def __call__(self, environ, start_response): ...\n\n self._lock = threading.Lock()\n self._app = app\n self._error = None\n self.requests = _SharedCherryPyThreadPool()\n self.software = http_runtime_constants.SERVER_SOFTWARE\n self.request_queue_size = 100\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_quit", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001843.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", "focal_class": null, "focal_method": "start", "tests": "import unittest\n\nclass Test_start(unittest.TestCase):\n def test_start(self):\n self.mox.StubOutWithMock(wsgiserver.ThreadPool, 'start')\n self.mox.StubOutWithMock(wsgi_server._SELECT_THREAD, 'add_socket')\n wsgi_server._SELECT_THREAD.add_socket(mox.IsA(socket.socket), self.server.tick)\n self.mox.ReplayAll()\n self.server.start()\n self.mox.VerifyAll()\n", "method_code": " def start(self):\n self._select_thread.start()\n ", "context": "class SelectThread(object):\n def start(self): ...\n def __init__(self): ...\n def add_socket(self, s, callback): ...\n def remove_socket(self, s): ...\n def _loop_forever(self): ...\n def _select(self): ...\n\n self._lock = threading.Lock()\n self._file_descriptors = frozenset()\n self._file_descriptor_to_callback = {}\n self._select_thread = threading.Thread(target=self._loop_forever, name='WSGI select')\n self._select_thread.daemon = True\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_start", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001844.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/admin_request_handler.py", "focal_class": null, "focal_method": "init_xsrf", "tests": "import unittest\n\nclass Test_init_xsrf(unittest.TestCase):\n def test_init_xsrf(self):\n xsrf_path = os.path.join(tempfile.mkdtemp(), 'xsrf')\n admin_request_handler.AdminRequestHandler.init_xsrf(xsrf_path)\n xsrf_token = admin_request_handler.AdminRequestHandler.xsrf_token\n self.assertEqual(10, len(xsrf_token))\n admin_request_handler.AdminRequestHandler.init_xsrf(xsrf_path)\n self.assertEqual(xsrf_token, admin_request_handler.AdminRequestHandler.xsrf_token)\n", "method_code": " def init_xsrf(cls, xsrf_path):\n \"\"\"Load the XSRF token from the given path.\"\"\"\n if os.path.exists(xsrf_path):\n with open(xsrf_path, 'r') as token_file:\n cls.xsrf_token = token_file.read().strip()\n else:\n cls.xsrf_token = ''.join((random.choice(string.ascii_letters) for _ in range(10)))\n with open(xsrf_path, 'w') as token_file:\n token_file.write(cls.xsrf_token)\n ", "context": "class AdminRequestHandler(webapp2.RequestHandler):\n @classmethod\n def init_xsrf(cls, xsrf_path): ...\n def dispatch(self): ...\n def render(self, template, context): ...\n def _construct_url(self, remove=None, add=None): ...\n def dispatcher(self): ...\n def configuration(self): ...\n\n _SDK_VERSION = _get_sdk_version()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_init_xsrf", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001845.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/admin_request_handler.py", "focal_class": "google.appengine.tools.devappserver2.admin.admin_request_handler.AdminRequestHandler", "focal_method": "_construct_url", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_admin_request_handler_AdminRequestHandler_construct_url(unittest.TestCase):\n def test_construct_url_no_args(self):\n request = webapp2.Request.blank('/foo', POST={'arg1': 'value1', 'arg2': 'value2'})\n response = webapp2.Response()\n handler = admin_request_handler.AdminRequestHandler(request, response)\n url = handler._construct_url()\n parsed_url = urlparse.urlparse(url)\n self.assertEqual('/foo', parsed_url.path)\n self.assertEqual({'arg1': ['value1'], 'arg2': ['value2']}, urlparse.parse_qs(parsed_url.query))\n\n def test_construct_url_remove(self):\n request = webapp2.Request.blank('/foo', POST={'arg1': 'value1', 'arg2': 'value2'})\n response = webapp2.Response()\n handler = admin_request_handler.AdminRequestHandler(request, response)\n url = handler._construct_url(remove=['arg1'])\n parsed_url = urlparse.urlparse(url)\n self.assertEqual('/foo', parsed_url.path)\n self.assertEqual({'arg2': ['value2']}, urlparse.parse_qs(parsed_url.query))\n\n def test_construct_url_add(self):\n request = webapp2.Request.blank('/foo', POST={'arg1': 'value1', 'arg2': 'value2'})\n response = webapp2.Response()\n handler = admin_request_handler.AdminRequestHandler(request, response)\n url = handler._construct_url(add={'arg2': 'new2', 'arg3': 'new3'})\n parsed_url = urlparse.urlparse(url)\n self.assertEqual('/foo', parsed_url.path)\n self.assertEqual({'arg1': ['value1'], 'arg2': ['new2'], 'arg3': ['new3']}, urlparse.parse_qs(parsed_url.query))\n", "method_code": " def _construct_url(self, remove=None, add=None):\n \"\"\"Returns a URL referencing the current resource with the same params.\n \n For example, if the request URL is\n \"http://foo/bar?animal=cat&color=redirect\" then\n _construct_url(['animal'], {'vehicle': 'car'}) will return\n \"http://foo/bar?color=redirect&vehicle=car\"\n \n Args:\n remove: A sequence of query parameters to remove from the query string.\n add: A mapping of query parameters to add to the query string.\n \n Returns:\n A new query string suitable for use in \"GET\" requests.\n \"\"\"\n remove = remove or []\n add = add or {}\n params = dict(self.request.params)\n for arg in remove:\n if arg in params:\n del params[arg]\n params.update(add)\n return str('%s?%s' % (self.request.path, urllib.urlencode(sorted(params.iteritems()))))\n ", "context": "class AdminRequestHandler(webapp2.RequestHandler):\n def _construct_url(self, remove=None, add=None): ...\n def init_xsrf(cls, xsrf_path): ...\n def dispatch(self): ...\n def render(self, template, context): ...\n def dispatcher(self): ...\n def configuration(self): ...\n\n _SDK_VERSION = _get_sdk_version()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_construct_url_no_args", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001846.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/blobstore_viewer.py", "focal_class": null, "focal_method": "_get_blobs", "tests": "import unittest\n\nclass Test_get_blobs(unittest.TestCase):\n def test_get_blobs(self):\n query = db.Query(model_class=blobstore.BlobInfo, namespace='')\n query.order('-creation').AndReturn(query)\n query.fetch(10, offset=40).AndReturn(['some blob'])\n self.mox.ReplayAll()\n self.assertEqual(['some blob'], blobstore_viewer._get_blobs(start=40, limit=10))\n self.mox.VerifyAll()\n", "method_code": "def _get_blobs(start, limit):\n \"\"\"Return a list of BlobInfo objects ordered by most recently created.\n\n Args:\n start: The offset of the first blobstore.BlobInfo instances to return,\n ordered by descending creation time.\n limit: The maximum number of blobstore.BlobInfo blobstore to return.\n\n Returns:\n A list of blobstore.BlobInfo blobstore ordered by most recently created.\n \"\"\"\n q = blobstore.BlobInfo.all().order('-creation')\n return q.fetch(limit, offset=start)", "context": "def _get_blobs(start, limit): ...\ndef _get_blobs(start, limit): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_blobs", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001847.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/blobstore_viewer.py", "focal_class": "google.appengine.tools.devappserver2.admin.blobstore_viewer.BlobstoreRequestHandler", "focal_method": "post", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_blobstore_viewer_BlobstoreRequestHandler_post(unittest.TestCase):\n def test_post(self):\n request = webapp2.Request.blank('/blobstore', method='POST', POST=multidict.MultiDict([('blob_key', 'a'), ('blob_key', 'b')]))\n response = webapp2.Response()\n handler = blobstore_viewer.BlobstoreRequestHandler(request, response)\n self.mox.StubOutWithMock(blobstore, 'delete')\n blobstore.delete(['a', 'b'])\n self.mox.ReplayAll()\n handler.post()\n self.mox.VerifyAll()\n self.assertEqual(302, response.status_int)\n self.assertEqual('http://localhost/blobstore', response.headers.get('Location'))\n", "method_code": " def post(self):\n \"\"\"Deletes blobs identified in 'blob_key' form variables.\n \n Multiple keys can be specified e.g. '...&blob_key=key1&blob_key=key2'.\n \n Redirects the client back to the value specified in the 'return_to' form\n variable.\n \"\"\"\n redirect_url = str(self.request.get('return_to', '/blobstore'))\n keys = self.request.get_all('blob_key')\n blobstore.delete(keys)\n self.redirect(redirect_url)\n ", "context": "class BlobstoreRequestHandler(admin_request_handler.AdminRequestHandler):\n def post(self): ...\n def get(self): ...\n\n BLOBS_PER_PAGE = 20\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_post", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001848.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/dispatcher.py", "focal_class": null, "focal_method": "quit", "tests": "import unittest\n\nclass Test_quit(unittest.TestCase):\n def test_quit(self):\n console.ConsoleRequestHandler._modulename_to_shell_module = {'default': self.interactive_command_module}\n self.interactive_command_module.quit()\n self.mox.ReplayAll()\n console.ConsoleRequestHandler.quit()\n self.mox.VerifyAll()\n", "method_code": " def quit(self):\n \"\"\"Quits all modules.\"\"\"\n self._executor.quit()\n self._quit_event.set()\n if self._dispatch_server:\n self._dispatch_server.quit()\n for _module in self._module_name_to_module.values():\n _module.quit()\n ", "context": "class Dispatcher(request_info.Dispatcher):\n def quit(self): ...\n def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_config, python_config, java_config, custom_config, cloud_sql_config, vm_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files, module_to_threadsafe_override, external_port): ...\n def start(self, api_host, api_port, request_data): ...\n def dispatch_port(self): ...\n def host(self): ...\n def dispatch_address(self): ...\n def _check_for_updates(self): ...\n def _loop_checking_for_updates(self): ...\n def _create_module(self, module_configuration, port): ...\n def modules(self): ...\n def get_hostname(self, module_name, version, instance_id=None): ...\n def get_module_names(self): ...\n def get_module_by_name(self, _module): ...\n def get_versions(self, _module): ...\n def get_default_version(self, _module): ...\n def add_event(self, runnable, eta, service=None, event_id=None): ...\n def update_event(self, eta, service, event_id): ...\n def _get_module(self, module_name, version): ...\n def _get_module_with_soft_routing(self, module_name, version): ...\n def set_num_instances(self, module_name, version, num_instances): ...\n def get_num_instances(self, module_name, version): ...\n def start_version(self, module_name, version): ...\n def stop_version(self, module_name, version): ...\n def send_background_request(self, module_name, version, inst, background_request_id): ...\n def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None): ...\n def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False): ...\n def _resolve_target(self, hostname, path): ...\n def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False): ...\n def __call__(self, environ, start_response): ...\n def _should_use_dispatch_config(self, path): ...\n def _module_for_request(self, path): ...\n\n self._configuration = configuration\n self._php_config = php_config\n self._python_config = python_config\n self._java_config = java_config\n self._custom_config = custom_config\n self._cloud_sql_config = cloud_sql_config\n self._vm_config = vm_config\n self._request_data = None\n self._api_host = None\n self._api_port = None\n self._running_modules = []\n self._module_configurations = {}\n self._host = host\n self._port = port\n self._auth_domain = auth_domain\n self._runtime_stderr_loglevel = runtime_stderr_loglevel\n self._module_name_to_module = {}\n self._dispatch_server = None\n self._quit_event = threading.Event()\n self._update_checking_thread = threading.Thread(target=self._loop_checking_for_updates, name='Dispatcher Update Checking')\n self._module_to_max_instances = module_to_max_instances or {}\n self._use_mtime_file_watcher = use_mtime_file_watcher\n self._automatic_restart = automatic_restart\n self._allow_skipped_files = allow_skipped_files\n self._module_to_threadsafe_override = module_to_threadsafe_override\n self._executor = scheduled_executor.ScheduledExecutor(_THREAD_POOL)\n self._port_registry = PortRegistry()\n self._external_port = external_port\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_quit", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001849.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/cron_handler.py", "focal_class": "google.appengine.tools.devappserver2.admin.cron_handler.CronHandler", "focal_method": "post", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_cron_handler_CronHandler_post(unittest.TestCase):\n def test_post(self):\n self.mox.StubOutWithMock(cron_handler.CronHandler, 'dispatcher')\n request = webapp2.Request.blank('/cron', POST={'url': '/url'})\n response = webapp2.Response()\n handler = cron_handler.CronHandler(request, response)\n handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher)\n handler.dispatcher.add_request(method='GET', relative_url='/url', headers=[('X-AppEngine-Cron', 'true')], body='', source_ip='0.1.0.1').AndReturn(dispatcher.ResponseTuple('500 Internal Server Error', [], ''))\n self.mox.ReplayAll()\n handler.post()\n self.mox.VerifyAll()\n self.assertEqual(500, response.status_int)\n", "method_code": " def post(self):\n self.response.status = self.dispatcher.add_request(method='GET', relative_url=self.request.get('url'), headers=[('X-AppEngine-Cron', 'true')], body='', source_ip=REMOTE_IP).status\n ", "context": "class CronHandler(admin_request_handler.AdminRequestHandler):\n def post(self): ...\n def get(self): ...\n def _get_cron_jobs(self): ...\n def _parse_cron_yaml(self): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_post", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001850.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/cron_handler.py", "focal_class": "google.appengine.tools.devappserver2.admin.cron_handler.CronHandler", "focal_method": "_get_cron_jobs", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_cron_handler_CronHandler_get_cron_jobs(unittest.TestCase):\n @unittest.skipIf(cron_handler.pytz is None, 'requires pytz')\n def test_get_cron_jobs_with_pytz(self):\n handler = cron_handler.CronHandler(None, None)\n self.mox.StubOutWithMock(handler, '_parse_cron_yaml')\n handler._parse_cron_yaml().AndReturn(CRON_INFO_EXTERNAL)\n self.mox.ReplayAll()\n cron_jobs = handler._get_cron_jobs()\n self.mox.VerifyAll()\n self.assertEqual(2, len(cron_jobs))\n next_runs = [cron_jobs[0].pop('times'), cron_jobs[1].pop('times')]\n self.assertEqual(CRON_INFO_EXTERNAL.cron[0].ToDict(), cron_jobs[0])\n self.assertEqual(CRON_INFO_EXTERNAL.cron[1].ToDict(), cron_jobs[1])\n for next_run in next_runs:\n self.assertEqual(3, len(next_run))\n for run in next_run:\n datetime.datetime.strptime(run['runtime'], '%Y-%m-%d %H:%M:%SZ')\n\n def test_get_cron_jobs_without_pytz(self):\n cron_handler.pytz = None\n handler = cron_handler.CronHandler(None, None)\n self.mox.StubOutWithMock(handler, '_parse_cron_yaml')\n handler._parse_cron_yaml().AndReturn(CRON_INFO_EXTERNAL)\n self.mox.ReplayAll()\n cron_jobs = handler._get_cron_jobs()\n self.mox.VerifyAll()\n self.assertEqual(2, len(cron_jobs))\n self.assertEqual(CRON_INFO_EXTERNAL.cron[0].ToDict(), cron_jobs[0])\n next_run = cron_jobs[1].pop('times')\n self.assertEqual(CRON_INFO_EXTERNAL.cron[1].ToDict(), cron_jobs[1])\n self.assertEqual(3, len(next_run))\n for run in next_run:\n datetime.datetime.strptime(run['runtime'], '%Y-%m-%d %H:%M:%SZ')\n\n def test_get_cron_jobs_no_cron_yaml(self):\n cron_handler.pytz = None\n handler = cron_handler.CronHandler(None, None)\n self.mox.StubOutWithMock(handler, '_parse_cron_yaml')\n handler._parse_cron_yaml().AndReturn(None)\n self.mox.ReplayAll()\n self.assertEqual([], handler._get_cron_jobs())\n self.mox.VerifyAll()\n", "method_code": " def _get_cron_jobs(self):\n cron_info = self._parse_cron_yaml()\n if not cron_info or not cron_info.cron:\n return []\n jobs = []\n for entry in cron_info.cron:\n job = entry.ToDict()\n if not entry.timezone or pytz:\n now = datetime.datetime.utcnow()\n schedule = groctimespecification.GrocTimeSpecification(entry.schedule, entry.timezone)\n matches = schedule.GetMatches(now, 3)\n job['times'] = []\n for match in matches:\n job['times'].append({'runtime': match.strftime('%Y-%m-%d %H:%M:%SZ'), 'difference': str(match - now)})\n jobs.append(job)\n return jobs\n ", "context": "class CronHandler(admin_request_handler.AdminRequestHandler):\n def _get_cron_jobs(self): ...\n def get(self): ...\n def _parse_cron_yaml(self): ...\n def post(self): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001851.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/datastore_viewer.py", "focal_class": null, "focal_method": "_property_name_to_values", "tests": "import unittest\n\nclass Test_property_name_to_values(unittest.TestCase):\n def test_property_name_to_values(self):\n self.assertEqual({'cat': [5], 'dog': mox.SameElementsAs([10, 15]), 'mouse': ['happy']}, datastore_viewer._property_name_to_values([self.entity1, self.entity2]))\n", "method_code": "def _property_name_to_values(entities):\n \"\"\"Returns a a mapping of entity property names to a list of their values.\n\n For example:\n _property_name_to_values([{'cat': 5, 'dog': 10},\n {'dog': 15, 'mouse': 'happy'}])\n => {'cat': [5], 'dog': [10, 15], 'mouse': ['happy']}\n\n Args:\n entities: A sequence of mappings (i.e. datastore.Entity) that represent\n datastore properties and their values.\n\n Returns:\n A dict whose keys are the union of the keys of the given entities and\n whose values are the list of values for those keys.\n \"\"\"\n property_name_to_values = {}\n for entity in entities:\n for property_name, value in entity.iteritems():\n property_name_to_values.setdefault(property_name, []).append(value)\n return property_name_to_values", "context": "def _property_name_to_values(entities): ...\ndef _format_datastore_key(key): ...\ndef _property_name_to_values(entities): ...\ndef _property_name_to_value(entities): ...\ndef _get_entities(kind, namespace, order, start, count): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_property_name_to_values", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001852.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/datastore_viewer.py", "focal_class": null, "focal_method": "_property_name_to_value", "tests": "import unittest\n\nclass Test_property_name_to_value(unittest.TestCase):\n def test_property_name_to_value(self):\n self.assertEqual({'cat': 5, 'dog': mox.Func(lambda v: v in [10, 15]), 'mouse': 'happy'}, datastore_viewer._property_name_to_value([self.entity1, self.entity2]))\n", "method_code": "def _property_name_to_value(entities):\n \"\"\"Returns a a mapping of entity property names to a sample value.\n\n For example:\n _property_name_to_value([{'cat': 5, 'dog': 10},\n {'dog': 15, 'mouse': 'happy'}])\n => {'cat': 5, 'dog': 10 or 15, 'mouse': 'happy'}\n\n Args:\n entities: A sequence of mappings (i.e. datastore.Entity) that represent\n datastore properties and their values.\n\n Returns:\n A dict whose keys are the union of the keys of the given entities and\n whose values are arbitrarily chosen from the key values of the given\n entities.\n \"\"\"\n return {key: values[0] for key, values in _property_name_to_values(entities).iteritems()}", "context": "def _property_name_to_value(entities): ...\ndef _format_datastore_key(key): ...\ndef _property_name_to_values(entities): ...\ndef _property_name_to_value(entities): ...\ndef _get_entities(kind, namespace, order, start, count): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_property_name_to_value", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001853.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/mail_request_handler.py", "focal_class": null, "focal_method": "_generate_email", "tests": "import unittest\n\nclass Test_generate_email(unittest.TestCase):\n def test_generate_email(self):\n message = mail_request_handler.MailRequestHandler._generate_email('to', 'from', 'cc', 'subject', 'body')\n self.assertEqual('from', message['From'])\n self.assertEqual('to', message['To'])\n self.assertEqual('cc', message['Cc'])\n self.assertEqual('subject', message['Subject'])\n text, html = message.get_payload()\n self.assertEqual('text/plain', text.get_content_type())\n self.assertEqual('utf-8', text.get_content_charset())\n content = text.get_payload()\n if text['content-transfer-encoding'] != '7bit':\n content = content.decode(text['content-transfer-encoding'])\n self.assertEqual('body', content)\n self.assertEqual('text/html', html.get_content_type())\n self.assertEqual('utf-8', html.get_content_charset())\n content = html.get_payload()\n if html['content-transfer-encoding'] != '7bit':\n content = content.decode(html['content-transfer-encoding'])\n self.assertEqual('body', content)\n", "method_code": " def _generate_email(to, from_, cc, subject, body):\n message = email.mime.multipart.MIMEMultipart('alternative')\n message['To'] = to\n message['From'] = from_\n message['Cc'] = cc\n message['Subject'] = subject\n message['Date'] = email.utils.formatdate()\n plain_text = email.mime.Text.MIMEText(body, 'plain', 'utf-8')\n html_text = email.mime.Text.MIMEText(body, 'html', 'utf-8')\n message.attach(plain_text)\n message.attach(html_text)\n return message\n ", "context": "class MailRequestHandler(admin_request_handler.AdminRequestHandler):\n @staticmethod\n def _generate_email(to, from_, cc, subject, body): ...\n def get(self): ...\n def post(self): ...\n def _send_email(self, to, from_, cc, subject, body): ...\n def _send(self, relative_url, mail_message): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_generate_email", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001854.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/mail_request_handler.py", "focal_class": "google.appengine.tools.devappserver2.admin.mail_request_handler.MailRequestHandler", "focal_method": "_send_email", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_mail_request_handler_MailRequestHandler_send_email(unittest.TestCase):\n def test_send_email(self):\n response = webapp2.Response()\n handler = mail_request_handler.MailRequestHandler(None, response)\n message = object()\n self.mox.StubOutWithMock(handler, '_send')\n self.mox.StubOutWithMock(handler, '_generate_email')\n handler._generate_email('to', 'from', 'cc', 'subject', 'body').AndReturn(message)\n handler._send('/_ah/mail/to', message).AndReturn(dispatcher.ResponseTuple('500 Internal Server Error', [], 'Response'))\n self.mox.ReplayAll()\n handler._send_email('to', 'from', 'cc', 'subject', 'body')\n self.mox.VerifyAll()\n self.assertEqual(500, response.status_int)\n", "method_code": " def _send_email(self, to, from_, cc, subject, body):\n mail_message = self._generate_email(to, from_, cc, subject, body)\n response = self._send('/_ah/mail/%s' % to, mail_message)\n self.response.status = response.status\n ", "context": "class MailRequestHandler(admin_request_handler.AdminRequestHandler):\n def _send_email(self, to, from_, cc, subject, body): ...\n def get(self): ...\n def post(self): ...\n def _generate_email(to, from_, cc, subject, body): ...\n def _send(self, relative_url, mail_message): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_send_email", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001855.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/mail_request_handler.py", "focal_class": "google.appengine.tools.devappserver2.admin.mail_request_handler.MailRequestHandler", "focal_method": "_send", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_mail_request_handler_MailRequestHandler_send(unittest.TestCase):\n def test_send(self):\n self.mox.StubOutWithMock(mail_request_handler.MailRequestHandler, 'dispatcher')\n handler = mail_request_handler.MailRequestHandler(None, None)\n handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher)\n handler.dispatcher.add_request(method='POST', relative_url='URL', headers=[('Content-Type', 'message/rfc822')], body='mail message', source_ip='0.1.0.20')\n message = self.mox.CreateMock(email.message.Message)\n message.as_string().AndReturn('mail message')\n self.mox.ReplayAll()\n handler._send('URL', message)\n self.mox.VerifyAll()\n", "method_code": " def _send(self, relative_url, mail_message):\n return self.dispatcher.add_request(method='POST', relative_url=relative_url, headers=[('Content-Type', 'message/rfc822')], body=mail_message.as_string(), source_ip=REMOTE_IP)\n ", "context": "class MailRequestHandler(admin_request_handler.AdminRequestHandler):\n def _send(self, relative_url, mail_message): ...\n def get(self): ...\n def post(self): ...\n def _generate_email(to, from_, cc, subject, body): ...\n def _send_email(self, to, from_, cc, subject, body): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_send", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001856.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/mail_request_handler.py", "focal_class": "google.appengine.tools.devappserver2.admin.mail_request_handler.MailRequestHandler", "focal_method": "post", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_mail_request_handler_MailRequestHandler_post(unittest.TestCase):\n def test_post(self):\n request = webapp2.Request.blank('/mail', POST={'to': 'to', 'from': 'from', 'cc': 'cc', 'subject': 'subject', 'body': 'body'})\n response = webapp2.Response()\n handler = mail_request_handler.MailRequestHandler(request, response)\n self.mox.StubOutWithMock(handler, '_send_email')\n handler._send_email('to', 'from', 'cc', 'subject', 'body')\n self.mox.ReplayAll()\n handler.post()\n self.mox.VerifyAll()\n", "method_code": " def post(self):\n to = self.request.get('to')\n from_ = self.request.get('from')\n cc = self.request.get('cc')\n subject = self.request.get('subject')\n body = self.request.get('body')\n self._send_email(to, from_, cc, subject, body)\n ", "context": "class MailRequestHandler(admin_request_handler.AdminRequestHandler):\n def post(self): ...\n def get(self): ...\n def _generate_email(to, from_, cc, subject, body): ...\n def _send_email(self, to, from_, cc, subject, body): ...\n def _send(self, relative_url, mail_message): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_post", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001857.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/taskqueue_queues_handler.py", "focal_class": "google.appengine.tools.devappserver2.admin.taskqueue_queues_handler.TaskQueueQueuesHandler", "focal_method": "get", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_taskqueue_queues_handler_TaskQueueQueuesHandler_get(unittest.TestCase):\n def test_get(self):\n queue1 = taskqueue_utils.QueueInfo(name='queue1', mode=taskqueue_service_pb.TaskQueueMode.PUSH, rate='10/s', bucket_size=20, tasks_in_queue=10, oldest_eta_usec=-1)\n queue2 = taskqueue_utils.QueueInfo(name='queue1', mode=taskqueue_service_pb.TaskQueueMode.PUSH, rate='20/s', bucket_size=20, tasks_in_queue=10, oldest_eta_usec=-1)\n queue3 = taskqueue_utils.QueueInfo(name='queue1', mode=taskqueue_service_pb.TaskQueueMode.PULL, rate='20/s', bucket_size=20, tasks_in_queue=10, oldest_eta_usec=-1)\n taskqueue_utils.QueueInfo.get().AndReturn([queue1, queue2, queue3])\n request = webapp2.Request.blank('/taskqueue')\n response = webapp2.Response()\n handler = taskqueue_queues_handler.TaskQueueQueuesHandler(request, response)\n handler.render('taskqueue_queues.html', {'push_queues': [queue1, queue2], 'pull_queues': [queue3]})\n self.mox.ReplayAll()\n handler.get()\n self.mox.VerifyAll()\n", "method_code": " def get(self):\n push_queues = []\n pull_queues = []\n for queue_info in taskqueue_utils.QueueInfo.get():\n if queue_info.mode == taskqueue_service_pb.TaskQueueMode.PUSH:\n push_queues.append(queue_info)\n elif queue_info.mode == taskqueue_service_pb.TaskQueueMode.PULL:\n pull_queues.append(queue_info)\n else:\n assert 0, 'unexpected queue type: %r' % queue_info.mode\n self.response.write(self.render('taskqueue_queues.html', {'push_queues': push_queues, 'pull_queues': pull_queues}))\n ", "context": "class TaskQueueQueuesHandler(admin_request_handler.AdminRequestHandler):\n def get(self): ...\n def _purge_queue(self, queue_name): ...\n def post(self): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001858.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/taskqueue_utils.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_get(self):\n fetch_queue_request = taskqueue_service_pb.TaskQueueFetchQueuesRequest()\n fetch_queue_request.set_max_rows(1000)\n fetch_queue_response = taskqueue_service_pb.TaskQueueFetchQueuesResponse()\n queue1 = fetch_queue_response.add_queue()\n queue1.set_queue_name('queue1')\n queue1.set_mode(taskqueue_service_pb.TaskQueueMode.PUSH)\n queue1.set_user_specified_rate('20/s')\n queue1.set_bucket_capacity(10)\n queue2 = fetch_queue_response.add_queue()\n queue2.set_queue_name('queue2')\n queue2.set_mode(taskqueue_service_pb.TaskQueueMode.PULL)\n queue2.set_user_specified_rate('20/s')\n queue2.set_bucket_capacity(10)\n apiproxy_stub_map.MakeSyncCall('taskqueue', 'FetchQueues', fetch_queue_request, mox.IgnoreArg()).WithSideEffects(lambda _, _1, _2, response: response.CopyFrom(fetch_queue_response))\n queue_stats_request = taskqueue_service_pb.TaskQueueFetchQueueStatsRequest()\n queue_stats_request.add_queue_name('queue1')\n queue_stats_request.add_queue_name('queue2')\n queue_stats_response = taskqueue_service_pb.TaskQueueFetchQueueStatsResponse()\n queue_stats1 = queue_stats_response.add_queuestats()\n queue_stats1.set_num_tasks(20)\n queue_stats1.set_oldest_eta_usec(-1)\n queue_stats2 = queue_stats_response.add_queuestats()\n queue_stats2.set_num_tasks(50)\n queue_stats2.set_oldest_eta_usec(1234567890)\n apiproxy_stub_map.MakeSyncCall('taskqueue', 'FetchQueueStats', queue_stats_request, mox.IgnoreArg()).WithSideEffects(lambda _, _1, _2, response: response.CopyFrom(queue_stats_response))\n self.mox.ReplayAll()\n queues = list(taskqueue_utils.QueueInfo.get())\n self.mox.VerifyAll()\n self.assertEqual('queue1', queues[0].name)\n self.assertEqual('queue2', queues[1].name)\n", "method_code": " def get(cls, queue_names=frozenset()):\n \"\"\"Returns a 2-tuple: (list of push _QueueInfo, list of pull _QueueInfo).\"\"\"\n fetch_queue_request = taskqueue_service_pb.TaskQueueFetchQueuesRequest()\n fetch_queue_request.set_max_rows(1000)\n fetch_queue_response = taskqueue_service_pb.TaskQueueFetchQueuesResponse()\n apiproxy_stub_map.MakeSyncCall('taskqueue', 'FetchQueues', fetch_queue_request, fetch_queue_response)\n queue_stats_request = taskqueue_service_pb.TaskQueueFetchQueueStatsRequest()\n for queue in fetch_queue_response.queue_list():\n queue_stats_request.add_queue_name(queue.queue_name())\n queue_stats_response = taskqueue_service_pb.TaskQueueFetchQueueStatsResponse()\n apiproxy_stub_map.MakeSyncCall('taskqueue', 'FetchQueueStats', queue_stats_request, queue_stats_response)\n for queue, queue_stats in zip(fetch_queue_response.queue_list(), queue_stats_response.queuestats_list()):\n if queue_names and queue.queue_name() not in queue_names:\n continue\n yield cls._from_queue_and_stats(queue, queue_stats)\n ", "context": "class QueueInfo(object):\n @classmethod\n def get(cls, queue_names=frozenset()): ...\n def __init__(self, name, mode, rate, bucket_size, tasks_in_queue, oldest_eta_usec): ...\n def human_readable_oldest_task_eta(self): ...\n def human_readable_oldest_task_eta_delta(self): ...\n def _from_queue_and_stats(cls, queue, queue_stats): ...\n\n self.name = name\n self.mode = mode\n self.rate = rate\n self.bucket_size = bucket_size\n self.tasks_in_queue = tasks_in_queue\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001859.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/admin/xmpp_request_handler.py", "focal_class": "google.appengine.tools.devappserver2.admin.xmpp_request_handler.XmppRequestHandler", "focal_method": "_send", "tests": "import unittest\n\nclass Test_google_appengine_tools_devappserver2_admin_xmpp_request_handler_XmppRequestHandler_send(unittest.TestCase):\n def test_send(self):\n self.mox.StubOutWithMock(xmpp_request_handler.XmppRequestHandler, 'dispatcher')\n handler = xmpp_request_handler.XmppRequestHandler()\n handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher)\n handler.dispatcher.add_request(method='POST', relative_url='url', headers=[('Content-Type', mox.Regex('multipart/form-data; boundary=\".*?\"'))], body=mox.IsA(str), source_ip='0.1.0.10', fake_login=True)\n data = xmpp_request_handler._FormData()\n self.mox.ReplayAll()\n handler._send('url', data)\n self.mox.VerifyAll()\n", "method_code": " def _send(self, relative_url, form_data):\n boundary, content = form_data.get_boundary_and_content()\n return self.dispatcher.add_request(method='POST', relative_url=relative_url, headers=[('Content-Type', 'multipart/form-data; boundary=\"%s\"' % boundary)], body=content, source_ip=REMOTE_IP, fake_login=True)\n ", "context": "class XmppRequestHandler(admin_request_handler.AdminRequestHandler):\n def _send(self, relative_url, form_data): ...\n def get(self): ...\n def post(self): ...\n def _generate_chat(self, to, from_, body): ...\n def _send_chat(self, to, from_): ...\n def _generate_presence_available(self, to, from_, show=None): ...\n def _send_presence_available(self, to, from_): ...\n def _generate_presence_type(self, to, from_, presence_type): ...\n def _send_presence_unavailable(self, to, from_): ...\n def _send_subscription(self, to, from_): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_send", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001860.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/api_request.py", "focal_class": null, "focal_method": "is_rpc", "tests": "import unittest\n\nclass Test_is_rpc(unittest.TestCase):\n def test_is_rpc(self):\n request = test_utils.build_request('/_ah/api/rpc')\n self.assertEqual('rpc', request.path)\n self.assertEqual(None, request.query)\n self.assertTrue(request.is_rpc())\n\n def test_is_not_rpc(self):\n request = test_utils.build_request('/_ah/api/guestbook/v1/greetings/7')\n self.assertEqual('guestbook/v1/greetings/7', request.path)\n self.assertEqual(None, request.query)\n self.assertFalse(request.is_rpc())\n", "method_code": " def is_rpc(self):\n return self.path == 'rpc'\n ", "context": "class ApiRequest(object):\n def is_rpc(self): ...\n def __init__(self, environ): ...\n def _reconstruct_relative_url(self, environ): ...\n def copy(self): ...\n def is_batch(self): ...\n\n self.headers = util.get_headers_from_environ(environ)\n self.http_method = environ['REQUEST_METHOD']\n self.server = environ['SERVER_NAME']\n self.port = environ['SERVER_PORT']\n self.path = environ['PATH_INFO']\n self.query = environ.get('QUERY_STRING')\n self.body = environ['wsgi.input'].read()\n self.source_ip = environ.get('REMOTE_ADDR')\n self.relative_url = self._reconstruct_relative_url(environ)\n self.path = self.path[len(self._API_PREFIX):]\n self.body_json = json.loads(self.body) if self.body else {}\n self.request_id = None\n\n _API_PREFIX = '/_ah/api/'\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_is_rpc", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001861.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/api_request.py", "focal_class": null, "focal_method": "is_batch", "tests": "import unittest\n\nclass Test_is_batch(unittest.TestCase):\n def test_batch(self):\n request = test_utils.build_request('/_ah/api/rpc', '[{\"method\": \"foo\", \"apiVersion\": \"v1\"}]')\n self.assertTrue(request.is_batch())\n self.assertFalse(isinstance(request.body_json, list))\n", "method_code": " def is_batch(self):\n return self._is_batch\n ", "context": "class ApiRequest(object):\n def is_batch(self): ...\n def __init__(self, environ): ...\n def _reconstruct_relative_url(self, environ): ...\n def copy(self): ...\n def is_rpc(self): ...\n\n self.headers = util.get_headers_from_environ(environ)\n self.http_method = environ['REQUEST_METHOD']\n self.server = environ['SERVER_NAME']\n self.port = environ['SERVER_PORT']\n self.path = environ['PATH_INFO']\n self.query = environ.get('QUERY_STRING')\n self.body = environ['wsgi.input'].read()\n self.source_ip = environ.get('REMOTE_ADDR')\n self.relative_url = self._reconstruct_relative_url(environ)\n self.path = self.path[len(self._API_PREFIX):]\n self.body_json = json.loads(self.body) if self.body else {}\n self.request_id = None\n\n _API_PREFIX = '/_ah/api/'\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_batch", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001862.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/api_request.py", "focal_class": null, "focal_method": "copy", "tests": "import unittest\n\nclass Test_copy(unittest.TestCase):\n def test_copy(self):\n request = test_utils.build_request('/_ah/api/foo?bar=baz', '{\"test\": \"body\"}')\n copied = request.copy()\n self.assertEqual(request.headers.items(), copied.headers.items())\n self.assertEqual(request.body, copied.body)\n self.assertEqual(request.body_json, copied.body_json)\n self.assertEqual(request.path, copied.path)\n copied.headers['Content-Type'] = 'text/plain'\n copied.body = 'Got a whole new body!'\n copied.body_json = {'new': 'body'}\n copied.path = 'And/a/new/path/'\n self.assertNotEqual(request.headers.items(), copied.headers.items())\n self.assertNotEqual(request.body, copied.body)\n self.assertNotEqual(request.body_json, copied.body_json)\n self.assertNotEqual(request.path, copied.path)\n", "method_code": " def copy(self):\n return copy.deepcopy(self)\n ", "context": "class ApiRequest(object):\n def copy(self): ...\n def __init__(self, environ): ...\n def _reconstruct_relative_url(self, environ): ...\n def is_rpc(self): ...\n def is_batch(self): ...\n\n self.headers = util.get_headers_from_environ(environ)\n self.http_method = environ['REQUEST_METHOD']\n self.server = environ['SERVER_NAME']\n self.port = environ['SERVER_PORT']\n self.path = environ['PATH_INFO']\n self.query = environ.get('QUERY_STRING')\n self.body = environ['wsgi.input'].read()\n self.source_ip = environ.get('REMOTE_ADDR')\n self.relative_url = self._reconstruct_relative_url(environ)\n self.path = self.path[len(self._API_PREFIX):]\n self.body_json = json.loads(self.body) if self.body else {}\n self.request_id = None\n\n _API_PREFIX = '/_ah/api/'\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_copy", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001863.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/discovery_api_proxy.py", "focal_class": null, "focal_method": "generate_discovery_doc", "tests": "import unittest\n\nclass Test_generate_discovery_doc(unittest.TestCase):\n def test_generate_discovery_doc_rest(self):\n body = {'baseUrl': 'https://tictactoe.appspot.com/_ah/api/tictactoe/v1/'}\n self.prepare_discovery_request(200, json.dumps(body))\n self.mox.ReplayAll()\n doc = self.discovery_api.generate_discovery_doc(self.api_config_dict, 'rest')\n self.mox.VerifyAll()\n self.assertTrue(doc)\n api_config = json.loads(doc)\n self.assertEquals('https://tictactoe.appspot.com/_ah/api/tictactoe/v1/', api_config['baseUrl'])\n\n def test_generate_discovery_doc_rpc(self):\n body = {'rpcUrl': 'https://tictactoe.appspot.com/_ah/api/rpc'}\n self.prepare_discovery_request(200, json.dumps(body))\n self.mox.ReplayAll()\n doc = self.discovery_api.generate_discovery_doc(self.api_config_dict, 'rpc')\n self.mox.VerifyAll()\n self.assertTrue(doc)\n api_config = json.loads(doc)\n self.assertEquals('https://tictactoe.appspot.com/_ah/api/rpc', api_config['rpcUrl'])\n\n def test_generate_discovery_doc_bad_api_config(self):\n self.prepare_discovery_request(503, None)\n self.mox.ReplayAll()\n doc = self.discovery_api.generate_discovery_doc('{ \"name\": \"none\" }', 'rpc')\n self.mox.VerifyAll()\n self.assertIsNone(doc)\n", "method_code": " def generate_discovery_doc(self, api_config, api_format):\n \"\"\"Generates a discovery document from an API file.\n \n Args:\n api_config: A string containing the .api file contents.\n api_format: A string, either 'rest' or 'rpc' depending on the which kind\n of discvoery doc is requested.\n \n Returns:\n The discovery doc as JSON string.\n \n Raises:\n ValueError: When api_format is invalid.\n \"\"\"\n if api_format not in ['rest', 'rpc']:\n raise ValueError('Invalid API format')\n path = 'apis/generate/' + api_format\n request_dict = {'config': json.dumps(api_config)}\n request_body = json.dumps(request_dict)\n return self._dispatch_request(path, request_body)\n ", "context": "class DiscoveryApiProxy(object):\n def generate_discovery_doc(self, api_config, api_format): ...\n def _dispatch_request(self, path, body): ...\n def generate_directory(self, api_configs): ...\n def get_static_file(self, path): ...\n\n _DISCOVERY_PROXY_HOST = 'webapis-discovery.appspot.com'\n _STATIC_PROXY_HOST = 'webapis-discovery.appspot.com'\n _DISCOVERY_API_PATH_PREFIX = '/_ah/api/discovery/v1/'\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_generate_discovery_doc_rest", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001864.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/discovery_api_proxy.py", "focal_class": null, "focal_method": "get_static_file", "tests": "import unittest\n\nclass Test_get_static_file(unittest.TestCase):\n def test_get_static_file_existing(self):\n body = 'static file body'\n self.prepare_discovery_request(200, body)\n self.mox.ReplayAll()\n response, response_body = self.discovery_api.get_static_file('/_ah/api/static/proxy.html')\n self.mox.VerifyAll()\n self.assertEqual(200, response.status)\n self.assertEqual(body, response_body)\n", "method_code": " def get_static_file(self, path):\n \"\"\"Returns static content via a GET request.\n \n Args:\n path: A string containing the URL path after the domain.\n \n Returns:\n A tuple of (response, response_body):\n response: A HTTPResponse object with the response from the static\n proxy host.\n response_body: A string containing the response body.\n \"\"\"\n connection = httplib.HTTPSConnection(self._STATIC_PROXY_HOST)\n try:\n connection.request('GET', path, None, {})\n response = connection.getresponse()\n response_body = response.read()\n finally:\n connection.close()\n return (response, response_body)\n ", "context": "class DiscoveryApiProxy(object):\n def get_static_file(self, path): ...\n def _dispatch_request(self, path, body): ...\n def generate_discovery_doc(self, api_config, api_format): ...\n def generate_directory(self, api_configs): ...\n\n _DISCOVERY_PROXY_HOST = 'webapis-discovery.appspot.com'\n _STATIC_PROXY_HOST = 'webapis-discovery.appspot.com'\n _DISCOVERY_API_PATH_PREFIX = '/_ah/api/discovery/v1/'\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_static_file_existing", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001865.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py", "focal_class": null, "focal_method": "handle_spi_response", "tests": "import unittest\n\nclass Test_handle_spi_response(unittest.TestCase):\n def test_handle_non_json_spi_response(self):\n orig_request = test_utils.build_request('/_ah/api/fake/path')\n spi_request = orig_request.copy()\n spi_response = dispatcher.ResponseTuple(200, [('Content-type', 'text/plain')], 'This is an invalid response.')\n response = self.server.handle_spi_response(orig_request, spi_request, spi_response, {}, self.start_response)\n error_json = {'error': {'message': 'Non-JSON reply: This is an invalid response.'}}\n body = json.dumps(error_json)\n self.assert_http_match(response, '500', [('Content-Type', 'application/json'), ('Content-Length', '%d' % len(body))], body)\n\n def test_handle_spi_response_json_rpc(self):\n \"\"\"Verify headers transformed, JsonRpc response transformed, written.\"\"\"\n orig_request = test_utils.build_request('/_ah/api/rpc', '{\"method\": \"foo.bar\", \"apiVersion\": \"X\"}')\n self.assertTrue(orig_request.is_rpc())\n orig_request.request_id = 'Z'\n spi_request = orig_request.copy()\n spi_response = dispatcher.ResponseTuple('200 OK', [('a', 'b')], '{\"some\": \"response\"}')\n response = self.server.handle_spi_response(orig_request, spi_request, spi_response, {}, self.start_response)\n response = ''.join(response)\n self.assertEqual(self.response_status, '200 OK')\n self.assertIn(('a', 'b'), self.response_headers)\n self.assertEqual({'id': 'Z', 'result': {'some': 'response'}}, json.loads(response))\n\n def test_handle_spi_response_batch_json_rpc(self):\n \"\"\"Verify that batch requests have an appropriate batch response.\"\"\"\n orig_request = test_utils.build_request('/_ah/api/rpc', '[{\"method\": \"foo.bar\", \"apiVersion\": \"X\"}]')\n self.assertTrue(orig_request.is_batch())\n self.assertTrue(orig_request.is_rpc())\n orig_request.request_id = 'Z'\n spi_request = orig_request.copy()\n spi_response = dispatcher.ResponseTuple('200 OK', [('a', 'b')], '{\"some\": \"response\"}')\n response = self.server.handle_spi_response(orig_request, spi_request, spi_response, {}, self.start_response)\n response = ''.join(response)\n self.assertEqual(self.response_status, '200 OK')\n self.assertIn(('a', 'b'), self.response_headers)\n self.assertEqual([{'id': 'Z', 'result': {'some': 'response'}}], json.loads(response))\n\n def test_handle_spi_response_rest(self):\n orig_request = test_utils.build_request('/_ah/api/test', '{}')\n spi_request = orig_request.copy()\n body = json.dumps({'some': 'response'}, indent=1)\n spi_response = dispatcher.ResponseTuple('200 OK', [('a', 'b')], body)\n response = self.server.handle_spi_response(orig_request, spi_request, spi_response, {}, self.start_response)\n self.assert_http_match(response, '200 OK', [('a', 'b'), ('Content-Length', '%d' % len(body))], body)\n", "method_code": " def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response):\n \"\"\"Handle SPI response, transforming output as needed.\n \n This calls start_response and returns the response body.\n \n Args:\n orig_request: An ApiRequest, the original request from the user.\n spi_request: An ApiRequest, the transformed request that was sent to the\n SPI handler.\n response: A ResponseTuple, the response from the SPI handler.\n method_config: A dict, the API config of the method to be called.\n start_response: A function with semantics defined in PEP-333.\n \n Returns:\n A string containing the response body.\n \"\"\"\n for header, value in response.headers:\n if header.lower() == 'content-type' and (not value.lower().startswith('application/json')):\n return self.fail_request(orig_request, 'Non-JSON reply: %s' % response.content, start_response)\n self.check_error_response(response)\n if orig_request.is_rpc():\n body = self.transform_jsonrpc_response(spi_request, response.content)\n else:\n empty_response = self.check_empty_response(orig_request, method_config, start_response)\n if empty_response is not None:\n return empty_response\n body = self.transform_rest_response(response.content)\n cors_handler = EndpointsDispatcher.__CheckCorsHeaders(orig_request)\n return util.send_wsgi_response(response.status, response.headers, body, start_response, cors_handler=cors_handler)\n ", "context": "class EndpointsDispatcher(object):\n def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response): ...\n def __init__(self, dispatcher, config_manager=None): ...\n def _add_dispatcher(self, path_regex, dispatch_function): ...\n def __call__(self, environ, start_response): ...\n def dispatch(self, request, start_response): ...\n def dispatch_non_api_requests(self, request, start_response): ...\n def handle_api_explorer_request(self, request, start_response): ...\n def handle_api_static_request(self, request, start_response): ...\n def get_api_configs(self): ...\n def verify_response(response, status_code, content_type=None): ...\n def handle_get_api_configs_response(self, api_config_response): ...\n def call_spi(self, orig_request, start_response): ...\n def fail_request(self, orig_request, message, start_response): ...\n def lookup_rest_method(self, orig_request): ...\n def lookup_rpc_method(self, orig_request): ...\n def transform_request(self, orig_request, params, method_config): ...\n def _add_message_field(self, field_name, value, params): ...\n def _update_from_body(self, destination, source): ...\n def transform_rest_request(self, orig_request, params, method_parameters): ...\n def transform_jsonrpc_request(self, orig_request): ...\n def check_error_response(self, response): ...\n def check_empty_response(self, orig_request, method_config, start_response): ...\n def transform_rest_response(self, response_body): ...\n def transform_jsonrpc_response(self, spi_request, response_body): ...\n def _finish_rpc_response(self, request_id, is_batch, body_json): ...\n def _handle_request_error(self, orig_request, error, start_response): ...\n\n self._dispatcher = dispatcher\n self.config_manager = config_manager\n self._dispatchers = []\n\n _API_EXPLORER_URL = 'http://apis-explorer.appspot.com/apis-explorer/?base='\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_handle_non_json_spi_response", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001866.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py", "focal_class": null, "focal_method": "transform_rest_response", "tests": "import unittest\n\nclass Test_transform_rest_response(unittest.TestCase):\n def test_transform_rest_response(self):\n \"\"\"Verify the response is reformatted correctly.\"\"\"\n orig_response = '{\"sample\": \"test\", \"value1\": {\"value2\": 2}}'\n expected_response = '{\\n \"sample\": \"test\", \\n \"value1\": {\\n \"value2\": 2\\n }\\n}'\n self.assertEqual(expected_response, self.server.transform_rest_response(orig_response))\n", "method_code": " def transform_rest_response(self, response_body):\n \"\"\"Translates an apiserving REST response so it's ready to return.\n \n Currently, the only thing that needs to be fixed here is indentation,\n so it's consistent with what the live app will return.\n \n Args:\n response_body: A string containing the backend response.\n \n Returns:\n A reformatted version of the response JSON.\n \"\"\"\n body_json = json.loads(response_body)\n return json.dumps(body_json, indent=1, sort_keys=True)\n ", "context": "class EndpointsDispatcher(object):\n def transform_rest_response(self, response_body): ...\n def __init__(self, dispatcher, config_manager=None): ...\n def _add_dispatcher(self, path_regex, dispatch_function): ...\n def __call__(self, environ, start_response): ...\n def dispatch(self, request, start_response): ...\n def dispatch_non_api_requests(self, request, start_response): ...\n def handle_api_explorer_request(self, request, start_response): ...\n def handle_api_static_request(self, request, start_response): ...\n def get_api_configs(self): ...\n def verify_response(response, status_code, content_type=None): ...\n def handle_get_api_configs_response(self, api_config_response): ...\n def call_spi(self, orig_request, start_response): ...\n def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response): ...\n def fail_request(self, orig_request, message, start_response): ...\n def lookup_rest_method(self, orig_request): ...\n def lookup_rpc_method(self, orig_request): ...\n def transform_request(self, orig_request, params, method_config): ...\n def _add_message_field(self, field_name, value, params): ...\n def _update_from_body(self, destination, source): ...\n def transform_rest_request(self, orig_request, params, method_parameters): ...\n def transform_jsonrpc_request(self, orig_request): ...\n def check_error_response(self, response): ...\n def check_empty_response(self, orig_request, method_config, start_response): ...\n def transform_jsonrpc_response(self, spi_request, response_body): ...\n def _finish_rpc_response(self, request_id, is_batch, body_json): ...\n def _handle_request_error(self, orig_request, error, start_response): ...\n\n self._dispatcher = dispatcher\n self.config_manager = config_manager\n self._dispatchers = []\n\n _API_EXPLORER_URL = 'http://apis-explorer.appspot.com/apis-explorer/?base='\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_transform_rest_response", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001867.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py", "focal_class": null, "focal_method": "transform_jsonrpc_response", "tests": "import unittest\n\nclass Test_transform_jsonrpc_response(unittest.TestCase):\n def test_transform_json_rpc_response_batch(self):\n \"\"\"Verify request_id inserted into the body, and body into body.result.\"\"\"\n orig_request = test_utils.build_request('/_ah/api/rpc', '[{\"params\": {\"sample\": \"body\"}, \"id\": \"42\"}]')\n request = orig_request.copy()\n request.request_id = '42'\n orig_response = '{\"sample\": \"body\"}'\n response = self.server.transform_jsonrpc_response(request, orig_response)\n self.assertEqual([{'result': {'sample': 'body'}, 'id': '42'}], json.loads(response))\n", "method_code": " def transform_jsonrpc_response(self, spi_request, response_body):\n \"\"\"Translates an apiserving response to a JsonRpc response.\n \n Args:\n spi_request: An ApiRequest, the transformed request that was sent to the\n SPI handler.\n response_body: A string containing the backend response to transform\n back to JsonRPC.\n \n Returns:\n A string with the updated, JsonRPC-formatted request body.\n \"\"\"\n body_json = {'result': json.loads(response_body)}\n return self._finish_rpc_response(spi_request.request_id, spi_request.is_batch(), body_json)\n ", "context": "class EndpointsDispatcher(object):\n def transform_jsonrpc_response(self, spi_request, response_body): ...\n def __init__(self, dispatcher, config_manager=None): ...\n def _add_dispatcher(self, path_regex, dispatch_function): ...\n def __call__(self, environ, start_response): ...\n def dispatch(self, request, start_response): ...\n def dispatch_non_api_requests(self, request, start_response): ...\n def handle_api_explorer_request(self, request, start_response): ...\n def handle_api_static_request(self, request, start_response): ...\n def get_api_configs(self): ...\n def verify_response(response, status_code, content_type=None): ...\n def handle_get_api_configs_response(self, api_config_response): ...\n def call_spi(self, orig_request, start_response): ...\n def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response): ...\n def fail_request(self, orig_request, message, start_response): ...\n def lookup_rest_method(self, orig_request): ...\n def lookup_rpc_method(self, orig_request): ...\n def transform_request(self, orig_request, params, method_config): ...\n def _add_message_field(self, field_name, value, params): ...\n def _update_from_body(self, destination, source): ...\n def transform_rest_request(self, orig_request, params, method_parameters): ...\n def transform_jsonrpc_request(self, orig_request): ...\n def check_error_response(self, response): ...\n def check_empty_response(self, orig_request, method_config, start_response): ...\n def transform_rest_response(self, response_body): ...\n def _finish_rpc_response(self, request_id, is_batch, body_json): ...\n def _handle_request_error(self, orig_request, error, start_response): ...\n\n self._dispatcher = dispatcher\n self.config_manager = config_manager\n self._dispatchers = []\n\n _API_EXPLORER_URL = 'http://apis-explorer.appspot.com/apis-explorer/?base='\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_transform_json_rpc_response_batch", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001868.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py", "focal_class": null, "focal_method": "lookup_rpc_method", "tests": "import unittest\n\nclass Test_lookup_rpc_method(unittest.TestCase):\n def test_lookup_rpc_method_no_body(self):\n orig_request = test_utils.build_request('/_ah/api/rpc', '')\n self.assertEqual(None, self.server.lookup_rpc_method(orig_request))\n\n def test_lookup_rpc_method(self):\n self.mox.StubOutWithMock(self.server.config_manager, 'lookup_rpc_method')\n self.server.config_manager.lookup_rpc_method('foo', 'v1').AndReturn('bar')\n self.mox.ReplayAll()\n orig_request = test_utils.build_request('/_ah/api/rpc', '{\"method\": \"foo\", \"apiVersion\": \"v1\"}')\n self.assertEqual('bar', self.server.lookup_rpc_method(orig_request))\n self.mox.VerifyAll()\n", "method_code": " def lookup_rpc_method(self, orig_request):\n \"\"\"Looks up and returns RPC method for the currently-pending request.\n \n Args:\n orig_request: An ApiRequest, the original request from the user.\n \n Returns:\n The RPC method descriptor that was found for the current request, or None\n if none was found.\n \"\"\"\n if not orig_request.body_json:\n return None\n method_name = orig_request.body_json.get('method', '')\n version = orig_request.body_json.get('apiVersion', '')\n orig_request.method_name = method_name\n return self.config_manager.lookup_rpc_method(method_name, version)\n ", "context": "class EndpointsDispatcher(object):\n def lookup_rpc_method(self, orig_request): ...\n def __init__(self, dispatcher, config_manager=None): ...\n def _add_dispatcher(self, path_regex, dispatch_function): ...\n def __call__(self, environ, start_response): ...\n def dispatch(self, request, start_response): ...\n def dispatch_non_api_requests(self, request, start_response): ...\n def handle_api_explorer_request(self, request, start_response): ...\n def handle_api_static_request(self, request, start_response): ...\n def get_api_configs(self): ...\n def verify_response(response, status_code, content_type=None): ...\n def handle_get_api_configs_response(self, api_config_response): ...\n def call_spi(self, orig_request, start_response): ...\n def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response): ...\n def fail_request(self, orig_request, message, start_response): ...\n def lookup_rest_method(self, orig_request): ...\n def transform_request(self, orig_request, params, method_config): ...\n def _add_message_field(self, field_name, value, params): ...\n def _update_from_body(self, destination, source): ...\n def transform_rest_request(self, orig_request, params, method_parameters): ...\n def transform_jsonrpc_request(self, orig_request): ...\n def check_error_response(self, response): ...\n def check_empty_response(self, orig_request, method_config, start_response): ...\n def transform_rest_response(self, response_body): ...\n def transform_jsonrpc_response(self, spi_request, response_body): ...\n def _finish_rpc_response(self, request_id, is_batch, body_json): ...\n def _handle_request_error(self, orig_request, error, start_response): ...\n\n self._dispatcher = dispatcher\n self.config_manager = config_manager\n self._dispatchers = []\n\n _API_EXPLORER_URL = 'http://apis-explorer.appspot.com/apis-explorer/?base='\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_lookup_rpc_method_no_body", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001869.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py", "focal_class": null, "focal_method": "verify_response", "tests": "import unittest\n\nclass Test_verify_response(unittest.TestCase):\n def test_verify_response(self):\n response = dispatcher.ResponseTuple('200', [('Content-Type', 'a')], '')\n self.assertEqual(True, self.server.verify_response(response, 200, 'a'))\n self.assertEqual(True, self.server.verify_response(response, 200, None))\n self.assertEqual(False, self.server.verify_response(response, 400, 'a'))\n self.assertEqual(False, self.server.verify_response(response, 200, 'b'))\n response = dispatcher.ResponseTuple('200', [('Content-Length', '10')], '')\n self.assertEqual(True, self.server.verify_response(response, 200, None))\n self.assertEqual(False, self.server.verify_response(response, 200, 'a'))\n", "method_code": " def verify_response(response, status_code, content_type=None):\n \"\"\"Verifies that a response has the expected status and content type.\n \n Args:\n response: The ResponseTuple to be checked.\n status_code: An int, the HTTP status code to be compared with response\n status.\n content_type: A string with the acceptable Content-Type header value.\n None allows any content type.\n \n Returns:\n True if both status_code and content_type match, else False.\n \"\"\"\n status = int(response.status.split(' ', 1)[0])\n if status != status_code:\n return False\n if content_type is None:\n return True\n for header, value in response.headers:\n if header.lower() == 'content-type':\n return value == content_type\n else:\n return False\n ", "context": "class EndpointsDispatcher(object):\n @staticmethod\n def verify_response(response, status_code, content_type=None): ...\n def __init__(self, dispatcher, config_manager=None): ...\n def _add_dispatcher(self, path_regex, dispatch_function): ...\n def __call__(self, environ, start_response): ...\n def dispatch(self, request, start_response): ...\n def dispatch_non_api_requests(self, request, start_response): ...\n def handle_api_explorer_request(self, request, start_response): ...\n def handle_api_static_request(self, request, start_response): ...\n def get_api_configs(self): ...\n def handle_get_api_configs_response(self, api_config_response): ...\n def call_spi(self, orig_request, start_response): ...\n def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response): ...\n def fail_request(self, orig_request, message, start_response): ...\n def lookup_rest_method(self, orig_request): ...\n def lookup_rpc_method(self, orig_request): ...\n def transform_request(self, orig_request, params, method_config): ...\n def _add_message_field(self, field_name, value, params): ...\n def _update_from_body(self, destination, source): ...\n def transform_rest_request(self, orig_request, params, method_parameters): ...\n def transform_jsonrpc_request(self, orig_request): ...\n def check_error_response(self, response): ...\n def check_empty_response(self, orig_request, method_config, start_response): ...\n def transform_rest_response(self, response_body): ...\n def transform_jsonrpc_response(self, spi_request, response_body): ...\n def _finish_rpc_response(self, request_id, is_batch, body_json): ...\n def _handle_request_error(self, orig_request, error, start_response): ...\n\n self._dispatcher = dispatcher\n self.config_manager = config_manager\n self._dispatchers = []\n\n _API_EXPLORER_URL = 'http://apis-explorer.appspot.com/apis-explorer/?base='\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_verify_response", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001870.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py", "focal_class": null, "focal_method": "check_empty_response", "tests": "import unittest\n\nclass Test_check_empty_response(unittest.TestCase):\n def test_check_empty_response(self):\n \"\"\"Test that check_empty_response returns 204 for an empty response.\"\"\"\n orig_request = test_utils.build_request('/_ah/api/test', '{}')\n method_config = {'response': {'body': 'empty'}}\n empty_response = self.server.check_empty_response(orig_request, method_config, self.start_response)\n self.assert_http_match(empty_response, 204, [('Content-Length', '0')], '')\n\n def test_check_non_empty_response(self):\n \"\"\"Test that check_empty_response returns None for a non-empty response.\"\"\"\n orig_request = test_utils.build_request('/_ah/api/test', '{}')\n method_config = {'response': {'body': 'autoTemplate(backendResponse)'}}\n empty_response = self.server.check_empty_response(orig_request, method_config, self.start_response)\n self.assertIsNone(empty_response)\n self.assertIsNone(self.response_status)\n self.assertIsNone(self.response_headers)\n self.assertIsNone(self.response_exc_info)\n", "method_code": " def check_empty_response(self, orig_request, method_config, start_response):\n \"\"\"If the response from the SPI is empty, return a HTTP 204 No Content.\n \n Args:\n orig_request: An ApiRequest, the original request from the user.\n method_config: A dict, the API config of the method to be called.\n start_response: A function with semantics defined in PEP-333.\n \n Returns:\n If the SPI response was empty, this returns a string containing the\n response body that should be returned to the user. If the SPI response\n wasn't empty, this returns None, indicating that we should not exit early\n with a 204.\n \"\"\"\n response_config = method_config.get('response', {}).get('body')\n if response_config == 'empty':\n cors_handler = EndpointsDispatcher.__CheckCorsHeaders(orig_request)\n return util.send_wsgi_no_content_response(start_response, cors_handler)\n ", "context": "class EndpointsDispatcher(object):\n def check_empty_response(self, orig_request, method_config, start_response): ...\n def __init__(self, dispatcher, config_manager=None): ...\n def _add_dispatcher(self, path_regex, dispatch_function): ...\n def __call__(self, environ, start_response): ...\n def dispatch(self, request, start_response): ...\n def dispatch_non_api_requests(self, request, start_response): ...\n def handle_api_explorer_request(self, request, start_response): ...\n def handle_api_static_request(self, request, start_response): ...\n def get_api_configs(self): ...\n def verify_response(response, status_code, content_type=None): ...\n def handle_get_api_configs_response(self, api_config_response): ...\n def call_spi(self, orig_request, start_response): ...\n def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response): ...\n def fail_request(self, orig_request, message, start_response): ...\n def lookup_rest_method(self, orig_request): ...\n def lookup_rpc_method(self, orig_request): ...\n def transform_request(self, orig_request, params, method_config): ...\n def _add_message_field(self, field_name, value, params): ...\n def _update_from_body(self, destination, source): ...\n def transform_rest_request(self, orig_request, params, method_parameters): ...\n def transform_jsonrpc_request(self, orig_request): ...\n def check_error_response(self, response): ...\n def transform_rest_response(self, response_body): ...\n def transform_jsonrpc_response(self, spi_request, response_body): ...\n def _finish_rpc_response(self, request_id, is_batch, body_json): ...\n def _handle_request_error(self, orig_request, error, start_response): ...\n\n self._dispatcher = dispatcher\n self.config_manager = config_manager\n self._dispatchers = []\n\n _API_EXPLORER_URL = 'http://apis-explorer.appspot.com/apis-explorer/?base='\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_check_empty_response", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001871.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py", "focal_class": null, "focal_method": "transform_request", "tests": "import unittest\n\nclass Test_transform_request(unittest.TestCase):\n def test_transform_request(self):\n \"\"\"Verify path is method name after a request is transformed.\"\"\"\n request = test_utils.build_request('/_ah/api/test/{gid}', '{\"sample\": \"body\"}')\n method_config = {'rosyMethod': 'GuestbookApi.greetings_get'}\n new_request = self.server.transform_request(request, {'gid': 'X'}, method_config)\n self.assertEqual({'sample': 'body', 'gid': 'X'}, json.loads(new_request.body))\n self.assertEqual('GuestbookApi.greetings_get', new_request.path)\n", "method_code": " def transform_request(self, orig_request, params, method_config):\n \"\"\"Transforms orig_request to apiserving request.\n \n This method uses orig_request to determine the currently-pending request\n and returns a new transformed request ready to send to the SPI. This\n method accepts a rest-style or RPC-style request.\n \n Args:\n orig_request: An ApiRequest, the original request from the user.\n params: A dictionary containing path parameters for rest requests, or\n None for an RPC request.\n method_config: A dict, the API config of the method to be called.\n \n Returns:\n An ApiRequest that's a copy of the current request, modified so it can\n be sent to the SPI. The path is updated and parts of the body or other\n properties may also be changed.\n \"\"\"\n if orig_request.is_rpc():\n request = self.transform_jsonrpc_request(orig_request)\n else:\n method_params = method_config.get('request', {}).get('parameters', {})\n request = self.transform_rest_request(orig_request, params, method_params)\n request.path = method_config.get('rosyMethod', '')\n return request\n ", "context": "class EndpointsDispatcher(object):\n def transform_request(self, orig_request, params, method_config): ...\n def __init__(self, dispatcher, config_manager=None): ...\n def _add_dispatcher(self, path_regex, dispatch_function): ...\n def __call__(self, environ, start_response): ...\n def dispatch(self, request, start_response): ...\n def dispatch_non_api_requests(self, request, start_response): ...\n def handle_api_explorer_request(self, request, start_response): ...\n def handle_api_static_request(self, request, start_response): ...\n def get_api_configs(self): ...\n def verify_response(response, status_code, content_type=None): ...\n def handle_get_api_configs_response(self, api_config_response): ...\n def call_spi(self, orig_request, start_response): ...\n def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response): ...\n def fail_request(self, orig_request, message, start_response): ...\n def lookup_rest_method(self, orig_request): ...\n def lookup_rpc_method(self, orig_request): ...\n def _add_message_field(self, field_name, value, params): ...\n def _update_from_body(self, destination, source): ...\n def transform_rest_request(self, orig_request, params, method_parameters): ...\n def transform_jsonrpc_request(self, orig_request): ...\n def check_error_response(self, response): ...\n def check_empty_response(self, orig_request, method_config, start_response): ...\n def transform_rest_response(self, response_body): ...\n def transform_jsonrpc_response(self, spi_request, response_body): ...\n def _finish_rpc_response(self, request_id, is_batch, body_json): ...\n def _handle_request_error(self, orig_request, error, start_response): ...\n\n self._dispatcher = dispatcher\n self.config_manager = config_manager\n self._dispatchers = []\n\n _API_EXPLORER_URL = 'http://apis-explorer.appspot.com/apis-explorer/?base='\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_transform_request", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001872.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py", "focal_class": null, "focal_method": "transform_jsonrpc_request", "tests": "import unittest\n\nclass Test_transform_jsonrpc_request(unittest.TestCase):\n def test_transform_json_rpc_request(self):\n \"\"\"Verify request_id is extracted and body is scoped to body.params.\"\"\"\n orig_request = test_utils.build_request('/_ah/api/rpc', '{\"params\": {\"sample\": \"body\"}, \"id\": \"42\"}')\n new_request = self.server.transform_jsonrpc_request(orig_request)\n self.assertEqual({'sample': 'body'}, json.loads(new_request.body))\n self.assertEqual('42', new_request.request_id)\n", "method_code": " def transform_jsonrpc_request(self, orig_request):\n \"\"\"Translates a JsonRpc request/response into apiserving request/response.\n \n Args:\n orig_request: An ApiRequest, the original request from the user.\n \n Returns:\n A new request with the request_id updated and params moved to the body.\n \"\"\"\n request = orig_request.copy()\n request.request_id = request.body_json.get('id')\n request.body_json = request.body_json.get('params', {})\n request.body = json.dumps(request.body_json)\n return request\n ", "context": "class EndpointsDispatcher(object):\n def transform_jsonrpc_request(self, orig_request): ...\n def __init__(self, dispatcher, config_manager=None): ...\n def _add_dispatcher(self, path_regex, dispatch_function): ...\n def __call__(self, environ, start_response): ...\n def dispatch(self, request, start_response): ...\n def dispatch_non_api_requests(self, request, start_response): ...\n def handle_api_explorer_request(self, request, start_response): ...\n def handle_api_static_request(self, request, start_response): ...\n def get_api_configs(self): ...\n def verify_response(response, status_code, content_type=None): ...\n def handle_get_api_configs_response(self, api_config_response): ...\n def call_spi(self, orig_request, start_response): ...\n def handle_spi_response(self, orig_request, spi_request, response, method_config, start_response): ...\n def fail_request(self, orig_request, message, start_response): ...\n def lookup_rest_method(self, orig_request): ...\n def lookup_rpc_method(self, orig_request): ...\n def transform_request(self, orig_request, params, method_config): ...\n def _add_message_field(self, field_name, value, params): ...\n def _update_from_body(self, destination, source): ...\n def transform_rest_request(self, orig_request, params, method_parameters): ...\n def check_error_response(self, response): ...\n def check_empty_response(self, orig_request, method_config, start_response): ...\n def transform_rest_response(self, response_body): ...\n def transform_jsonrpc_response(self, spi_request, response_body): ...\n def _finish_rpc_response(self, request_id, is_batch, body_json): ...\n def _handle_request_error(self, orig_request, error, start_response): ...\n\n self._dispatcher = dispatcher\n self.config_manager = config_manager\n self._dispatchers = []\n\n _API_EXPLORER_URL = 'http://apis-explorer.appspot.com/apis-explorer/?base='\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_transform_json_rpc_request", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001873.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/request_state.py", "focal_class": null, "focal_method": "end_thread", "tests": "import unittest\n\nclass Test_end_thread(unittest.TestCase):\n def test_start_and_end_thread(self):\n self.request_state._threads = set()\n self.request_state.start_thread()\n self.assertEquals(set([threading.current_thread().ident]), self.request_state._threads)\n self.request_state.end_thread()\n self.assertEquals(set(), self.request_state._threads)\n", "method_code": " def end_thread(self):\n \"\"\"Records the end of a user-created thread as part of this request.\"\"\"\n thread_id = threading.current_thread().ident\n with self._condition:\n self._threads.remove(thread_id)\n self._condition.notify()\n ", "context": "class RequestState(object):\n def end_thread(self): ...\n def __init__(self, request_id): ...\n def start_thread(self): ...\n def end_request(self): ...\n def inject_exception(self, exception): ...\n\n self.request_id = request_id\n self._threads = set([threading.current_thread().ident])\n self._condition = threading.Condition()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_start_and_end_thread", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001874.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/request_state.py", "focal_class": null, "focal_method": "inject_exception", "tests": "import unittest\n\nclass Test_inject_exception(unittest.TestCase):\n def test_inject_exception(self):\n ctypes.pythonapi.PyThreadState_SetAsyncExc(CtypesComparator(ctypes.c_long(threading.current_thread().ident)), CtypesComparator(ctypes.py_object(Exception)))\n self.mox.ReplayAll()\n self.request_state.inject_exception(Exception)\n self.mox.VerifyAll()\n", "method_code": " def inject_exception(self, exception):\n \"\"\"Injects an exception to all threads running as part of this request.\"\"\"\n with self._condition:\n thread_ids = list(self._threads)\n for thread_id in thread_ids:\n ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id), ctypes.py_object(exception))\n ", "context": "class RequestState(object):\n def inject_exception(self, exception): ...\n def __init__(self, request_id): ...\n def start_thread(self): ...\n def end_thread(self): ...\n def end_request(self): ...\n\n self.request_id = request_id\n self._threads = set([threading.current_thread().ident])\n self._condition = threading.Condition()\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_inject_exception", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001875.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/request_state.py", "focal_class": null, "focal_method": "end_request", "tests": "import unittest\n\nclass Test_end_request(unittest.TestCase):\n def test_end_request(self):\n\n def remove_fake_thread():\n self.request_state._threads.remove('fake thread id')\n self.mox.StubOutWithMock(self.request_state._condition, 'wait')\n self.request_state._threads.add('fake thread id')\n self.request_state._condition.wait().WithSideEffects(remove_fake_thread)\n self.mox.ReplayAll()\n self.request_state.end_request()\n self.mox.VerifyAll()\n\n def test_end_request_function(self):\n request_state._request_states = {'id': self.request_state}\n self.mox.StubOutWithMock(self.request_state, 'end_request')\n self.request_state.end_request()\n self.mox.ReplayAll()\n request_state.end_request('id')\n self.mox.VerifyAll()\n self.assertEqual([], request_state.get_request_states())\n", "method_code": "def end_request(request_id):\n \"\"\"Ends the request with the provided request id.\"\"\"\n with _request_states_lock:\n request_state = _request_states[request_id]\n request_state.end_request()\n with _request_states_lock:\n del _request_states[request_id]", "context": "def end_request(request_id): ...\ndef start_request(request_id): ...\ndef end_request(request_id): ...\ndef get_request_state(request_id): ...\ndef get_request_states(): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_end_request", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001876.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/request_state.py", "focal_class": null, "focal_method": "get_request_states", "tests": "import unittest\n\nclass Test_get_request_states(unittest.TestCase):\n def test_get_request_states(self):\n request_state.start_request('1')\n request_state.start_request('2')\n request_state.start_request('3')\n self.assertEqual(3, len(request_state.get_request_states()))\n self.assertItemsEqual([request_state.get_request_state(request_id) for request_id in ['1', '2', '3']], request_state.get_request_states())\n", "method_code": "def get_request_states():\n \"\"\"Returns a list of RequestState instances for all current requests.\"\"\"\n with _request_states_lock:\n return _request_states.values()", "context": "def get_request_states(): ...\ndef start_request(request_id): ...\ndef end_request(request_id): ...\ndef get_request_state(request_id): ...\ndef get_request_states(): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_request_states", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001877.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", "focal_class": null, "focal_method": "_enable_libraries", "tests": "import unittest\n\nclass Test_enable_libraries(unittest.TestCase):\n def test_enable_libraries(self):\n sandbox._THIRD_PARTY_LIBRARY_FORMAT_STRING = 'name=%(name)s-version=%(version)s'\n libs = self.config.libraries\n libs.add(name='foo', version='12345')\n libs.add(name='webapp2', version='2.5.1')\n self.assertEqual([os.path.join(os.path.dirname(os.path.dirname(google.__file__)), 'name=foo-version=12345'), os.path.join(os.path.dirname(os.path.dirname(google.__file__)), 'name=webapp2-version=2.5.1')], sandbox._enable_libraries(libs))\n", "method_code": "def _enable_libraries(libraries):\n \"\"\"Add enabled libraries to the path.\n\n Args:\n libraries: A repeated Config.Library containing the libraries to enable.\n\n Returns:\n A list of paths containing the enabled libraries.\n \"\"\"\n library_dirs = []\n library_pattern = os.path.join(os.path.dirname(os.path.dirname(google.__file__)), _THIRD_PARTY_LIBRARY_FORMAT_STRING)\n for library in libraries:\n library_dir = os.path.abspath(library_pattern % {'name': library.name.encode('ascii'), 'version': library.version.encode('ascii')})\n library_dirs.append(library_dir)\n return library_dirs", "context": "def _enable_libraries(libraries): ...\ndef add_open_hook(install_open_hook): ...\ndef _make_request_id_aware_start_new_thread(base_start_new_thread): ...\ndef enable_sandbox(config): ...\ndef _prune_sys_modules(): ...\ndef _install_import_hooks(config, path_override_hook): ...\ndef _install_fake_file(config, python_lib_paths, path_override_hook): ...\ndef _install_open_hooks(): ...\ndef _find_shared_object_c_module(): ...\ndef _should_keep_module(name): ...\ndef _init_logging(stderr_log_level): ...\ndef _enable_libraries(libraries): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_enable_libraries", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001878.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", "focal_class": null, "focal_method": "is_package", "tests": "import unittest\n\nclass Test_is_package(unittest.TestCase):\n def test_is_package(self):\n self.assertTrue(self.hook.is_package('distutils'))\n", "method_code": " def is_package(self, fullname):\n \"\"\"Returns whether the module specified by fullname refers to a package.\n \n This implements part of the extensions to the PEP 302 importer protocol.\n \n Args:\n fullname: The fullname of the module.\n \n Returns:\n True if fullname refers to a package.\n \"\"\"\n submodule, search_path = self._get_parent_search_path(fullname)\n _, _, description, loader = self._find_module_or_loader(submodule, fullname, search_path)\n if loader:\n return loader.is_package(fullname)\n _, _, file_type = description\n if file_type == imp.PKG_DIRECTORY:\n return True\n return False\n ", "context": "class BaseImportHook(object):\n def is_package(self, fullname): ...\n def _find_module_or_loader(self, submodule_name, fullname, path): ...\n def _find_and_load_module(self, submodule_name, fullname, path): ...\n def _find_path_hook(self, submodule, submodule_fullname, path_entry): ...\n def _get_parent_package(self, fullname): ...\n def _get_parent_search_path(self, fullname): ...\n def _get_module_info(self, fullname): ...\n def get_source(self, fullname): ...\n def get_code(self, fullname): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_is_package", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001879.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", "focal_class": null, "focal_method": "get_source", "tests": "import unittest\n\nclass Test_get_source(unittest.TestCase):\n def test_get_source(self):\n with open(__import__('distutils').__file__.replace('.pyc', '.py')) as f:\n source = f.read()\n self.assertEqual(source, self.hook.get_source('distutils'))\n", "method_code": " def get_source(self, fullname):\n \"\"\"Returns the source for the module specified by fullname.\n \n This implements part of the extensions to the PEP 302 importer protocol.\n \n Args:\n fullname: The fullname of the module.\n \n Returns:\n The source for the module.\n \"\"\"\n full_path, _, _, loader = self._get_module_info(fullname)\n if loader:\n return loader.get_source(fullname)\n if full_path is None:\n return None\n source_file = open(full_path)\n try:\n return source_file.read()\n finally:\n source_file.close()\n ", "context": "class BaseImportHook(object):\n def get_source(self, fullname): ...\n def _find_module_or_loader(self, submodule_name, fullname, path): ...\n def _find_and_load_module(self, submodule_name, fullname, path): ...\n def _find_path_hook(self, submodule, submodule_fullname, path_entry): ...\n def _get_parent_package(self, fullname): ...\n def _get_parent_search_path(self, fullname): ...\n def _get_module_info(self, fullname): ...\n def is_package(self, fullname): ...\n def get_code(self, fullname): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_source", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001880.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", "focal_class": null, "focal_method": "get_code", "tests": "import unittest\n\nclass Test_get_code(unittest.TestCase):\n def test_get_code(self):\n filename = __import__('distutils').__file__.replace('.pyc', '.py')\n with open(filename) as f:\n expected_code = compile(f.read(), filename, 'exec')\n self.assertEqual(expected_code, self.hook.get_code('distutils'))\n", "method_code": " def get_code(self, fullname):\n \"\"\"Returns the code object for the module specified by fullname.\n \n This implements part of the extensions to the PEP 302 importer protocol.\n \n Args:\n fullname: The fullname of the module.\n \n Returns:\n The code object associated the module.\n \"\"\"\n full_path, _, _, loader = self._get_module_info(fullname)\n if loader:\n return loader.get_code(fullname)\n if full_path is None:\n return None\n source_file = open(full_path)\n try:\n source_code = source_file.read()\n finally:\n source_file.close()\n encoding = DEFAULT_ENCODING\n for line in source_code.split('\\n', 2)[:2]:\n matches = CODING_MAGIC_COMMENT_RE.findall(line)\n if matches:\n encoding = matches[0].lower()\n source_code.decode(encoding)\n return compile(source_code, full_path, 'exec')\n ", "context": "class BaseImportHook(object):\n def get_code(self, fullname): ...\n def _find_module_or_loader(self, submodule_name, fullname, path): ...\n def _find_and_load_module(self, submodule_name, fullname, path): ...\n def _find_path_hook(self, submodule, submodule_fullname, path_entry): ...\n def _get_parent_package(self, fullname): ...\n def _get_parent_search_path(self, fullname): ...\n def _get_module_info(self, fullname): ...\n def is_package(self, fullname): ...\n def get_source(self, fullname): ...\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_get_code", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001881.py"} {"focal_file": "google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", "focal_class": null, "focal_method": "find_module", "tests": "import unittest\n\nclass Test_find_module(unittest.TestCase):\n def test_find_module(self):\n self.assertIsInstance(sandbox.PyCryptoRandomImportHook.find_module('Crypto.Random.OSRNG.posix'), sandbox.PyCryptoRandomImportHook)\n self.assertIsNone(sandbox.PyCryptoRandomImportHook.find_module('Crypto.Random.OSRNG.nt'))\n", "method_code": " def find_module(self, fullname, unused_path=None):\n return fullname in self._modules and self or None\n ", "context": "class PathOverrideImportHook(BaseImportHook):\n def find_module(self, fullname, unused_path=None): ...\n def __init__(self, modules): ...\n def load_module(self, fullname): ...\n def _get_module_path(self, fullname): ...\n\n self._modules = {}\n self.extra_accessible_paths = []\n self.extra_sys_paths = []\n", "repository": "Dalimil/Hack-Cambridge", "test_name": "test_find_module", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001882.py"} {"focal_file": "bitbake/lib/bb/data.py", "focal_class": null, "focal_method": "renameVar", "tests": "import unittest\n\nclass Test_renameVar(unittest.TestCase):\n def test_rename(self):\n self.d.renameVar('foo', 'newfoo')\n self.assertEqual(self.d.getVar('newfoo'), 'value_of_foo')\n self.assertEqual(self.d.getVar('foo'), None)\n", "method_code": "def renameVar(key, newkey, d):\n \"\"\"Renames a variable from key to newkey\"\"\"\n d.renameVar(key, newkey)", "context": "def renameVar(key, newkey, d): ...\ndef init(): ...\ndef init_db(parent=None): ...\ndef createCopy(source): ...\ndef initVar(var, d): ...\ndef setVar(var, value, d): ...\ndef getVar(var, d, exp=0): ...\ndef renameVar(key, newkey, d): ...\ndef delVar(var, d): ...\ndef appendVar(var, value, d): ...\ndef setVarFlag(var, flag, flagvalue, d): ...\ndef getVarFlag(var, flag, d): ...\ndef delVarFlag(var, flag, d): ...\ndef setVarFlags(var, flags, d): ...\ndef getVarFlags(var, d): ...\ndef delVarFlags(var, d): ...\ndef keys(d): ...\ndef expand(s, d, varname=None): ...\ndef expandKeys(alterdata, readdata=None): ...\ndef inheritFromOS(d, savedenv, permitted): ...\ndef emit_var(var, o=sys.__stdout__, d=init(), all=False): ...\ndef emit_env(o=sys.__stdout__, d=init(), all=False): ...\ndef exported_keys(d): ...\ndef exported_vars(d): ...\ndef emit_func(func, o=sys.__stdout__, d=init()): ...\ndef emit_func_python(func, o=sys.__stdout__, d=init()): ...\ndef update_data(d): ...\ndef build_dependencies(key, keys, shelldeps, varflagsexcl, d): ...\ndef generate_dependencies(d): ...\ndef inherits_class(klass, d): ...\n", "repository": "thiagoss/tizen-distro", "test_name": "test_rename", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001883.py"} {"focal_file": "bitbake/lib/bb/data.py", "focal_class": null, "focal_method": "keys", "tests": "import unittest\n\nclass Test_keys(unittest.TestCase):\n def test_keys(self):\n keys = self.d.keys()\n self.assertEqual(keys, ['value_of_foo', 'foo', 'bar'])\n", "method_code": "def keys(d):\n \"\"\"Return a list of keys in d\"\"\"\n return d.keys()", "context": "def keys(d): ...\ndef init(): ...\ndef init_db(parent=None): ...\ndef createCopy(source): ...\ndef initVar(var, d): ...\ndef setVar(var, value, d): ...\ndef getVar(var, d, exp=0): ...\ndef renameVar(key, newkey, d): ...\ndef delVar(var, d): ...\ndef appendVar(var, value, d): ...\ndef setVarFlag(var, flag, flagvalue, d): ...\ndef getVarFlag(var, flag, d): ...\ndef delVarFlag(var, flag, d): ...\ndef setVarFlags(var, flags, d): ...\ndef getVarFlags(var, d): ...\ndef delVarFlags(var, d): ...\ndef keys(d): ...\ndef expand(s, d, varname=None): ...\ndef expandKeys(alterdata, readdata=None): ...\ndef inheritFromOS(d, savedenv, permitted): ...\ndef emit_var(var, o=sys.__stdout__, d=init(), all=False): ...\ndef emit_env(o=sys.__stdout__, d=init(), all=False): ...\ndef exported_keys(d): ...\ndef exported_vars(d): ...\ndef emit_func(func, o=sys.__stdout__, d=init()): ...\ndef emit_func_python(func, o=sys.__stdout__, d=init()): ...\ndef update_data(d): ...\ndef build_dependencies(key, keys, shelldeps, varflagsexcl, d): ...\ndef generate_dependencies(d): ...\ndef inherits_class(klass, d): ...\n", "repository": "thiagoss/tizen-distro", "test_name": "test_keys", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001884.py"} {"focal_file": "bitbake/lib/bb/data.py", "focal_class": null, "focal_method": "appendVar", "tests": "import unittest\n\nclass Test_appendVar(unittest.TestCase):\n def test_append(self):\n self.d.setVar('TEST', '${VAL}')\n self.d.appendVar('TEST', ':${BAR}')\n self.assertEqual(self.d.getVar('TEST', True), 'val:bar')\n", "method_code": "def appendVar(var, value, d):\n \"\"\"Append additional value to a variable\"\"\"\n d.appendVar(var, value)", "context": "def appendVar(var, value, d): ...\ndef init(): ...\ndef init_db(parent=None): ...\ndef createCopy(source): ...\ndef initVar(var, d): ...\ndef setVar(var, value, d): ...\ndef getVar(var, d, exp=0): ...\ndef renameVar(key, newkey, d): ...\ndef delVar(var, d): ...\ndef appendVar(var, value, d): ...\ndef setVarFlag(var, flag, flagvalue, d): ...\ndef getVarFlag(var, flag, d): ...\ndef delVarFlag(var, flag, d): ...\ndef setVarFlags(var, flags, d): ...\ndef getVarFlags(var, d): ...\ndef delVarFlags(var, d): ...\ndef keys(d): ...\ndef expand(s, d, varname=None): ...\ndef expandKeys(alterdata, readdata=None): ...\ndef inheritFromOS(d, savedenv, permitted): ...\ndef emit_var(var, o=sys.__stdout__, d=init(), all=False): ...\ndef emit_env(o=sys.__stdout__, d=init(), all=False): ...\ndef exported_keys(d): ...\ndef exported_vars(d): ...\ndef emit_func(func, o=sys.__stdout__, d=init()): ...\ndef emit_func_python(func, o=sys.__stdout__, d=init()): ...\ndef update_data(d): ...\ndef build_dependencies(key, keys, shelldeps, varflagsexcl, d): ...\ndef generate_dependencies(d): ...\ndef inherits_class(klass, d): ...\n", "repository": "thiagoss/tizen-distro", "test_name": "test_append", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001885.py"} {"focal_file": "meta/lib/oe/utils.py", "focal_class": null, "focal_method": "trim_version", "tests": "import unittest\n\nclass Test_trim_version(unittest.TestCase):\n def test_version_exception(self):\n with self.assertRaises(TypeError):\n trim_version(None, 2)\n with self.assertRaises(TypeError):\n trim_version((1, 2, 3), 2)\n", "method_code": "def trim_version(version, num_parts=2):\n \"\"\"\n Return just the first of , split by periods. For\n example, trim_version(\"1.2.3\", 2) will return \"1.2\".\n \"\"\"\n if type(version) is not str:\n raise TypeError('Version should be a string')\n if num_parts < 1:\n raise ValueError('Cannot split to parts < 1')\n parts = version.split('.')\n trimmed = '.'.join(parts[:num_parts])\n return trimmed", "context": "def trim_version(version, num_parts=2): ...\ndef read_file(filename): ...\ndef ifelse(condition, iftrue=True, iffalse=False): ...\ndef conditional(variable, checkvalue, truevalue, falsevalue, d): ...\ndef less_or_equal(variable, checkvalue, truevalue, falsevalue, d): ...\ndef version_less_or_equal(variable, checkvalue, truevalue, falsevalue, d): ...\ndef both_contain(variable1, variable2, checkvalue, d): ...\ndef prune_suffix(var, suffixes, d): ...\ndef str_filter(f, str, d): ...\ndef str_filter_out(f, str, d): ...\ndef param_bool(cfg, field, dflt=None): ...\ndef inherits(d, *classes): ...\ndef features_backfill(var, d): ...\ndef packages_filter_out_system(d): ...\ndef getstatusoutput(cmd): ...\ndef trim_version(version, num_parts=2): ...\ndef cpu_count(): ...\ndef execute_pre_post_process(d, cmds): ...\ndef multiprocess_exec(commands, function): ...\n", "repository": "thiagoss/tizen-distro", "test_name": "test_version_exception", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001886.py"} {"focal_file": "scripts/pybootchartgui/pybootchartgui/process_tree.py", "focal_class": null, "focal_method": "merge_logger", "tests": "import unittest\n\nclass Test_merge_logger(unittest.TestCase):\n def testMergeLogger(self):\n self.processtree.merge_logger(self.processtree.process_tree, 'bootchartd', None, False)\n process_tree = self.processtree.process_tree\n self.checkAgainstJavaExtract(self.mk_fname('extract.processtree.2.log'), process_tree)\n", "method_code": " def merge_logger(self, process_subtree, logger_proc, monitored_app, app_tree):\n \"\"\"Merges the logger's process subtree. The logger will typically\n spawn lots of sleep and cat processes, thus polluting the\n process tree.\n \n \"\"\"\n num_removed = 0\n for p in process_subtree:\n is_app_tree = app_tree\n if logger_proc == p.cmd and (not app_tree):\n is_app_tree = True\n num_removed += self.merge_logger(p.child_list, logger_proc, monitored_app, is_app_tree)\n continue\n if app_tree and monitored_app != None and (monitored_app == p.cmd):\n is_app_tree = False\n if is_app_tree:\n for child in p.child_list:\n self.merge_processes(p, child)\n num_removed += 1\n p.child_list = []\n else:\n num_removed += self.merge_logger(p.child_list, logger_proc, monitored_app, is_app_tree)\n return num_removed\n ", "context": "class ProcessTree():\n def merge_logger(self, process_subtree, logger_proc, monitored_app, app_tree): ...\n def __init__(self, writer, kernel, psstats, sample_period, monitoredApp, prune, idle, taskstats, accurate_parentage, for_testing=False): ...\n def build(self): ...\n def sort(self, process_subtree): ...\n def num_nodes(self, process_list): ...\n def get_start_time(self, process_subtree): ...\n def get_end_time(self, process_subtree): ...\n def get_max_pid(self, process_subtree): ...\n def update_ppids_for_daemons(self, process_list): ...\n def prune(self, process_subtree, parent): ...\n def merge_exploders(self, process_subtree, processes): ...\n def merge_siblings(self, process_subtree): ...\n def merge_runs(self, process_subtree): ...\n def merge_processes(self, p1, p2): ...\n\n self.writer = writer\n self.process_tree = []\n self.taskstats = taskstats\n self.process_list = sorted(process_list, key=lambda p: p.pid)\n self.sample_period = sample_period\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.idle = idle\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.num_proc = self.num_nodes(self.process_tree)\n\n LOGGER_PROC = 'bootchart-colle'\n EXPLODER_PROCESSES = set(['hwup'])\n", "repository": "thiagoss/tizen-distro", "test_name": "testMergeLogger", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001887.py"} {"focal_file": "scripts/pybootchartgui/pybootchartgui/process_tree.py", "focal_class": null, "focal_method": "merge_exploders", "tests": "import unittest\n\nclass Test_merge_exploders(unittest.TestCase):\n def testMergeExploders(self):\n self.processtree.merge_logger(self.processtree.process_tree, 'bootchartd', None, False)\n self.processtree.prune(self.processtree.process_tree, None)\n self.processtree.merge_exploders(self.processtree.process_tree, set(['hwup']))\n process_tree = self.processtree.process_tree\n self.checkAgainstJavaExtract(self.mk_fname('extract.processtree.3c.log'), process_tree)\n", "method_code": " def merge_exploders(self, process_subtree, processes):\n \"\"\"Merges specific process subtrees (used for processes which usually\n spawn huge meaningless process trees).\n \n \"\"\"\n num_removed = 0\n for p in process_subtree:\n if processes in processes and len(p.child_list) > 0:\n subtreemap = self.getProcessMap(p.child_list)\n for child in subtreemap.values():\n self.merge_processes(p, child)\n num_removed += len(subtreemap)\n p.child_list = []\n p.cmd += ' (+)'\n else:\n num_removed += self.merge_exploders(p.child_list, processes)\n return num_removed\n ", "context": "class ProcessTree():\n def merge_exploders(self, process_subtree, processes): ...\n def __init__(self, writer, kernel, psstats, sample_period, monitoredApp, prune, idle, taskstats, accurate_parentage, for_testing=False): ...\n def build(self): ...\n def sort(self, process_subtree): ...\n def num_nodes(self, process_list): ...\n def get_start_time(self, process_subtree): ...\n def get_end_time(self, process_subtree): ...\n def get_max_pid(self, process_subtree): ...\n def update_ppids_for_daemons(self, process_list): ...\n def prune(self, process_subtree, parent): ...\n def merge_logger(self, process_subtree, logger_proc, monitored_app, app_tree): ...\n def merge_siblings(self, process_subtree): ...\n def merge_runs(self, process_subtree): ...\n def merge_processes(self, p1, p2): ...\n\n self.writer = writer\n self.process_tree = []\n self.taskstats = taskstats\n self.process_list = sorted(process_list, key=lambda p: p.pid)\n self.sample_period = sample_period\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.idle = idle\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.num_proc = self.num_nodes(self.process_tree)\n\n LOGGER_PROC = 'bootchart-colle'\n EXPLODER_PROCESSES = set(['hwup'])\n", "repository": "thiagoss/tizen-distro", "test_name": "testMergeExploders", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001888.py"} {"focal_file": "scripts/pybootchartgui/pybootchartgui/process_tree.py", "focal_class": null, "focal_method": "merge_siblings", "tests": "import unittest\n\nclass Test_merge_siblings(unittest.TestCase):\n def testMergeSiblings(self):\n self.processtree.merge_logger(self.processtree.process_tree, 'bootchartd', None, False)\n self.processtree.prune(self.processtree.process_tree, None)\n self.processtree.merge_exploders(self.processtree.process_tree, set(['hwup']))\n self.processtree.merge_siblings(self.processtree.process_tree)\n process_tree = self.processtree.process_tree\n self.checkAgainstJavaExtract(self.mk_fname('extract.processtree.3d.log'), process_tree)\n", "method_code": " def merge_siblings(self, process_subtree):\n \"\"\"Merges thread processes. Sibling processes with the same command\n line are merged together.\n \n \"\"\"\n num_removed = 0\n idx = 0\n while idx < len(process_subtree) - 1:\n p = process_subtree[idx]\n nextp = process_subtree[idx + 1]\n if nextp.cmd == p.cmd:\n process_subtree.pop(idx + 1)\n idx -= 1\n num_removed += 1\n p.child_list.extend(nextp.child_list)\n self.merge_processes(p, nextp)\n num_removed += self.merge_siblings(p.child_list)\n idx += 1\n if len(process_subtree) > 0:\n p = process_subtree[-1]\n num_removed += self.merge_siblings(p.child_list)\n return num_removed\n ", "context": "class ProcessTree():\n def merge_siblings(self, process_subtree): ...\n def __init__(self, writer, kernel, psstats, sample_period, monitoredApp, prune, idle, taskstats, accurate_parentage, for_testing=False): ...\n def build(self): ...\n def sort(self, process_subtree): ...\n def num_nodes(self, process_list): ...\n def get_start_time(self, process_subtree): ...\n def get_end_time(self, process_subtree): ...\n def get_max_pid(self, process_subtree): ...\n def update_ppids_for_daemons(self, process_list): ...\n def prune(self, process_subtree, parent): ...\n def merge_logger(self, process_subtree, logger_proc, monitored_app, app_tree): ...\n def merge_exploders(self, process_subtree, processes): ...\n def merge_runs(self, process_subtree): ...\n def merge_processes(self, p1, p2): ...\n\n self.writer = writer\n self.process_tree = []\n self.taskstats = taskstats\n self.process_list = sorted(process_list, key=lambda p: p.pid)\n self.sample_period = sample_period\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.idle = idle\n self.start_time = self.get_start_time(self.process_tree)\n self.end_time = self.get_end_time(self.process_tree)\n self.duration = self.end_time - self.start_time\n self.num_proc = self.num_nodes(self.process_tree)\n\n LOGGER_PROC = 'bootchart-colle'\n EXPLODER_PROCESSES = set(['hwup'])\n", "repository": "thiagoss/tizen-distro", "test_name": "testMergeSiblings", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001889.py"} {"focal_file": "snmpagent_unity/access.py", "focal_class": null, "focal_method": "_validate_params", "tests": "import unittest\n\nclass Test_validate_params(unittest.TestCase):\n @ddt.data({'security_level': enums.SecurityLevel.NO_AUTH_NO_PRIV}, {'security_level': enums.SecurityLevel.NO_AUTH_NO_PRIV, 'auth_protocol': enums.AuthProtocol.MD5, 'priv_protocol': enums.PrivProtocol.AES})\n def test_validate_params_no_auth_priv(self, param_dict):\n level, auth_p, auth_k, priv_p, priv_k = access._validate_params(**param_dict)\n self.assertEqual(level, enums.SecurityLevel.NO_AUTH_NO_PRIV)\n self.assertIsNone(auth_p)\n self.assertIsNone(auth_k)\n self.assertIsNone(priv_p)\n self.assertIsNone(priv_k)\n\n @ddt.data({'security_level': enums.SecurityLevel.AUTH_PRIV, 'auth_protocol': enums.AuthProtocol.MD5, 'auth_key': 'key123', 'priv_protocol': enums.PrivProtocol.AES, 'priv_key': 'key456'})\n def test_validate_params_auth_priv(self, param_dict):\n level, auth_p, auth_k, priv_p, priv_k = access._validate_params(**param_dict)\n self.assertEqual(level, enums.SecurityLevel.AUTH_PRIV)\n self.assertEqual(auth_p, enums.AuthProtocol.MD5)\n self.assertEqual(auth_k, 'key123')\n self.assertEqual(priv_p, enums.PrivProtocol.AES)\n self.assertEqual(priv_k, 'key456')\n\n @ddt.data({'security_level': enums.SecurityLevel.AUTH_NO_PRIV, 'auth_protocol': enums.AuthProtocol.MD5, 'auth_key': 'key123', 'priv_protocol': enums.PrivProtocol.AES, 'priv_key': 'key456'})\n def test_validate_params_auth_no_priv(self, param_dict):\n level, auth_p, auth_k, priv_p, priv_k = access._validate_params(**param_dict)\n self.assertEqual(level, enums.SecurityLevel.AUTH_NO_PRIV)\n self.assertEqual(auth_p, enums.AuthProtocol.MD5)\n self.assertEqual(auth_k, 'key123')\n self.assertIsNone(priv_p)\n self.assertIsNone(priv_k)\n", "method_code": "def _validate_params(security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None):\n level = utils.enum(enums.SecurityLevel, security_level)\n if level is None:\n raise snmp_ex.UserConfigError('Not supported security level: {}'.format(security_level))\n auth_p, auth_k = (None, None)\n priv_p, priv_k = (None, None)\n if level != enums.SecurityLevel.NO_AUTH_NO_PRIV:\n auth_p = utils.enum(enums.AuthProtocol, auth_protocol)\n if auth_p is None:\n raise snmp_ex.UserConfigError('Not supported auth protocol: {}'.format(auth_protocol))\n auth_k = auth_key\n if level == enums.SecurityLevel.AUTH_PRIV:\n priv_p = utils.enum(enums.PrivProtocol, priv_protocol)\n if priv_p is None:\n raise snmp_ex.UserConfigError('Not supported priv protocol: {}'.format(priv_protocol))\n priv_k = priv_key\n return (level, auth_p, auth_k, priv_p, priv_k)", "context": "def _validate_params(security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\ndef _validate_params(security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\ndef get_access_data_path(): ...\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001890.py"} {"focal_file": "snmpagent_unity/access.py", "focal_class": null, "focal_method": "add_v3_user", "tests": "import unittest\n\nclass Test_add_v3_user(unittest.TestCase):\n @patches.user_v3_entry\n def test_add_v3_user(self, user_v3_entry):\n self.access.user_conf.entries = {}\n self.access.add_v3_user('user_1', enums.SecurityLevel.AUTH_PRIV, auth_protocol=enums.AuthProtocol.MD5, auth_key='key123', priv_protocol=enums.PrivProtocol.AES, priv_key='key456')\n user_v3_entry.assert_called_with('user_1', None, enums.SecurityLevel.AUTH_PRIV, enums.AuthProtocol.MD5, 'key123', enums.PrivProtocol.AES, 'key456')\n self.assertIn('user_1', self.access.user_conf.entries)\n", "method_code": " def add_v3_user(self, name, security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None):\n if name in self.user_conf.entries:\n raise snmp_ex.UserExistingError(\"The user: '{}' already exists.\".format(name))\n level, auth_p, auth_k, priv_p, priv_k = _validate_params(security_level, auth_protocol, auth_key, priv_protocol, priv_key)\n self.user_conf.entries[name] = config.UserV3ConfigEntry(name, None, level, auth_p, auth_k, priv_p, priv_k)\n self.user_conf.save()\n LOG.info(\"Added user '{}' successfully.\".format(name))\n ", "context": "class Access(object):\n def add_v3_user(self, name, security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def __init__(self): ...\n def add_v2_user(self, name): ...\n def delete_v3_user(self, name): ...\n def delete_v2_user(self, name): ...\n def update_v3_user(self, name, security_level=None, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def list_users(self): ...\n\n self.user_conf = config.UserConfig(get_access_data_path())\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001891.py"} {"focal_file": "snmpagent_unity/access.py", "focal_class": null, "focal_method": "add_v2_user", "tests": "import unittest\n\nclass Test_add_v2_user(unittest.TestCase):\n @patches.user_v2_entry\n def test_add_v2_user(self, user_v2_entry):\n self.access.user_conf.entries = {}\n self.access.add_v2_user('user_1')\n user_v2_entry.assert_called_with('user_1', 'user_1')\n self.assertIn('user_1', self.access.user_conf.entries)\n", "method_code": " def add_v2_user(self, name):\n if name in self.user_conf.entries:\n raise snmp_ex.UserExistingError(\"The user: '{}' already exists.\".format(name))\n self.user_conf.entries[name] = config.UserV2ConfigEntry(name, name)\n self.user_conf.save()\n LOG.info(\"Added user '{}' successfully.\".format(name))\n ", "context": "class Access(object):\n def add_v2_user(self, name): ...\n def __init__(self): ...\n def add_v3_user(self, name, security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def delete_v3_user(self, name): ...\n def delete_v2_user(self, name): ...\n def update_v3_user(self, name, security_level=None, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def list_users(self): ...\n\n self.user_conf = config.UserConfig(get_access_data_path())\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001892.py"} {"focal_file": "snmpagent_unity/access.py", "focal_class": null, "focal_method": "delete_v3_user", "tests": "import unittest\n\nclass Test_delete_v3_user(unittest.TestCase):\n def test_delete_v3_user(self):\n name = 'user_1'\n self.access.user_conf.entries = {name: name}\n self.access.delete_v3_user(name)\n self.assertNotIn(name, self.access.user_conf.entries)\n", "method_code": " def delete_v3_user(self, name):\n if name not in self.user_conf.entries:\n raise snmp_ex.UserNotExistsError(\"User '{}' was already deleted.\".format(name))\n del self.user_conf.entries[name]\n self.user_conf.save()\n LOG.info(\"Deleted user '{}' successfully.\".format(name))\n ", "context": "class Access(object):\n def delete_v3_user(self, name): ...\n def __init__(self): ...\n def add_v3_user(self, name, security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def add_v2_user(self, name): ...\n def delete_v2_user(self, name): ...\n def update_v3_user(self, name, security_level=None, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def list_users(self): ...\n\n self.user_conf = config.UserConfig(get_access_data_path())\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_delete_v3_user", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001893.py"} {"focal_file": "snmpagent_unity/access.py", "focal_class": null, "focal_method": "delete_v2_user", "tests": "import unittest\n\nclass Test_delete_v2_user(unittest.TestCase):\n def test_delete_v2_user(self):\n name = 'user_1'\n self.access.user_conf.entries = {name: name}\n self.access.delete_v2_user(name)\n self.assertNotIn(name, self.access.user_conf.entries)\n", "method_code": " def delete_v2_user(self, name):\n if name not in self.user_conf.entries:\n raise snmp_ex.UserNotExistsError(\"User '{}' was already deleted.\".format(name))\n del self.user_conf.entries[name]\n self.user_conf.save()\n LOG.info(\"Deleted user '{}' successfully.\".format(name))\n ", "context": "class Access(object):\n def delete_v2_user(self, name): ...\n def __init__(self): ...\n def add_v3_user(self, name, security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def add_v2_user(self, name): ...\n def delete_v3_user(self, name): ...\n def update_v3_user(self, name, security_level=None, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def list_users(self): ...\n\n self.user_conf = config.UserConfig(get_access_data_path())\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_delete_v2_user", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001894.py"} {"focal_file": "snmpagent_unity/access.py", "focal_class": null, "focal_method": "update_v3_user", "tests": "import unittest\n\nclass Test_update_v3_user(unittest.TestCase):\n def test_update_v3_user(self):\n name = 'user_1'\n old_user = config.UserV3ConfigEntry(name, None, enums.SecurityLevel.AUTH_PRIV, enums.AuthProtocol.SHA, 'key123', enums.PrivProtocol.AES, 'key456')\n self.access.user_conf.entries = {name: old_user}\n self.access.update_v3_user(name, security_level=enums.SecurityLevel.AUTH_PRIV, auth_protocol=enums.AuthProtocol.SHA, auth_key='key123', priv_key='key789', priv_protocol=enums.PrivProtocol.DES)\n new_user = self.access.user_conf.entries[name]\n self.assertEqual(name, new_user.name)\n self.assertEqual(enums.SecurityLevel.AUTH_PRIV, new_user.security_level)\n self.assertEqual(enums.AuthProtocol.SHA, new_user.auth_protocol)\n self.assertEqual('key123', new_user.auth_key.raw)\n self.assertEqual(enums.PrivProtocol.DES, new_user.priv_protocol)\n self.assertEqual('key789', new_user.priv_key.raw)\n self.access.user_conf.save.assert_called_once()\n\n def test_update_v3_user_no_private(self):\n name = 'user_1'\n old_user = config.UserV3ConfigEntry(name, enums.SecurityLevel.AUTH_PRIV, enums.SecurityLevel.AUTH_PRIV, enums.AuthProtocol.SHA, 'key123', enums.PrivProtocol.AES, 'key456')\n self.access.user_conf.entries = {name: old_user}\n self.access.update_v3_user(name, security_level=enums.SecurityLevel.AUTH_NO_PRIV, auth_protocol=enums.AuthProtocol.SHA, auth_key='key123')\n new_user = self.access.user_conf.entries[name]\n self.assertIsNone(new_user.priv_protocol)\n self.assertIsNone(new_user.priv_key.raw)\n", "method_code": " def update_v3_user(self, name, security_level=None, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None):\n if name not in self.user_conf.entries:\n raise snmp_ex.UserNotExistsError(\"Could not update nonexistent user '{}'.\".format(name))\n old = self.user_conf.entries[name]\n level, auth_p, auth_k, priv_p, priv_k = _validate_params(security_level, auth_protocol, auth_key, priv_protocol, priv_key)\n if old.auth_protocol != auth_p:\n raise snmp_ex.UserInvalidProtocolError(\"'{}' does not match auth with '{}'.\".format(auth_p, old.auth_protocol))\n if old.auth_key.raw != auth_k:\n raise snmp_ex.UserInvalidPasswordError('Incorrect password supplied.')\n self.user_conf.entries[name] = config.UserV3ConfigEntry(name, None, level, auth_p, auth_k, priv_p, priv_k)\n self.user_conf.save()\n LOG.info(\"Updated user '{}' successfully.\".format(name))\n ", "context": "class Access(object):\n def update_v3_user(self, name, security_level=None, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def __init__(self): ...\n def add_v3_user(self, name, security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def add_v2_user(self, name): ...\n def delete_v3_user(self, name): ...\n def delete_v2_user(self, name): ...\n def list_users(self): ...\n\n self.user_conf = config.UserConfig(get_access_data_path())\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_update_v3_user", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001895.py"} {"focal_file": "snmpagent_unity/access.py", "focal_class": null, "focal_method": "list_users", "tests": "import unittest\n\nclass Test_list_users(unittest.TestCase):\n def test_list_users(self):\n users = collections.OrderedDict()\n users['user_1'] = config.UserV2ConfigEntry('user_1', enums.Community.PUBLIC)\n users['user_2'] = config.UserV2ConfigEntry('user_2', enums.Community.PUBLIC)\n users['user_3'] = config.UserV3ConfigEntry('user_3', '-', enums.SecurityLevel.AUTH_PRIV, enums.AuthProtocol.MD5, 'key123', enums.PrivProtocol.AES, 'key456')\n users['user_4'] = config.UserV3ConfigEntry('user_4', '-', enums.SecurityLevel.AUTH_NO_PRIV, enums.AuthProtocol.SHA, 'key123', None, None)\n self.access.user_conf.entries = users\n expected = 'SNMP Version 2 Community Access:\\nuser_1\\n Version: SNMP Version 2c\\n Community: user_1\\nuser_2\\n Version: SNMP Version 2c\\n Community: user_2\\n\\nSNMP Version 3 Users:\\nuser_3\\n Version: SNMP Version 3\\n Security Level: Authentication and Privacy\\n Auth Protocol: MD5\\n Auth Key: ******\\n Privacy Protocol: AES\\n Privacy Key: ******\\nuser_4\\n Version: SNMP Version 3\\n Security Level: Authentication\\n Auth Protocol: SHA\\n Auth Key: ******\\n Privacy Protocol: -\\n Privacy Key: -\\n'\n with patches.stdout() as out:\n self.access.list_users()\n output = out.getvalue()\n self.assertEqual(output, expected)\n", "method_code": " def list_users(self):\n v2, v3 = config.UserConfig.split_v2_v3(self.user_conf.entries)\n print('\\n'.join([config.USER_V2_SHOW_HEAD] + [str(e) for e in v2] + ['\\n' + config.USER_V3_SHOW_HEAD] + [str(e) for e in v3]))\n ", "context": "class Access(object):\n def list_users(self): ...\n def __init__(self): ...\n def add_v3_user(self, name, security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n def add_v2_user(self, name): ...\n def delete_v3_user(self, name): ...\n def delete_v2_user(self, name): ...\n def update_v3_user(self, name, security_level=None, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\n\n self.user_conf = config.UserConfig(get_access_data_path())\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_list_users", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001896.py"} {"focal_file": "snmpagent_unity/access.py", "focal_class": null, "focal_method": "get_access_data_path", "tests": "import unittest\n\nclass Test_get_access_data_path(unittest.TestCase):\n def test_get_access_path(self):\n with mock.patch('os.path.expanduser') as my_path:\n my_path.return_value = os.path.join(os.path.join(os.path.dirname(__file__), 'test_data', 'configs'))\n access_path = access.get_access_data_path()\n self.assertTrue('access.db' in access_path)\n\n def test_get_access_path_create_dir(self):\n temp_path = os.path.join(tempfile.gettempdir(), '.{}'.format(snmpagent_unity.SERVICE_NAME))\n if os.path.exists(os.path.join(temp_path, 'access.db')):\n os.remove(os.path.join(temp_path, 'access.db'))\n if os.path.isdir(temp_path):\n os.removedirs(temp_path)\n with mock.patch('os.path.expanduser') as my_path:\n my_path.return_value = temp_path\n access_path = access.get_access_data_path()\n self.assertTrue(temp_path in access_path)\n", "method_code": "def get_access_data_path():\n \"\"\"Returns the access data location.\n\n The data location is fixed:\n on Windows, it's %USERPROFILE%\\\\.snmpagent\\x07ccess.db\n on Linux, it's %HOME%/.snmpagent\\x07ccess.db\n\n \"\"\"\n data_folder = os.path.expanduser('~{}.{}'.format(os.path.sep, snmpagent_unity.SERVICE_NAME))\n access_file = os.path.join(data_folder, 'access.db')\n if not os.path.isdir(data_folder):\n os.mkdir(data_folder)\n LOG.info(\"Created '{}' for access data persistence.\".format(data_folder))\n if not os.path.exists(access_file):\n with open(access_file, 'w'):\n LOG.debug(\"Created file '{}' for storing access data\".format(access_file))\n return access_file", "context": "def get_access_data_path(): ...\ndef _validate_params(security_level, auth_protocol=None, auth_key=None, priv_protocol=None, priv_key=None): ...\ndef get_access_data_path(): ...\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_access_path", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001897.py"} {"focal_file": "snmpagent_unity/cipher.py", "focal_class": null, "focal_method": "is_encrypted", "tests": "import unittest\n\nclass Test_is_encrypted(unittest.TestCase):\n def test_is_encrypted_true(self):\n data = 'abc\\x06'\n self.assertTrue(cipher.is_encrypted(data))\n\n def test_is_encrypted_false(self):\n data = 'abc'\n self.assertFalse(cipher.is_encrypted(data))\n", "method_code": "def is_encrypted(data):\n return data is not None and data.endswith(__ENCRYPTED_FLAG)", "context": "def is_encrypted(data): ...\ndef is_encrypted(data): ...\ndef encrypt(data): ...\ndef decrypt(data): ...\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_is_encrypted_true", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001898.py"} {"focal_file": "snmpagent_unity/cipher.py", "focal_class": null, "focal_method": "decrypt", "tests": "import unittest\n\nclass Test_decrypt(unittest.TestCase):\n @ddt.data('abc', 'abcdefghijkl', 'abcdefghijklmn')\n def test_encrypt_decrypt(self, data):\n encrypted = cipher.encrypt(data)\n self.assertNotEqual(encrypted, data)\n decrypted = cipher.decrypt(encrypted)\n self.assertEqual(decrypted, data)\n", "method_code": "def decrypt(data):\n plain = data\n if is_encrypted(data):\n cipher = AES.new(__I_AM_SAFE, __MODE, __I_AM_SAFE)\n data = data.rstrip(__ENCRYPTED_FLAG)\n plain = cipher.decrypt(binascii.a2b_hex(data))\n plain = plain.rstrip(b'\\x00').decode('utf-8')\n return plain", "context": "def decrypt(data): ...\ndef is_encrypted(data): ...\ndef encrypt(data): ...\ndef decrypt(data): ...\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001899.py"} {"focal_file": "snmpagent_unity/utils.py", "focal_class": null, "focal_method": "setup_log", "tests": "import unittest\n\nclass Test_setup_log(unittest.TestCase):\n def test_setup_log(self):\n utils.setup_log(tempfile.gettempdir() + '/logfile.log', level='debug')\n", "method_code": "def setup_log(log_file_path='snmpagent-unity.log', level=None, log_to_stdout=True, max_bytes=104857600, max_file_count=5):\n if level:\n level = getattr(logging, level.upper(), None)\n else:\n level = logging.INFO\n fmt_str = '%(asctime)-15s %(name)-12s %(threadName)s %(levelname)-8s %(message)s'\n fmt = logging.Formatter(fmt_str)\n root = logging.getLogger()\n root.setLevel(level)\n if log_to_stdout:\n console = logging.StreamHandler()\n console.setLevel(level)\n console.setFormatter(fmt)\n root.addHandler(console)\n if log_file_path:\n file_handler = handlers.RotatingFileHandler(filename=log_file_path, maxBytes=0 if not max_bytes else int(max_bytes), backupCount=0 if not max_file_count else int(max_file_count))\n file_handler.setLevel(level)\n file_handler.setFormatter(fmt)\n root.addHandler(file_handler)", "context": "def setup_log(log_file_path='snmpagent-unity.log', level=None, log_to_stdout=True, max_bytes=104857600, max_file_count=5): ...\ndef enum(enum_clz, value): ...\ndef setup_log(log_file_path='snmpagent-unity.log', level=None, log_to_stdout=True, max_bytes=104857600, max_file_count=5): ...\ndef log_command_exception(cmd): ...\ndef log_trace(excType, excValue, traceback): ...\ndef disable_urllib3_warnings(): ...\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_setup_log", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001900.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_agent_version", "tests": "import unittest\n\nclass Test_get_agent_version(unittest.TestCase):\n def test_get_agent_version(self):\n self.assertEqual(snmpagent_unity.__version__, self.client.get_agent_version())\n", "method_code": " def get_agent_version(self):\n return snmpagent_unity.__version__\n ", "context": "class UnityClient(object):\n @to_string\n def get_agent_version(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_agent_version", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001901.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_mib_version", "tests": "import unittest\n\nclass Test_get_mib_version(unittest.TestCase):\n def test_get_mib_version(self):\n self.assertEqual('1.0', self.client.get_mib_version())\n", "method_code": " def get_mib_version(self):\n return '1.0'\n ", "context": "class UnityClient(object):\n @to_string\n def get_mib_version(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_mib_version", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001902.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_manufacturer", "tests": "import unittest\n\nclass Test_get_manufacturer(unittest.TestCase):\n def test_get_manufacturer(self):\n self.assertEqual('DellEMC', self.client.get_manufacturer())\n", "method_code": " def get_manufacturer(self):\n return 'DellEMC'\n ", "context": "class UnityClient(object):\n @to_string\n def get_manufacturer(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_manufacturer", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001903.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_serial_number", "tests": "import unittest\n\nclass Test_get_serial_number(unittest.TestCase):\n def test_get_serial_number(self):\n self.assertEqual('FNM00150600267', self.client.get_serial_number())\n", "method_code": " def get_serial_number(self):\n return self.unity_system.serial_number\n ", "context": "class UnityClient(object):\n @to_string\n def get_serial_number(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_serial_number", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001904.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_operation_environment_version", "tests": "import unittest\n\nclass Test_get_operation_environment_version(unittest.TestCase):\n def test_get_operation_environment_version(self):\n self.assertEqual('4.2.0', self.client.get_operation_environment_version())\n", "method_code": " def get_operation_environment_version(self):\n return self.unity_system.system_version\n ", "context": "class UnityClient(object):\n @to_string\n def get_operation_environment_version(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_operation_environment_version", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001905.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_mgmt_ip", "tests": "import unittest\n\nclass Test_get_mgmt_ip(unittest.TestCase):\n def test_get_mgmt_ip(self):\n self.assertEqual('10.10.10.10, 10.10.10.11', self.client.get_mgmt_ip())\n", "method_code": " def get_mgmt_ip(self):\n return ', '.join((x.ip_address for x in self.unity_system.get_mgmt_interface()))\n ", "context": "class UnityClient(object):\n @to_string\n def get_mgmt_ip(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_mgmt_ip", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001906.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_current_power", "tests": "import unittest\n\nclass Test_get_current_power(unittest.TestCase):\n def test_get_current_power(self):\n self.assertEqual('542', self.client.get_current_power())\n", "method_code": " def get_current_power(self):\n self.unity_system.update()\n return self.unity_system.current_power\n ", "context": "class UnityClient(object):\n @to_string\n def get_current_power(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_current_power", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001907.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_avg_power", "tests": "import unittest\n\nclass Test_get_avg_power(unittest.TestCase):\n def test_get_avg_power(self):\n self.assertEqual('540', self.client.get_avg_power())\n", "method_code": " def get_avg_power(self):\n self.unity_system.update()\n return self.unity_system.avg_power\n ", "context": "class UnityClient(object):\n @to_string\n def get_avg_power(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_avg_power", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001908.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_number_of_sp", "tests": "import unittest\n\nclass Test_get_number_of_sp(unittest.TestCase):\n def test_get_number_of_sp(self):\n self.assertEqual(3, self.client.get_number_of_sp())\n", "method_code": " def get_number_of_sp(self):\n return len(self.get_sps())\n ", "context": "class UnityClient(object):\n @to_number\n def get_number_of_sp(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_number_of_sp", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001909.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_number_of_enclosure", "tests": "import unittest\n\nclass Test_get_number_of_enclosure(unittest.TestCase):\n def test_get_number_of_enclosure(self):\n self.assertEqual(4, self.client.get_number_of_enclosure())\n", "method_code": " def get_number_of_enclosure(self):\n return len(self.get_enclosures())\n ", "context": "class UnityClient(object):\n @to_number\n def get_number_of_enclosure(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_number_of_enclosure", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001910.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_number_of_power_supply", "tests": "import unittest\n\nclass Test_get_number_of_power_supply(unittest.TestCase):\n def test_get_number_of_power_supply(self):\n self.assertEqual(2, self.client.get_number_of_power_supply())\n", "method_code": " def get_number_of_power_supply(self):\n return len(self.get_power_supplies())\n ", "context": "class UnityClient(object):\n @to_number\n def get_number_of_power_supply(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_number_of_power_supply", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001911.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_number_of_fan", "tests": "import unittest\n\nclass Test_get_number_of_fan(unittest.TestCase):\n def test_get_number_of_fan(self):\n self.assertEqual(4, self.client.get_number_of_fan())\n", "method_code": " def get_number_of_fan(self):\n return len(self.get_fans())\n ", "context": "class UnityClient(object):\n @to_number\n def get_number_of_fan(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_number_of_fan", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001912.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_number_of_disk", "tests": "import unittest\n\nclass Test_get_number_of_disk(unittest.TestCase):\n def test_get_number_of_disk(self):\n self.assertEqual(4, self.client.get_number_of_disk())\n", "method_code": " def get_number_of_disk(self):\n return len(self.get_disks())\n ", "context": "class UnityClient(object):\n @to_number\n def get_number_of_disk(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_number_of_disk", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001913.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_number_of_frontend_port", "tests": "import unittest\n\nclass Test_get_number_of_frontend_port(unittest.TestCase):\n def test_get_number_of_frontend_port(self):\n self.assertEqual(4, self.client.get_number_of_frontend_port())\n", "method_code": " def get_number_of_frontend_port(self):\n return len(self.get_frontend_ports())\n ", "context": "class UnityClient(object):\n @to_number\n def get_number_of_frontend_port(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_number_of_frontend_port", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001914.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_number_of_backend_port", "tests": "import unittest\n\nclass Test_get_number_of_backend_port(unittest.TestCase):\n def test_get_number_of_backend_port(self):\n self.assertEqual(2, self.client.get_number_of_backend_port())\n", "method_code": " def get_number_of_backend_port(self):\n return len(self.get_backend_ports())\n ", "context": "class UnityClient(object):\n @to_number\n def get_number_of_backend_port(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_number_of_backend_port", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001915.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_total_capacity", "tests": "import unittest\n\nclass Test_get_total_capacity(unittest.TestCase):\n def test_get_total_capacity(self):\n self.assertEqual('10240.0', self.client.get_total_capacity())\n", "method_code": " def get_total_capacity(self):\n return sum((x.size_total for x in self.unity_system.get_system_capacity()))\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_total_capacity(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_total_capacity", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001916.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_used_capacity", "tests": "import unittest\n\nclass Test_get_used_capacity(unittest.TestCase):\n def test_get_used_capacity(self):\n self.assertEqual('3072.0', self.client.get_used_capacity())\n", "method_code": " def get_used_capacity(self):\n return sum((x.size_used for x in self.unity_system.get_system_capacity()))\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_used_capacity(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_used_capacity", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001917.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_free_capacity", "tests": "import unittest\n\nclass Test_get_free_capacity(unittest.TestCase):\n def test_get_free_capacity(self):\n self.assertEqual('7168.0', self.client.get_free_capacity())\n", "method_code": " def get_free_capacity(self):\n return sum((x.size_free for x in self.unity_system.get_system_capacity()))\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_free_capacity(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_free_capacity", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001918.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_total_iops", "tests": "import unittest\n\nclass Test_get_total_iops(unittest.TestCase):\n def test_get_total_iops(self):\n self.assertEqual('0.533', self.client.get_total_iops())\n", "method_code": " def get_total_iops(self):\n self.unity_system.update()\n return self.unity_system.total_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_total_iops(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_total_iops", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001919.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_read_iops", "tests": "import unittest\n\nclass Test_get_read_iops(unittest.TestCase):\n def test_get_read_iops(self):\n self.assertEqual('0.133', self.client.get_read_iops())\n", "method_code": " def get_read_iops(self):\n self.unity_system.update()\n return self.unity_system.read_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_read_iops(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_read_iops", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001920.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_write_iops", "tests": "import unittest\n\nclass Test_get_write_iops(unittest.TestCase):\n def test_get_write_iops(self):\n self.assertEqual('0.4', self.client.get_write_iops())\n", "method_code": " def get_write_iops(self):\n self.unity_system.update()\n return self.unity_system.write_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_write_iops(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_write_iops", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001921.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_total_byte_rate", "tests": "import unittest\n\nclass Test_get_total_byte_rate(unittest.TestCase):\n def test_get_total_byte_rate(self):\n self.assertEqual('2.628', self.client.get_total_byte_rate())\n", "method_code": " def get_total_byte_rate(self):\n self.unity_system.update()\n return self.unity_system.total_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_total_byte_rate(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_total_byte_rate", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001922.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_read_byte_rate", "tests": "import unittest\n\nclass Test_get_read_byte_rate(unittest.TestCase):\n def test_get_read_byte_rate(self):\n self.assertEqual('0.178', self.client.get_read_byte_rate())\n", "method_code": " def get_read_byte_rate(self):\n self.unity_system.update()\n return self.unity_system.read_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_read_byte_rate(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_read_byte_rate", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001923.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_write_byte_rate", "tests": "import unittest\n\nclass Test_get_write_byte_rate(unittest.TestCase):\n def test_get_write_byte_rate(self):\n self.assertEqual('2.449', self.client.get_write_byte_rate())\n", "method_code": " def get_write_byte_rate(self):\n self.unity_system.update()\n return self.unity_system.write_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_write_byte_rate(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_write_byte_rate", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001924.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sps", "tests": "import unittest\n\nclass Test_get_sps(unittest.TestCase):\n def test_get_sps(self):\n items = self.client.get_sps()\n self.assertEqual(3, len(items))\n self.assertEqual({'spa', 'spb', 'spc'}, set(items))\n", "method_code": " def get_sps(self):\n self.sps = {sp.id: sp for sp in self.unity_system.get_sp()}\n return self.sps.keys()\n ", "context": "class UnityClient(object):\n def get_sps(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_sps", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001925.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_name", "tests": "import unittest\n\nclass Test_get_sp_name(unittest.TestCase):\n @ddt.data({'key': 'spa', 'name': 'SP A'}, {'key': 'spb', 'name': NONE_STRING})\n def test_get_sp_name(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['name'], self.client.get_sp_name(param_dict['key']))\n", "method_code": " def get_sp_name(self, id):\n sp = self._get_sp(id)\n return sp.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_sp_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001926.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_serial_number", "tests": "import unittest\n\nclass Test_get_sp_serial_number(unittest.TestCase):\n @ddt.data({'key': 'spa', 'emc_serial_number': 'CF2HF144300003'}, {'key': 'spb', 'emc_serial_number': NONE_STRING})\n def test_get_sp_serial_number(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['emc_serial_number'], self.client.get_sp_serial_number(param_dict['key']))\n", "method_code": " def get_sp_serial_number(self, id):\n sp = self._get_sp(id)\n return sp.emc_serial_number\n ", "context": "class UnityClient(object):\n @to_string\n def get_sp_serial_number(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001927.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_health_status", "tests": "import unittest\n\nclass Test_get_sp_health_status(unittest.TestCase):\n @ddt.data({'key': 'spa', 'health': 'OK'}, {'key': 'spb', 'health': NONE_STRING}, {'key': 'spc', 'health': NONE_STRING})\n def test_get_sp_health_status(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['health'], self.client.get_sp_health_status(param_dict['key']))\n", "method_code": " def get_sp_health_status(self, id):\n sp = self._get_sp(id)\n return sp.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_sp_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001928.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_utilization", "tests": "import unittest\n\nclass Test_get_sp_utilization(unittest.TestCase):\n @ddt.data({'key': 'spa', 'utilization': '2.629'}, {'key': 'spb', 'utilization': '0'}, {'key': 'spc', 'utilization': '0'})\n def test_get_sp_utilization(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['utilization'], self.client.get_sp_utilization(param_dict['key']))\n", "method_code": " def get_sp_utilization(self, id):\n sp = self._get_sp(id)\n return sp.utilization\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_sp_utilization(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001929.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_block_total_iops", "tests": "import unittest\n\nclass Test_get_sp_block_total_iops(unittest.TestCase):\n @ddt.data({'key': 'spa', 'block_total_iops': '0.533'}, {'key': 'spb', 'block_total_iops': '0'}, {'key': 'spc', 'block_total_iops': '0'})\n def test_get_sp_block_total_iops(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['block_total_iops'], self.client.get_sp_block_total_iops(param_dict['key']))\n", "method_code": " def get_sp_block_total_iops(self, id):\n sp = self._get_sp(id)\n return sp.block_total_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_sp_block_total_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001930.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_block_read_iops", "tests": "import unittest\n\nclass Test_get_sp_block_read_iops(unittest.TestCase):\n @ddt.data({'key': 'spa', 'block_read_iops': '0.133'}, {'key': 'spb', 'block_read_iops': '0'}, {'key': 'spc', 'block_read_iops': '0'})\n def test_get_sp_block_read_iops(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['block_read_iops'], self.client.get_sp_block_read_iops(param_dict['key']))\n", "method_code": " def get_sp_block_read_iops(self, id):\n sp = self._get_sp(id)\n return sp.block_read_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_sp_block_read_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001931.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_block_write_iops", "tests": "import unittest\n\nclass Test_get_sp_block_write_iops(unittest.TestCase):\n @ddt.data({'key': 'spa', 'block_write_iops': '0.4'}, {'key': 'spb', 'block_write_iops': '0'}, {'key': 'spc', 'block_write_iops': '0'})\n def test_get_sp_block_write_iops(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['block_write_iops'], self.client.get_sp_block_write_iops(param_dict['key']))\n", "method_code": " def get_sp_block_write_iops(self, id):\n sp = self._get_sp(id)\n return sp.block_write_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_sp_block_write_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001932.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_total_byte_rate", "tests": "import unittest\n\nclass Test_get_sp_total_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'spa', 'total_byte_rate': '2.628'}, {'key': 'spb', 'total_byte_rate': '0'}, {'key': 'spc', 'total_byte_rate': '0'})\n def test_get_sp_total_byte_rate(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['total_byte_rate'], self.client.get_sp_total_byte_rate(param_dict['key']))\n", "method_code": " def get_sp_total_byte_rate(self, id):\n sp = self._get_sp(id)\n return sp.total_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_sp_total_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001933.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_read_byte_rate", "tests": "import unittest\n\nclass Test_get_sp_read_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'spa', 'read_byte_rate': '0.178'}, {'key': 'spb', 'read_byte_rate': '0'}, {'key': 'spc', 'read_byte_rate': '0'})\n def test_get_sp_read_byte_rate(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['read_byte_rate'], self.client.get_sp_read_byte_rate(param_dict['key']))\n", "method_code": " def get_sp_read_byte_rate(self, id):\n sp = self._get_sp(id)\n return sp.read_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_sp_read_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001934.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_write_byte_rate", "tests": "import unittest\n\nclass Test_get_sp_write_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'spa', 'write_byte_rate': '2.449'}, {'key': 'spb', 'write_byte_rate': '0'}, {'key': 'spc', 'write_byte_rate': '0'})\n def test_get_sp_write_byte_rate(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['write_byte_rate'], self.client.get_sp_write_byte_rate(param_dict['key']))\n", "method_code": " def get_sp_write_byte_rate(self, id):\n sp = self._get_sp(id)\n return sp.write_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_sp_write_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001935.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_cache_dirty_size", "tests": "import unittest\n\nclass Test_get_sp_cache_dirty_size(unittest.TestCase):\n @ddt.data({'key': 'spa', 'block_cache_dirty_size': '65'}, {'key': 'spb', 'block_cache_dirty_size': '0'}, {'key': 'spc', 'block_cache_dirty_size': '0'})\n def test_get_sp_cache_dirty_size(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['block_cache_dirty_size'], self.client.get_sp_cache_dirty_size(param_dict['key']))\n", "method_code": " def get_sp_cache_dirty_size(self, id):\n sp = self._get_sp(id)\n return sp.block_cache_dirty_size\n ", "context": "class UnityClient(object):\n @to_string\n @to_number()\n def get_sp_cache_dirty_size(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001936.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_block_cache_read_hit_ratio", "tests": "import unittest\n\nclass Test_get_sp_block_cache_read_hit_ratio(unittest.TestCase):\n @ddt.data({'key': 'spa', 'block_cache_read_hit_ratio': '100.533'}, {'key': 'spb', 'block_cache_read_hit_ratio': '0'}, {'key': 'spc', 'block_cache_read_hit_ratio': '0'})\n def test_get_sp_block_cache_read_hit_ratio(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['block_cache_read_hit_ratio'], self.client.get_sp_block_cache_read_hit_ratio(param_dict['key']))\n", "method_code": " def get_sp_block_cache_read_hit_ratio(self, id):\n sp = self._get_sp(id)\n return sp.block_cache_read_hit_ratio\n ", "context": "class UnityClient(object):\n @to_string\n @to_number()\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001937.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_block_cache_write_hit_ratio", "tests": "import unittest\n\nclass Test_get_sp_block_cache_write_hit_ratio(unittest.TestCase):\n @ddt.data({'key': 'spa', 'block_cache_write_hit_ratio': '81.967'}, {'key': 'spb', 'block_cache_write_hit_ratio': '0'}, {'key': 'spc', 'block_cache_write_hit_ratio': '0'})\n def test_get_sp_block_cache_write_hit_ratio(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['block_cache_write_hit_ratio'], self.client.get_sp_block_cache_write_hit_ratio(param_dict['key']))\n", "method_code": " def get_sp_block_cache_write_hit_ratio(self, id):\n sp = self._get_sp(id)\n return sp.block_cache_write_hit_ratio\n ", "context": "class UnityClient(object):\n @to_string\n @to_number()\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001938.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_fast_cache_read_hits", "tests": "import unittest\n\nclass Test_get_sp_fast_cache_read_hits(unittest.TestCase):\n @ddt.data({'key': 'spa', 'fast_cache_read_hits': '30.0'}, {'key': 'spb', 'fast_cache_read_hits': '0'}, {'key': 'spc', 'fast_cache_read_hits': NONE_STRING})\n def test_get_sp_fast_cache_read_hits(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['fast_cache_read_hits'], self.client.get_sp_fast_cache_read_hits(param_dict['key']))\n", "method_code": " def get_sp_fast_cache_read_hits(self, id):\n sp = self._get_sp(id)\n return sp.fast_cache_read_hits\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_sp_fast_cache_read_hits(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001939.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_fast_cache_write_hits", "tests": "import unittest\n\nclass Test_get_sp_fast_cache_write_hits(unittest.TestCase):\n @ddt.data({'key': 'spa', 'fast_cache_write_hits': '30.0'}, {'key': 'spb', 'fast_cache_write_hits': '0'}, {'key': 'spc', 'fast_cache_write_hits': NONE_STRING})\n def test_get_sp_fast_cache_write_hits(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['fast_cache_write_hits'], self.client.get_sp_fast_cache_write_hits(param_dict['key']))\n", "method_code": " def get_sp_fast_cache_write_hits(self, id):\n sp = self._get_sp(id)\n return sp.fast_cache_write_hits\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_sp_fast_cache_write_hits(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001940.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_fast_cache_read_hit_rate", "tests": "import unittest\n\nclass Test_get_sp_fast_cache_read_hit_rate(unittest.TestCase):\n @ddt.data({'key': 'spa', 'fast_cache_read_hit_rate': '30.0'}, {'key': 'spb', 'fast_cache_read_hit_rate': '0'}, {'key': 'spc', 'fast_cache_read_hit_rate': NONE_STRING})\n def test_get_sp_fast_cache_read_hit_rate(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['fast_cache_read_hit_rate'], self.client.get_sp_fast_cache_read_hit_rate(param_dict['key']))\n", "method_code": " def get_sp_fast_cache_read_hit_rate(self, id):\n sp = self._get_sp(id)\n return sp.fast_cache_read_hit_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001941.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_sp_fast_cache_write_hit_rate", "tests": "import unittest\n\nclass Test_get_sp_fast_cache_write_hit_rate(unittest.TestCase):\n @ddt.data({'key': 'spa', 'fast_cache_write_hit_rate': '30.03'}, {'key': 'spb', 'fast_cache_write_hit_rate': '0'}, {'key': 'spc', 'fast_cache_write_hit_rate': NONE_STRING})\n def test_get_sp_fast_cache_write_hit_rate(self, param_dict):\n self.client.get_sps()\n self.assertEqual(param_dict['fast_cache_write_hit_rate'], self.client.get_sp_fast_cache_write_hit_rate(param_dict['key']))\n", "method_code": " def get_sp_fast_cache_write_hit_rate(self, id):\n sp = self._get_sp(id)\n return sp.fast_cache_write_hit_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001942.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pools", "tests": "import unittest\n\nclass Test_get_pools(unittest.TestCase):\n def test_get_pools(self):\n items = self.client.get_pools()\n self.assertEqual(3, len(items))\n self.assertEqual({'pool_1', 'pool_2', 'pool_3'}, set(items))\n", "method_code": " def get_pools(self):\n self.pools = {pool.id: pool for pool in self.unity_system.get_pool()}\n return self.pools.keys()\n ", "context": "class UnityClient(object):\n def get_pools(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_pools", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001943.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_name", "tests": "import unittest\n\nclass Test_get_pool_name(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'name': 'Beijing'}, {'key': 'pool_2', 'name': NONE_STRING})\n def test_get_pool_name(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['name'], self.client.get_pool_name(param_dict['key']))\n", "method_code": " def get_pool_name(self, id):\n pool = self._get_pool(id)\n return pool.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_pool_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001944.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_disk_types", "tests": "import unittest\n\nclass Test_get_pool_disk_types(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'tiers': 'Extreme Performance, Performance, Capacity'}, {'key': 'pool_2', 'tiers': NONE_STRING})\n def test_get_pool_disk_types(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['tiers'], self.client.get_pool_disk_types(param_dict['key']))\n", "method_code": " def get_pool_disk_types(self, id):\n pool = self._get_pool(id)\n if hasattr(pool, 'tiers') and pool.tiers:\n return ', '.join((x.name for x in pool.tiers))\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_pool_disk_types(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001945.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_raid_levels", "tests": "import unittest\n\nclass Test_get_pool_raid_levels(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'raid_type': 'RAID10'}, {'key': 'pool_2', 'raid_type': NONE_STRING})\n def test_get_pool_raid_levels(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['raid_type'], self.client.get_pool_raid_levels(param_dict['key']))\n", "method_code": " def get_pool_raid_levels(self, id):\n pool = self._get_pool(id)\n return pool.raid_type.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_pool_raid_levels(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001946.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_fast_cache_status", "tests": "import unittest\n\nclass Test_get_pool_fast_cache_status(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'is_fast_cache_enabled': 'True'}, {'key': 'pool_2', 'is_fast_cache_enabled': NONE_STRING})\n def test_get_pool_fast_cache_status(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['is_fast_cache_enabled'], self.client.get_pool_fast_cache_status(param_dict['key']))\n", "method_code": " def get_pool_fast_cache_status(self, id):\n pool = self._get_pool(id)\n return pool.is_fast_cache_enabled\n ", "context": "class UnityClient(object):\n @to_string\n def get_pool_fast_cache_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001947.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_number_of_disk", "tests": "import unittest\n\nclass Test_get_pool_number_of_disk(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'disk_count': 30}, {'key': 'pool_2', 'disk_count': 0})\n def test_get_pool_number_of_disk(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['disk_count'], self.client.get_pool_number_of_disk(param_dict['key']))\n", "method_code": " def get_pool_number_of_disk(self, id):\n pool = self._get_pool(id)\n if hasattr(pool, 'tiers') and pool.tiers:\n return sum((x.disk_count for x in pool.tiers))\n else:\n return 0\n ", "context": "class UnityClient(object):\n @to_number\n def get_pool_number_of_disk(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001948.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_size_total", "tests": "import unittest\n\nclass Test_get_pool_size_total(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'size_total': '2793.968'}, {'key': 'pool_2', 'size_total': '0'})\n def test_get_pool_size_total(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['size_total'], self.client.get_pool_size_total(param_dict['key']))\n", "method_code": " def get_pool_size_total(self, id):\n pool = self._get_pool(id)\n return pool.size_total\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_pool_size_total(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001949.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_size_free", "tests": "import unittest\n\nclass Test_get_pool_size_free(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'size_free': '931.323'}, {'key': 'pool_2', 'size_free': '0'})\n def test_get_pool_size_free(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['size_free'], self.client.get_pool_size_free(param_dict['key']))\n", "method_code": " def get_pool_size_free(self, id):\n pool = self._get_pool(id)\n return pool.size_free\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_pool_size_free(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001950.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_size_used", "tests": "import unittest\n\nclass Test_get_pool_size_used(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'size_used': '1862.645'}, {'key': 'pool_2', 'size_used': '0'})\n def test_get_pool_size_used(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['size_used'], self.client.get_pool_size_used(param_dict['key']))\n", "method_code": " def get_pool_size_used(self, id):\n pool = self._get_pool(id)\n return pool.size_used\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_pool_size_used(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001951.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_pool_size_ultilization", "tests": "import unittest\n\nclass Test_get_pool_size_ultilization(unittest.TestCase):\n @ddt.data({'key': 'pool_1', 'size_ultilization': '0.667'}, {'key': 'pool_2', 'size_ultilization': '0'})\n def test_get_pool_size_ultilization(self, param_dict):\n self.client.get_pools()\n self.assertEqual(param_dict['size_ultilization'], self.client.get_pool_size_ultilization(param_dict['key']))\n", "method_code": " def get_pool_size_ultilization(self, id):\n pool = self._get_pool(id)\n try:\n return float(pool.size_used) / float(pool.size_total)\n except ZeroDivisionError:\n return 0\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_pool_size_ultilization(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001952.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_luns", "tests": "import unittest\n\nclass Test_get_luns(unittest.TestCase):\n def test_get_luns(self):\n items = self.client.get_luns()\n self.assertEqual(4, len(items))\n self.assertEqual({'sv_1', 'sv_2', 'sv_3', 'sv_4'}, set(items))\n", "method_code": " def get_luns(self):\n self.luns = {lun.id: lun for lun in self.unity_system.get_lun()}\n self.get_hosts()\n return self.luns.keys()\n ", "context": "class UnityClient(object):\n def get_luns(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_luns", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001953.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_name", "tests": "import unittest\n\nclass Test_get_lun_name(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'name': 'Yangpu'}, {'key': 'sv_2', 'name': 'n/a'})\n def test_get_lun_name(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['name'], self.client.get_lun_name(param_dict['key']))\n", "method_code": " def get_lun_name(self, id):\n lun = self._get_lun(id)\n return lun.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_lun_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001954.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_raid_type", "tests": "import unittest\n\nclass Test_get_lun_raid_type(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'raid_type': 'RAID10'}, {'key': 'sv_2', 'raid_type': NONE_STRING}, {'key': 'sv_3', 'raid_type': NONE_STRING})\n def test_get_lun_raid_type(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['raid_type'], self.client.get_lun_raid_type(param_dict['key']))\n", "method_code": " def get_lun_raid_type(self, id):\n lun = self._get_lun(id)\n return lun.pool.raid_type.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_lun_raid_type(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001955.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_size_allocated", "tests": "import unittest\n\nclass Test_get_lun_size_allocated(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'size_allocated': '0.0'}, {'key': 'sv_2', 'size_allocated': '0'}, {'key': 'sv_3', 'size_allocated': '0'}, {'key': 'sv_4', 'size_allocated': NONE_STRING})\n def test_get_lun_size_allocated(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['size_allocated'], self.client.get_lun_size_allocated(param_dict['key']))\n", "method_code": " def get_lun_size_allocated(self, id):\n lun = self._get_lun(id)\n return lun.size_allocated\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_lun_size_allocated(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001956.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_size_total", "tests": "import unittest\n\nclass Test_get_lun_size_total(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'size_total': '100.0'}, {'key': 'sv_2', 'size_total': '0'}, {'key': 'sv_3', 'size_total': '0'}, {'key': 'sv_4', 'size_total': NONE_STRING})\n def test_get_lun_size_total(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['size_total'], self.client.get_lun_size_total(param_dict['key']))\n", "method_code": " def get_lun_size_total(self, id):\n lun = self._get_lun(id)\n return lun.size_total\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_lun_size_total(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001957.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_health_status", "tests": "import unittest\n\nclass Test_get_lun_health_status(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'health': 'OK'}, {'key': 'sv_2', 'health': NONE_STRING}, {'key': 'sv_3', 'health': NONE_STRING}, {'key': 'sv_4', 'health': 'OK BUT'})\n def test_get_lun_health_status(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['health'], self.client.get_lun_health_status(param_dict['key']))\n", "method_code": " def get_lun_health_status(self, id):\n lun = self._get_lun(id)\n return lun.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_lun_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001958.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_fast_cache_status", "tests": "import unittest\n\nclass Test_get_lun_fast_cache_status(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'is_fast_cache_enabled': 'False'}, {'key': 'sv_2', 'is_fast_cache_enabled': NONE_STRING}, {'key': 'sv_3', 'is_fast_cache_enabled': NONE_STRING}, {'key': 'sv_4', 'is_fast_cache_enabled': 'True'})\n def test_get_lun_fast_cache_status(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['is_fast_cache_enabled'], self.client.get_lun_fast_cache_status(param_dict['key']))\n", "method_code": " def get_lun_fast_cache_status(self, id):\n lun = self._get_lun(id)\n return lun.pool.is_fast_cache_enabled\n ", "context": "class UnityClient(object):\n @to_string\n def get_lun_fast_cache_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001959.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_default_sp", "tests": "import unittest\n\nclass Test_get_lun_default_sp(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'default_node': 'SP B'}, {'key': 'sv_2', 'default_node': NONE_STRING}, {'key': 'sv_3', 'default_node': NONE_STRING})\n def test_get_lun_default_sp(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['default_node'], self.client.get_lun_default_sp(param_dict['key']))\n", "method_code": " def get_lun_default_sp(self, id):\n lun = self._get_lun(id)\n return lun.default_node.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_lun_default_sp(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001960.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_current_sp", "tests": "import unittest\n\nclass Test_get_lun_current_sp(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'current_node': 'SP A'}, {'key': 'sv_2', 'current_node': NONE_STRING}, {'key': 'sv_3', 'current_node': NONE_STRING})\n def test_get_lun_current_sp(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['current_node'], self.client.get_lun_current_sp(param_dict['key']))\n", "method_code": " def get_lun_current_sp(self, id):\n lun = self._get_lun(id)\n return lun.current_node.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_lun_current_sp(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001961.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_response_time", "tests": "import unittest\n\nclass Test_get_lun_response_time(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'response_time': '5.08'}, {'key': 'sv_2', 'response_time': '0'}, {'key': 'sv_3', 'response_time': '0'}, {'key': 'sv_4', 'response_time': NONE_STRING})\n def test_get_lun_response_time(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['response_time'], self.client.get_lun_response_time(param_dict['key']))\n", "method_code": " def get_lun_response_time(self, id):\n lun = self._get_lun(id)\n return lun.response_time\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_time_unit\n def get_lun_response_time(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001962.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_queue_length", "tests": "import unittest\n\nclass Test_get_lun_queue_length(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'queue_length': '0.01'}, {'key': 'sv_2', 'queue_length': '0'}, {'key': 'sv_3', 'queue_length': '0'}, {'key': 'sv_4', 'queue_length': NONE_STRING})\n def test_get_lun_queue_length(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['queue_length'], self.client.get_lun_queue_length(param_dict['key']))\n", "method_code": " def get_lun_queue_length(self, id):\n lun = self._get_lun(id)\n return lun.queue_length\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_lun_queue_length(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001963.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_total_iops", "tests": "import unittest\n\nclass Test_get_lun_total_iops(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'total_iops': '0.433'}, {'key': 'sv_2', 'total_iops': '0'}, {'key': 'sv_3', 'total_iops': '0'}, {'key': 'sv_4', 'total_iops': NONE_STRING})\n def test_get_lun_total_iops(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['total_iops'], self.client.get_lun_total_iops(param_dict['key']))\n", "method_code": " def get_lun_total_iops(self, id):\n lun = self._get_lun(id)\n return lun.total_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_lun_total_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001964.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_read_iops", "tests": "import unittest\n\nclass Test_get_lun_read_iops(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'read_iops': '0.033'}, {'key': 'sv_2', 'read_iops': '0'}, {'key': 'sv_3', 'read_iops': '0'}, {'key': 'sv_4', 'read_iops': NONE_STRING})\n def test_get_lun_read_iops(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['read_iops'], self.client.get_lun_read_iops(param_dict['key']))\n", "method_code": " def get_lun_read_iops(self, id):\n lun = self._get_lun(id)\n return lun.read_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_lun_read_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001965.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_write_iops", "tests": "import unittest\n\nclass Test_get_lun_write_iops(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'write_iops': '0.4'}, {'key': 'sv_2', 'write_iops': '0'}, {'key': 'sv_3', 'write_iops': '0'}, {'key': 'sv_4', 'write_iops': NONE_STRING})\n def test_get_lun_write_iops(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['write_iops'], self.client.get_lun_write_iops(param_dict['key']))\n", "method_code": " def get_lun_write_iops(self, id):\n lun = self._get_lun(id)\n return lun.write_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_lun_write_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001966.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_total_byte_rate", "tests": "import unittest\n\nclass Test_get_lun_total_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'total_byte_rate': '0.003'}, {'key': 'sv_2', 'total_byte_rate': '0'}, {'key': 'sv_3', 'total_byte_rate': '0'}, {'key': 'sv_4', 'total_byte_rate': NONE_STRING})\n def test_get_lun_total_byte_rate(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['total_byte_rate'], self.client.get_lun_total_byte_rate(param_dict['key']))\n", "method_code": " def get_lun_total_byte_rate(self, id):\n lun = self._get_lun(id)\n return lun.total_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_lun_total_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001967.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_read_byte_rate", "tests": "import unittest\n\nclass Test_get_lun_read_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'read_byte_rate': '0.0'}, {'key': 'sv_2', 'read_byte_rate': '0'}, {'key': 'sv_3', 'read_byte_rate': '0'}, {'key': 'sv_4', 'read_byte_rate': NONE_STRING})\n def test_get_lun_read_byte_rate(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['read_byte_rate'], self.client.get_lun_read_byte_rate(param_dict['key']))\n", "method_code": " def get_lun_read_byte_rate(self, id):\n lun = self._get_lun(id)\n return lun.read_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_lun_read_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001968.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_write_byte_rate", "tests": "import unittest\n\nclass Test_get_lun_write_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'write_byte_rate': '0.002'}, {'key': 'sv_2', 'write_byte_rate': '0'}, {'key': 'sv_3', 'write_byte_rate': '0'}, {'key': 'sv_4', 'write_byte_rate': NONE_STRING})\n def test_get_lun_write_byte_rate(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['write_byte_rate'], self.client.get_lun_write_byte_rate(param_dict['key']))\n", "method_code": " def get_lun_write_byte_rate(self, id):\n lun = self._get_lun(id)\n return lun.write_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_lun_write_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001969.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_utilization", "tests": "import unittest\n\nclass Test_get_lun_utilization(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'utilization': '0.081'}, {'key': 'sv_2', 'utilization': '0'}, {'key': 'sv_3', 'utilization': '0'}, {'key': 'sv_4', 'utilization': NONE_STRING})\n def test_get_lun_utilization(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['utilization'], self.client.get_lun_utilization(param_dict['key']))\n", "method_code": " def get_lun_utilization(self, id):\n lun = self._get_lun(id)\n return lun.utilization\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_lun_utilization(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001970.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_lun_host_access", "tests": "import unittest\n\nclass Test_get_lun_host_access(unittest.TestCase):\n @ddt.data({'key': 'sv_1', 'host_access': 'ubuntu1604'}, {'key': 'sv_2', 'host_access': NONE_STRING}, {'key': 'sv_3', 'host_access': NONE_STRING})\n def test_get_lun_host_access(self, param_dict):\n self.client.get_luns()\n self.assertEqual(param_dict['host_access'], self.client.get_lun_host_access(param_dict['key']))\n", "method_code": " def get_lun_host_access(self, id):\n lst = []\n for host in self.hosts.values():\n if hasattr(host, 'host_luns') and host.host_luns is not None:\n for host_lun in host.host_luns:\n if host_lun.lun.id == id:\n lst.append(host.name)\n if lst:\n return ', '.join(lst)\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_lun_host_access(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001971.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disks", "tests": "import unittest\n\nclass Test_get_disks(unittest.TestCase):\n def test_get_disks(self):\n items = self.client.get_disks()\n self.assertEqual(4, len(items))\n self.assertEqual({'dpe_drive_0', 'dpe_drive_1', 'dae_drive_0', 'dae_drive_1'}, set(items))\n", "method_code": " def get_disks(self):\n self.disks = {disk.id: disk for disk in self.unity_system.get_disk()}\n return self.disks.keys()\n ", "context": "class UnityClient(object):\n def get_disks(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_disks", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001972.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_name", "tests": "import unittest\n\nclass Test_get_disk_name(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'name': 'DPE Drive 0'}, {'key': 'dpe_drive_1', 'name': NONE_STRING})\n def test_get_disk_name(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['name'], self.client.get_disk_name(param_dict['key']))\n", "method_code": " def get_disk_name(self, id):\n disk = self._get_disk(id)\n return disk.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_disk_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001973.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_model", "tests": "import unittest\n\nclass Test_get_disk_model(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'model': 'HU415606 EMC600'}, {'key': 'dpe_drive_1', 'model': NONE_STRING})\n def test_get_disk_model(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['model'], self.client.get_disk_model(param_dict['key']))\n", "method_code": " def get_disk_model(self, id):\n disk = self._get_disk(id)\n return disk.model\n ", "context": "class UnityClient(object):\n @to_string\n def get_disk_model(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001974.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_serial_number", "tests": "import unittest\n\nclass Test_get_disk_serial_number(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'emc_serial_number': '0XG507BJ'}, {'key': 'dpe_drive_1', 'emc_serial_number': NONE_STRING})\n def test_get_disk_serial_number(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['emc_serial_number'], self.client.get_disk_serial_number(param_dict['key']))\n", "method_code": " def get_disk_serial_number(self, id):\n disk = self._get_disk(id)\n return disk.emc_serial_number\n ", "context": "class UnityClient(object):\n @to_string\n def get_disk_serial_number(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001975.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_version", "tests": "import unittest\n\nclass Test_get_disk_version(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'version': 'K7P0'}, {'key': 'dpe_drive_1', 'version': NONE_STRING})\n def test_get_disk_version(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['version'], self.client.get_disk_version(param_dict['key']))\n", "method_code": " def get_disk_version(self, id):\n disk = self._get_disk(id)\n return disk.version\n ", "context": "class UnityClient(object):\n @to_string\n def get_disk_version(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001976.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_type", "tests": "import unittest\n\nclass Test_get_disk_type(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'disk_technology': 'SAS'}, {'key': 'dpe_drive_1', 'disk_technology': NONE_STRING})\n def test_get_disk_type(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['disk_technology'], self.client.get_disk_type(param_dict['key']))\n", "method_code": " def get_disk_type(self, id):\n disk = self._get_disk(id)\n return disk.disk_technology.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_disk_type(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001977.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_slot_number", "tests": "import unittest\n\nclass Test_get_disk_slot_number(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'slot_number': '0'}, {'key': 'dpe_drive_1', 'slot_number': NONE_STRING})\n def test_get_disk_slot_number(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['slot_number'], self.client.get_disk_slot_number(param_dict['key']))\n", "method_code": " def get_disk_slot_number(self, id):\n disk = self._get_disk(id)\n return disk.slot_number\n ", "context": "class UnityClient(object):\n @to_string\n def get_disk_slot_number(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001978.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_health_status", "tests": "import unittest\n\nclass Test_get_disk_health_status(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'health': 'OK'}, {'key': 'dpe_drive_1', 'health': NONE_STRING})\n def test_get_disk_health_status(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['health'], self.client.get_disk_health_status(param_dict['key']))\n", "method_code": " def get_disk_health_status(self, id):\n disk = self._get_disk(id)\n return disk.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_disk_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001979.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_raw_size", "tests": "import unittest\n\nclass Test_get_disk_raw_size(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'raw_size': '550.313'}, {'key': 'dpe_drive_1', 'raw_size': '0'}, {'key': 'dae_drive_0', 'raw_size': '0'}, {'key': 'dae_drive_1', 'raw_size': NONE_STRING})\n def test_get_disk_raw_size(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['raw_size'], self.client.get_disk_raw_size(param_dict['key']))\n", "method_code": " def get_disk_raw_size(self, id):\n disk = self._get_disk(id)\n return disk.raw_size\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit\n def get_disk_raw_size(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001980.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_current_pool", "tests": "import unittest\n\nclass Test_get_disk_current_pool(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'pool': 'Shanghai'}, {'key': 'dpe_drive_1', 'pool': NONE_STRING}, {'key': 'dae_drive_0', 'pool': NONE_STRING})\n def test_get_disk_current_pool(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['pool'], self.client.get_disk_current_pool(param_dict['key']))\n", "method_code": " def get_disk_current_pool(self, id):\n disk = self._get_disk(id)\n return disk.pool.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_disk_current_pool(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001981.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_response_time", "tests": "import unittest\n\nclass Test_get_disk_response_time(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'response_time': '35.337'}, {'key': 'dpe_drive_1', 'response_time': '0'}, {'key': 'dae_drive_0', 'response_time': '0'}, {'key': 'dae_drive_1', 'response_time': NONE_STRING})\n def test_get_disk_response_time(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['response_time'], self.client.get_disk_response_time(param_dict['key']))\n", "method_code": " def get_disk_response_time(self, id):\n disk = self._get_disk(id)\n return disk.response_time\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_time_unit\n def get_disk_response_time(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001982.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_queue_length", "tests": "import unittest\n\nclass Test_get_disk_queue_length(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'queue_length': '1.212'}, {'key': 'dpe_drive_1', 'queue_length': '0'}, {'key': 'dae_drive_0', 'queue_length': '0'}, {'key': 'dae_drive_1', 'queue_length': NONE_STRING})\n def test_get_disk_queue_length(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['queue_length'], self.client.get_disk_queue_length(param_dict['key']))\n", "method_code": " def get_disk_queue_length(self, id):\n disk = self._get_disk(id)\n return disk.queue_length\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_disk_queue_length(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001983.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_total_iops", "tests": "import unittest\n\nclass Test_get_disk_total_iops(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'total_iops': '2.2'}, {'key': 'dpe_drive_1', 'total_iops': '0'}, {'key': 'dae_drive_0', 'total_iops': '0'}, {'key': 'dae_drive_1', 'total_iops': NONE_STRING})\n def test_get_disk_total_iops(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['total_iops'], self.client.get_disk_total_iops(param_dict['key']))\n", "method_code": " def get_disk_total_iops(self, id):\n disk = self._get_disk(id)\n return disk.total_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_disk_total_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001984.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_read_iops", "tests": "import unittest\n\nclass Test_get_disk_read_iops(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'read_iops': '1.417'}, {'key': 'dpe_drive_1', 'read_iops': '0'}, {'key': 'dae_drive_0', 'read_iops': '0'}, {'key': 'dae_drive_1', 'read_iops': NONE_STRING})\n def test_get_disk_read_iops(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['read_iops'], self.client.get_disk_read_iops(param_dict['key']))\n", "method_code": " def get_disk_read_iops(self, id):\n disk = self._get_disk(id)\n return disk.read_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_disk_read_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001985.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_write_iops", "tests": "import unittest\n\nclass Test_get_disk_write_iops(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'write_iops': '0.783'}, {'key': 'dpe_drive_1', 'write_iops': '0'}, {'key': 'dae_drive_0', 'write_iops': '0'}, {'key': 'dae_drive_1', 'write_iops': NONE_STRING})\n def test_get_disk_write_iops(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['write_iops'], self.client.get_disk_write_iops(param_dict['key']))\n", "method_code": " def get_disk_write_iops(self, id):\n disk = self._get_disk(id)\n return disk.write_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_disk_write_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001986.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_total_byte_rate", "tests": "import unittest\n\nclass Test_get_disk_total_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'total_byte_rate': '1.269'}, {'key': 'dpe_drive_1', 'total_byte_rate': '0'}, {'key': 'dae_drive_0', 'total_byte_rate': '0'}, {'key': 'dae_drive_1', 'total_byte_rate': NONE_STRING})\n def test_get_disk_total_byte_rate(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['total_byte_rate'], self.client.get_disk_total_byte_rate(param_dict['key']))\n", "method_code": " def get_disk_total_byte_rate(self, id):\n disk = self._get_disk(id)\n return disk.total_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_disk_total_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001987.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_read_byte_rate", "tests": "import unittest\n\nclass Test_get_disk_read_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'read_byte_rate': '1.072'}, {'key': 'dpe_drive_1', 'read_byte_rate': '0'}, {'key': 'dae_drive_0', 'read_byte_rate': '0'}, {'key': 'dae_drive_1', 'read_byte_rate': NONE_STRING})\n def test_get_disk_read_byte_rate(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['read_byte_rate'], self.client.get_disk_read_byte_rate(param_dict['key']))\n", "method_code": " def get_disk_read_byte_rate(self, id):\n disk = self._get_disk(id)\n return disk.read_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_disk_read_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001988.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_write_byte_rate", "tests": "import unittest\n\nclass Test_get_disk_write_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'write_byte_rate': '0.197'}, {'key': 'dpe_drive_1', 'write_byte_rate': '0'}, {'key': 'dae_drive_0', 'write_byte_rate': '0'}, {'key': 'dae_drive_1', 'write_byte_rate': NONE_STRING})\n def test_get_disk_write_byte_rate(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['write_byte_rate'], self.client.get_disk_write_byte_rate(param_dict['key']))\n", "method_code": " def get_disk_write_byte_rate(self, id):\n disk = self._get_disk(id)\n return disk.write_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_disk_write_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001989.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_disk_utilization", "tests": "import unittest\n\nclass Test_get_disk_utilization(unittest.TestCase):\n @ddt.data({'key': 'dpe_drive_0', 'utilization': '22.45'}, {'key': 'dpe_drive_1', 'utilization': '0'}, {'key': 'dae_drive_0', 'utilization': '0'}, {'key': 'dae_drive_1', 'utilization': NONE_STRING})\n def test_get_disk_utilization(self, param_dict):\n self.client.get_disks()\n self.assertEqual(param_dict['utilization'], self.client.get_disk_utilization(param_dict['key']))\n", "method_code": " def get_disk_utilization(self, id):\n disk = self._get_disk(id)\n return disk.utilization\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_disk_utilization(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001990.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_ports", "tests": "import unittest\n\nclass Test_get_frontend_ports(unittest.TestCase):\n def test_get_frontend_ports(self):\n items = self.client.get_frontend_ports()\n self.assertEqual(4, len(items))\n self.assertEqual({'fc_port_spa_fc1', 'fc_port_spb_fc2', 'iscsi_port_iscsinode_spa_eth1', 'iscsi_port_iscsinode_spa_eth2'}, set(items))\n", "method_code": " def get_frontend_ports(self):\n self.fc_ports = {FC_PORT_TYPE + port.id: port for port in self.unity_system.get_fc_port()}\n self.iscsi_ports = {ISCSI_PORT_TYPE + port.id: port for port in self.unity_system.get_iscsi_node()}\n return list(self.fc_ports.keys()) + list(self.iscsi_ports.keys())\n ", "context": "class UnityClient(object):\n def get_frontend_ports(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_frontend_ports", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001991.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_id", "tests": "import unittest\n\nclass Test_get_frontend_port_id(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'id': 'spa_fc1'}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'id': 'iscsinode_spa_eth1'})\n def test_get_frontend_port_id(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['id'], self.client.get_frontend_port_id(param_dict['key']))\n", "method_code": " def get_frontend_port_id(self, id):\n port, _ = self._get_frontend_port(id)\n return port.id\n ", "context": "class UnityClient(object):\n @to_string\n def get_frontend_port_id(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001992.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_name", "tests": "import unittest\n\nclass Test_get_frontend_port_name(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'name': 'SP A FC Port 1'}, {'key': 'fc_port_spa_fc2', 'name': NONE_STRING}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'name': 'iqn.1992-04.com.emc:cx.fnm00150600267.a0'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'name': NONE_STRING})\n def test_get_frontend_port_name(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['name'], self.client.get_frontend_port_name(param_dict['key']))\n", "method_code": " def get_frontend_port_name(self, id):\n port, _ = self._get_frontend_port(id)\n return port.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_frontend_port_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001993.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_address", "tests": "import unittest\n\nclass Test_get_frontend_port_address(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'address': NONE_STRING}, {'key': 'fc_port_spa_fc2', 'address': NONE_STRING}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'address': '10.0.0.10'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'address': NONE_STRING})\n def test_get_frontend_port_address(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['address'], self.client.get_frontend_port_address(param_dict['key']))\n", "method_code": " def get_frontend_port_address(self, id):\n port, type = self._get_frontend_port(id)\n if type == FC_PORT_TYPE:\n return NONE_STRING\n if type == ISCSI_PORT_TYPE:\n ip_list = [portal.ip_address for portal in self.unity_system.get_iscsi_portal() if portal.iscsi_node.id == port.id]\n if ip_list:\n return ', '.join(ip_list)\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_frontend_port_address(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001994.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_type", "tests": "import unittest\n\nclass Test_get_frontend_port_type(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'port_type': 'LC'}, {'key': 'fc_port_spa_fc2', 'port_type': NONE_STRING}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'port_type': 'RJ45'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'port_type': NONE_STRING})\n def test_get_frontend_port_type(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['port_type'], self.client.get_frontend_port_type(param_dict['key']))\n", "method_code": " def get_frontend_port_type(self, id):\n port, type = self._get_frontend_port(id)\n if type == FC_PORT_TYPE:\n return port.connector_type.name\n if type == ISCSI_PORT_TYPE:\n return port.ethernet_port.connector_type.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_frontend_port_type(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001995.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_current_speed", "tests": "import unittest\n\nclass Test_get_frontend_port_current_speed(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'current_speed': '_8GbPS'}, {'key': 'fc_port_spa_fc2', 'current_speed': NONE_STRING}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'current_speed': '_10GbPS'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'current_speed': NONE_STRING})\n def test_get_frontend_port_current_speed(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['current_speed'], self.client.get_frontend_port_current_speed(param_dict['key']))\n", "method_code": " def get_frontend_port_current_speed(self, id):\n port, type = self._get_frontend_port(id)\n if type == FC_PORT_TYPE:\n return port.current_speed.name\n if type == ISCSI_PORT_TYPE:\n return port.ethernet_port.speed.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_frontend_port_current_speed(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001996.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_supported_speed", "tests": "import unittest\n\nclass Test_get_frontend_port_supported_speed(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'support_speed': '_4GbPS, _8GbPS, _16GbPS, AUTO'}, {'key': 'fc_port_spa_fc2', 'support_speed': NONE_STRING}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'support_speed': '_1GbPS, _10GbPS, _100MbPS, AUTO'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'support_speed': NONE_STRING})\n def test_get_frontend_port_supported_speed(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['support_speed'], self.client.get_frontend_port_supported_speed(param_dict['key']))\n", "method_code": " def get_frontend_port_supported_speed(self, id):\n port, type = self._get_frontend_port(id)\n if type == FC_PORT_TYPE:\n if hasattr(port, 'available_speeds') and port.available_speeds:\n return ', '.join((x.name for x in port.available_speeds))\n else:\n return NONE_STRING\n if type == ISCSI_PORT_TYPE:\n if hasattr(port.ethernet_port, 'supported_speeds') and port.ethernet_port.supported_speeds:\n return ', '.join((x.name for x in port.ethernet_port.supported_speeds))\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_frontend_port_supported_speed(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001997.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_health_status", "tests": "import unittest\n\nclass Test_get_frontend_port_health_status(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'health': 'MAJOR'}, {'key': 'fc_port_spa_fc2', 'health': NONE_STRING}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'health': 'OK BUT'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'health': NONE_STRING})\n def test_get_frontend_port_health_status(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['health'], self.client.get_frontend_port_health_status(param_dict['key']))\n", "method_code": " def get_frontend_port_health_status(self, id):\n port, type = self._get_frontend_port(id)\n if type == FC_PORT_TYPE:\n return port.health.value.name\n if type == ISCSI_PORT_TYPE:\n return port.ethernet_port.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_frontend_port_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001998.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_total_iops", "tests": "import unittest\n\nclass Test_get_frontend_port_total_iops(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'total_iops': '0'}, {'key': 'fc_port_spa_fc2', 'total_iops': '0'}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'total_iops': '0.533'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'total_iops': NONE_STRING})\n def test_get_frontend_port_total_iops(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['total_iops'], self.client.get_frontend_port_total_iops(param_dict['key']))\n", "method_code": " def get_frontend_port_total_iops(self, id):\n port, _ = self._get_frontend_port(id)\n return port.total_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_frontend_port_total_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001999.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_read_iops", "tests": "import unittest\n\nclass Test_get_frontend_port_read_iops(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'read_iops': '0'}, {'key': 'fc_port_spa_fc2', 'read_iops': '0'}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'read_iops': '0.133'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'read_iops': NONE_STRING})\n def test_get_frontend_port_read_iops(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['read_iops'], self.client.get_frontend_port_read_iops(param_dict['key']))\n", "method_code": " def get_frontend_port_read_iops(self, id):\n port, _ = self._get_frontend_port(id)\n return port.read_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_frontend_port_read_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002000.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_write_iops", "tests": "import unittest\n\nclass Test_get_frontend_port_write_iops(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'write_iops': '0'}, {'key': 'fc_port_spa_fc2', 'write_iops': '0'}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'write_iops': '0.4'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'write_iops': NONE_STRING})\n def test_get_frontend_port_write_iops(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['write_iops'], self.client.get_frontend_port_write_iops(param_dict['key']))\n", "method_code": " def get_frontend_port_write_iops(self, id):\n port, _ = self._get_frontend_port(id)\n return port.write_iops\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_frontend_port_write_iops(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002001.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_total_byte_rate", "tests": "import unittest\n\nclass Test_get_frontend_port_total_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'total_byte_rate': '0'}, {'key': 'fc_port_spa_fc2', 'total_byte_rate': '0'}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'total_byte_rate': '0.003'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'total_byte_rate': NONE_STRING})\n def test_get_frontend_port_total_byte_rate(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['total_byte_rate'], self.client.get_frontend_port_total_byte_rate(param_dict['key']))\n", "method_code": " def get_frontend_port_total_byte_rate(self, id):\n port, _ = self._get_frontend_port(id)\n return port.total_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_frontend_port_total_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002002.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_read_byte_rate", "tests": "import unittest\n\nclass Test_get_frontend_port_read_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'read_byte_rate': '0'}, {'key': 'fc_port_spa_fc2', 'read_byte_rate': '0'}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'read_byte_rate': '0.0'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'read_byte_rate': NONE_STRING})\n def test_get_frontend_port_read_byte_rate(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['read_byte_rate'], self.client.get_frontend_port_read_byte_rate(param_dict['key']))\n", "method_code": " def get_frontend_port_read_byte_rate(self, id):\n port, _ = self._get_frontend_port(id)\n return port.read_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_frontend_port_read_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002003.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_frontend_port_write_byte_rate", "tests": "import unittest\n\nclass Test_get_frontend_port_write_byte_rate(unittest.TestCase):\n @ddt.data({'key': 'fc_port_spa_fc1', 'write_byte_rate': '0'}, {'key': 'fc_port_spa_fc2', 'write_byte_rate': '0'}, {'key': 'iscsi_port_iscsinode_spa_eth1', 'write_byte_rate': '0.002'}, {'key': 'iscsi_port_iscsinode_spa_eth2', 'write_byte_rate': NONE_STRING})\n def test_get_frontend_port_write_byte_rate(self, param_dict):\n self.client.get_frontend_ports()\n self.assertEqual(param_dict['write_byte_rate'], self.client.get_frontend_port_write_byte_rate(param_dict['key']))\n", "method_code": " def get_frontend_port_write_byte_rate(self, id):\n port, _ = self._get_frontend_port(id)\n return port.write_byte_rate\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n @change_size_unit(to_unit='mb')\n def get_frontend_port_write_byte_rate(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002004.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_backend_ports", "tests": "import unittest\n\nclass Test_get_backend_ports(unittest.TestCase):\n def test_get_backend_ports(self):\n items = self.client.get_backend_ports()\n self.assertEqual(2, len(items))\n self.assertEqual({'spa_sas0', 'spb_sas0'}, set(items))\n", "method_code": " def get_backend_ports(self):\n self.sas_ports = {port.id: port for port in self.unity_system.get_sas_port()}\n return self.sas_ports.keys()\n ", "context": "class UnityClient(object):\n def get_backend_ports(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_backend_ports", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002005.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_backend_port_name", "tests": "import unittest\n\nclass Test_get_backend_port_name(unittest.TestCase):\n @ddt.data({'key': 'spa_sas0', 'name': 'SP A SAS Port 0'}, {'key': 'spb_sas0', 'name': NONE_STRING})\n def test_get_backend_port_name(self, param_dict):\n self.client.get_backend_ports()\n self.assertEqual(param_dict['name'], self.client.get_backend_port_name(param_dict['key']))\n", "method_code": " def get_backend_port_name(self, id):\n port = self._get_backend_port(id)\n return port.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_backend_port_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002006.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_backend_port_type", "tests": "import unittest\n\nclass Test_get_backend_port_type(unittest.TestCase):\n @ddt.data({'key': 'spa_sas0', 'connector_type': 'MINI_SAS_HD'}, {'key': 'spb_sas0', 'connector_type': NONE_STRING})\n def test_get_backend_port_type(self, param_dict):\n self.client.get_backend_ports()\n self.assertEqual(param_dict['connector_type'], self.client.get_backend_port_type(param_dict['key']))\n", "method_code": " def get_backend_port_type(self, id):\n port = self._get_backend_port(id)\n return port.connector_type.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_backend_port_type(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002007.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_backend_port_port_number", "tests": "import unittest\n\nclass Test_get_backend_port_port_number(unittest.TestCase):\n @ddt.data({'key': 'spa_sas0', 'port': '0'}, {'key': 'spb_sas0', 'port': NONE_STRING})\n def test_get_backend_port_port_number(self, param_dict):\n self.client.get_backend_ports()\n self.assertEqual(param_dict['port'], self.client.get_backend_port_port_number(param_dict['key']))\n", "method_code": " def get_backend_port_port_number(self, id):\n port = self._get_backend_port(id)\n return port.port\n ", "context": "class UnityClient(object):\n @to_string\n def get_backend_port_port_number(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002008.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_backend_port_current_speed", "tests": "import unittest\n\nclass Test_get_backend_port_current_speed(unittest.TestCase):\n @ddt.data({'key': 'spa_sas0', 'current_speed': '_12Gbps'}, {'key': 'spb_sas0', 'current_speed': NONE_STRING})\n def test_get_backend_port_current_speed(self, param_dict):\n self.client.get_backend_ports()\n self.assertEqual(param_dict['current_speed'], self.client.get_backend_port_current_speed(param_dict['key']))\n", "method_code": " def get_backend_port_current_speed(self, id):\n port = self._get_backend_port(id)\n return port.current_speed.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_backend_port_current_speed(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002009.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_backend_port_parent_io_module", "tests": "import unittest\n\nclass Test_get_backend_port_parent_io_module(unittest.TestCase):\n @ddt.data({'key': 'spa_sas0', 'parent_io_module': 'IO Module A'}, {'key': 'spb_sas0', 'parent_io_module': NONE_STRING})\n def test_get_backend_port_parent_io_module(self, param_dict):\n self.client.get_backend_ports()\n self.assertEqual(param_dict['parent_io_module'], self.client.get_backend_port_parent_io_module(param_dict['key']))\n", "method_code": " def get_backend_port_parent_io_module(self, id):\n port = self._get_backend_port(id)\n return port.parent_io_module.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_backend_port_parent_io_module(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002010.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_backend_port_parent_sp", "tests": "import unittest\n\nclass Test_get_backend_port_parent_sp(unittest.TestCase):\n @ddt.data({'key': 'spa_sas0', 'parent_storage_processor': 'SP A'}, {'key': 'spb_sas0', 'parent_storage_processor': NONE_STRING})\n def test_get_backend_port_parent_sp(self, param_dict):\n self.client.get_backend_ports()\n self.assertEqual(param_dict['parent_storage_processor'], self.client.get_backend_port_parent_sp(param_dict['key']))\n", "method_code": " def get_backend_port_parent_sp(self, id):\n port = self._get_backend_port(id)\n return port.parent_storage_processor.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_backend_port_parent_sp(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002011.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_backend_port_health_status", "tests": "import unittest\n\nclass Test_get_backend_port_health_status(unittest.TestCase):\n @ddt.data({'key': 'spa_sas0', 'health': 'OK'}, {'key': 'spb_sas0', 'health': NONE_STRING})\n def test_get_backend_port_health_status(self, param_dict):\n self.client.get_backend_ports()\n self.assertEqual(param_dict['health'], self.client.get_backend_port_health_status(param_dict['key']))\n", "method_code": " def get_backend_port_health_status(self, id):\n port = self._get_backend_port(id)\n return port.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_backend_port_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002012.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_hosts", "tests": "import unittest\n\nclass Test_get_hosts(unittest.TestCase):\n def test_get_hosts(self):\n items = self.client.get_hosts()\n self.assertEqual(5, len(items))\n self.assertEqual({'host_1', 'host_2', 'host_3', 'host_4', 'host_5'}, set(items))\n", "method_code": " def get_hosts(self):\n self.hosts = {host.id: host for host in self.unity_system.get_host()}\n return self.hosts.keys()\n ", "context": "class UnityClient(object):\n def get_hosts(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_hosts", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002013.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_host_name", "tests": "import unittest\n\nclass Test_get_host_name(unittest.TestCase):\n @ddt.data({'key': 'host_1', 'name': 'ubuntu1604'}, {'key': 'host_2', 'name': NONE_STRING})\n def test_get_host_name(self, param_dict):\n self.client.get_hosts()\n self.assertEqual(param_dict['name'], self.client.get_host_name(param_dict['key']))\n", "method_code": " def get_host_name(self, id):\n host = self._get_host(id)\n return host.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_host_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002014.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_host_network_address", "tests": "import unittest\n\nclass Test_get_host_network_address(unittest.TestCase):\n @ddt.data({'key': 'host_1', 'ip_list': '10.207.84.27, 2620:0:170:1d34:a236:9fff:fe66:8960, 2620:0:170:1d36:a236:9fff:fe66:8960'}, {'key': 'host_2', 'ip_list': NONE_STRING}, {'key': 'host_3', 'ip_list': NONE_STRING})\n def test_get_host_network_address(self, param_dict):\n self.client.get_hosts()\n self.assertEqual(param_dict['ip_list'], self.client.get_host_network_address(param_dict['key']))\n", "method_code": " def get_host_network_address(self, id):\n host = self._get_host(id)\n if hasattr(host, 'ip_list') and host.ip_list:\n return ', '.join(host.ip_list)\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_host_network_address(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002015.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_host_initiators", "tests": "import unittest\n\nclass Test_get_host_initiators(unittest.TestCase):\n @ddt.data({'key': 'host_1', 'initiators': 'iqn.1993-08.org.debian:01:b974ee37fea, 20:00:00:90:FA:53:49:28:10:00:00:90:FA:53:49:28, 20:00:00:90:FA:53:49:29:10:00:00:90:FA:53:49:29'}, {'key': 'host_2', 'initiators': NONE_STRING}, {'key': 'host_3', 'initiators': '20:00:00:90:FA:53:49, 20:00:00:90:FA:53:50'}, {'key': 'host_4', 'initiators': 'iqn.1993-08.org.debian:01:b974ee37fea'}, {'key': 'host_5', 'initiators': NONE_STRING})\n def test_get_host_initiators(self, param_dict):\n self.client.get_hosts()\n self.assertEqual(param_dict['initiators'], self.client.get_host_initiators(param_dict['key']))\n", "method_code": " def get_host_initiators(self, id):\n host = self._get_host(id)\n initiators = []\n if hasattr(host, 'iscsi_host_initiators') and host.iscsi_host_initiators:\n initiators.extend((x.initiator_id for x in host.iscsi_host_initiators))\n if hasattr(host, 'fc_host_initiators') and host.fc_host_initiators:\n initiators.extend((x.initiator_id for x in host.fc_host_initiators))\n if initiators:\n return ', '.join(initiators)\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_host_initiators(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002016.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_host_os_type", "tests": "import unittest\n\nclass Test_get_host_os_type(unittest.TestCase):\n @ddt.data({'key': 'host_1', 'os_type': 'Linux'})\n def test_get_host_os_type(self, param_dict):\n self.client.get_hosts()\n self.assertEqual(param_dict['os_type'], self.client.get_host_os_type(param_dict['key']))\n", "method_code": " def get_host_os_type(self, id):\n host = self._get_host(id)\n return host.os_type\n ", "context": "class UnityClient(object):\n @to_string\n def get_host_os_type(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002017.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_host_assigned_volumes", "tests": "import unittest\n\nclass Test_get_host_assigned_volumes(unittest.TestCase):\n @ddt.data({'key': 'host_1', 'host_luns': 'storops_dummy_lun'}, {'key': 'host_2', 'host_luns': NONE_STRING}, {'key': 'host_3', 'host_luns': NONE_STRING})\n def test_get_host_assigned_volumes(self, param_dict):\n self.client.get_hosts()\n self.assertEqual(param_dict['host_luns'], self.client.get_host_assigned_volumes(param_dict['key']))\n", "method_code": " def get_host_assigned_volumes(self, id):\n host = self._get_host(id)\n if hasattr(host, 'host_luns') and host.host_luns:\n return ', '.join((x.lun.name for x in host.host_luns))\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_host_assigned_volumes(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002018.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosures", "tests": "import unittest\n\nclass Test_get_enclosures(unittest.TestCase):\n def test_get_enclosures(self):\n items = self.client.get_enclosures()\n self.assertEqual(4, len(items))\n self.assertEqual({'dae_dae_1', 'dae_dae_2', 'dpe_dpe_1', 'dpe_dpe_2'}, set(items))\n", "method_code": " def get_enclosures(self):\n self.daes = {DAE_TYPE + dae.id: dae for dae in self.unity_system.get_dae()}\n self.dpes = {DPE_TYPE + dpe.id: dpe for dpe in self.unity_system.get_dpe()}\n return list(self.daes.keys()) + list(self.dpes.keys())\n ", "context": "class UnityClient(object):\n def get_enclosures(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_enclosures", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002019.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_id", "tests": "import unittest\n\nclass Test_get_enclosure_id(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'id': 'dae_1'}, {'key': 'dpe_dpe_1', 'id': 'dpe_1'})\n def test_get_enclosure_id(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['id'], self.client.get_enclosure_id(param_dict['key']))\n", "method_code": " def get_enclosure_id(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.id\n ", "context": "class UnityClient(object):\n @to_string\n def get_enclosure_id(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002020.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_name", "tests": "import unittest\n\nclass Test_get_enclosure_name(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'name': 'DAE 0 1'}, {'key': 'dpe_dpe_1', 'name': 'DPE 1'})\n def test_get_enclosure_name(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['name'], self.client.get_enclosure_name(param_dict['key']))\n", "method_code": " def get_enclosure_name(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_enclosure_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002021.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_model", "tests": "import unittest\n\nclass Test_get_enclosure_model(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'model': 'ANCHO LF 12G SAS DAE'}, {'key': 'dae_dae_2', 'model': NONE_STRING}, {'key': 'dpe_dpe_1', 'model': 'OBERON 25 DRIVE CHASSIS'}, {'key': 'dpe_dpe_2', 'model': NONE_STRING})\n def test_get_enclosure_model(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['model'], self.client.get_enclosure_model(param_dict['key']))\n", "method_code": " def get_enclosure_model(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.model\n ", "context": "class UnityClient(object):\n @to_string\n def get_enclosure_model(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002022.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_serial_number", "tests": "import unittest\n\nclass Test_get_enclosure_serial_number(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'emc_serial_number': 'CF22W145100058'}, {'key': 'dae_dae_2', 'emc_serial_number': NONE_STRING}, {'key': 'dpe_dpe_1', 'emc_serial_number': 'CF2CV145000001'}, {'key': 'dpe_dpe_2', 'emc_serial_number': NONE_STRING})\n def test_get_enclosure_serial_number(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['emc_serial_number'], self.client.get_enclosure_serial_number(param_dict['key']))\n", "method_code": " def get_enclosure_serial_number(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.emc_serial_number\n ", "context": "class UnityClient(object):\n @to_string\n def get_enclosure_serial_number(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002023.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_part_number", "tests": "import unittest\n\nclass Test_get_enclosure_part_number(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'emc_part_number': '100-900-000-04'}, {'key': 'dae_dae_2', 'emc_part_number': NONE_STRING}, {'key': 'dpe_dpe_1', 'emc_part_number': '100-542-901-05'}, {'key': 'dpe_dpe_2', 'emc_part_number': NONE_STRING})\n def test_get_enclosure_part_number(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['emc_part_number'], self.client.get_enclosure_part_number(param_dict['key']))\n", "method_code": " def get_enclosure_part_number(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.emc_part_number\n ", "context": "class UnityClient(object):\n @to_string\n def get_enclosure_part_number(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002024.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_health_status", "tests": "import unittest\n\nclass Test_get_enclosure_health_status(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'health': 'OK'}, {'key': 'dae_dae_2', 'health': NONE_STRING}, {'key': 'dpe_dpe_1', 'health': 'CRITICAL'}, {'key': 'dpe_dpe_2', 'health': NONE_STRING})\n def test_get_enclosure_health_status(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['health'], self.client.get_enclosure_health_status(param_dict['key']))\n", "method_code": " def get_enclosure_health_status(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_enclosure_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002025.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_current_power", "tests": "import unittest\n\nclass Test_get_enclosure_current_power(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'current_power': '430'}, {'key': 'dae_dae_2', 'current_power': '0'}, {'key': 'dpe_dpe_1', 'current_power': '0'}, {'key': 'dpe_dpe_2', 'current_power': NONE_STRING})\n def test_get_enclosure_current_power(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['current_power'], self.client.get_enclosure_current_power(param_dict['key']))\n", "method_code": " def get_enclosure_current_power(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.current_power\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_enclosure_current_power(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002026.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_avg_power", "tests": "import unittest\n\nclass Test_get_enclosure_avg_power(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'avg_power': '428'}, {'key': 'dae_dae_2', 'avg_power': '0'}, {'key': 'dpe_dpe_1', 'avg_power': '0'}, {'key': 'dpe_dpe_2', 'avg_power': NONE_STRING})\n def test_get_enclosure_avg_power(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['avg_power'], self.client.get_enclosure_avg_power(param_dict['key']))\n", "method_code": " def get_enclosure_avg_power(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.avg_power\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_enclosure_avg_power(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002027.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_max_power", "tests": "import unittest\n\nclass Test_get_enclosure_max_power(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'max_power': '458'}, {'key': 'dae_dae_2', 'max_power': '0'}, {'key': 'dpe_dpe_1', 'max_power': '0'}, {'key': 'dpe_dpe_2', 'max_power': NONE_STRING})\n def test_get_enclosure_max_power(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['max_power'], self.client.get_enclosure_max_power(param_dict['key']))\n", "method_code": " def get_enclosure_max_power(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.max_power\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_enclosure_max_power(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002028.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_current_temperature", "tests": "import unittest\n\nclass Test_get_enclosure_current_temperature(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'current_temperature': '26'}, {'key': 'dae_dae_2', 'current_temperature': '0'}, {'key': 'dpe_dpe_1', 'current_temperature': '0'}, {'key': 'dpe_dpe_2', 'current_temperature': NONE_STRING})\n def test_get_enclosure_current_temperature(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['current_temperature'], self.client.get_enclosure_current_temperature(param_dict['key']))\n", "method_code": " def get_enclosure_current_temperature(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.current_temperature\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_enclosure_current_temperature(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002029.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_avg_temperature", "tests": "import unittest\n\nclass Test_get_enclosure_avg_temperature(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'avg_temperature': '25'}, {'key': 'dae_dae_2', 'avg_temperature': '0'}, {'key': 'dpe_dpe_1', 'avg_temperature': '0'}, {'key': 'dpe_dpe_2', 'avg_temperature': NONE_STRING})\n def test_get_enclosure_avg_temperature(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['avg_temperature'], self.client.get_enclosure_avg_temperature(param_dict['key']))\n", "method_code": " def get_enclosure_avg_temperature(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.avg_temperature\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_enclosure_avg_temperature(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002030.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_enclosure_max_temperature", "tests": "import unittest\n\nclass Test_get_enclosure_max_temperature(unittest.TestCase):\n @ddt.data({'key': 'dae_dae_1', 'max_temperature': '30'}, {'key': 'dae_dae_2', 'max_temperature': '0'}, {'key': 'dpe_dpe_1', 'max_temperature': '0'}, {'key': 'dpe_dpe_2', 'max_temperature': NONE_STRING})\n def test_get_enclosure_max_temperature(self, param_dict):\n self.client.get_enclosures()\n self.assertEqual(param_dict['max_temperature'], self.client.get_enclosure_max_temperature(param_dict['key']))\n", "method_code": " def get_enclosure_max_temperature(self, id):\n enclosure = self._get_enclosure(id)\n return enclosure.max_temperature\n ", "context": "class UnityClient(object):\n @to_string\n @to_number\n def get_enclosure_max_temperature(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002031.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_power_supplies", "tests": "import unittest\n\nclass Test_get_power_supplies(unittest.TestCase):\n def test_get_power_supplies(self):\n items = self.client.get_power_supplies()\n self.assertEqual(2, len(items))\n self.assertEqual({'power_a', 'power_b'}, set(items))\n", "method_code": " def get_power_supplies(self):\n self.power_supplies = {power_supply.id: power_supply for power_supply in self.unity_system.get_power_supply()}\n return self.power_supplies.keys()\n ", "context": "class UnityClient(object):\n def get_power_supplies(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_power_supplies", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002032.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_power_supply_name", "tests": "import unittest\n\nclass Test_get_power_supply_name(unittest.TestCase):\n @ddt.data({'key': 'power_a', 'name': 'DPE Power Supply A0'}, {'key': 'power_b', 'name': NONE_STRING})\n def test_get_power_supply_name(self, param_dict):\n self.client.get_power_supplies()\n self.assertEqual(param_dict['name'], self.client.get_power_supply_name(param_dict['key']))\n", "method_code": " def get_power_supply_name(self, id):\n power_supply = self._get_power_supply(id)\n return power_supply.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_power_supply_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002033.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_power_supply_manufacturer", "tests": "import unittest\n\nclass Test_get_power_supply_manufacturer(unittest.TestCase):\n @ddt.data({'key': 'power_a', 'manufacturer': 'FLEXTRONICS POWER INC.'}, {'key': 'power_b', 'manufacturer': NONE_STRING})\n def test_get_power_supply_manufacturer(self, param_dict):\n self.client.get_power_supplies()\n self.assertEqual(param_dict['manufacturer'], self.client.get_power_supply_manufacturer(param_dict['key']))\n", "method_code": " def get_power_supply_manufacturer(self, id):\n power_supply = self._get_power_supply(id)\n return power_supply.manufacturer\n ", "context": "class UnityClient(object):\n @to_string\n def get_power_supply_manufacturer(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002034.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_power_supply_model", "tests": "import unittest\n\nclass Test_get_power_supply_model(unittest.TestCase):\n @ddt.data({'key': 'power_a', 'model': '12V P/S WITH 12VSTBY AND FAN'}, {'key': 'power_b', 'model': NONE_STRING})\n def test_get_power_supply_model(self, param_dict):\n self.client.get_power_supplies()\n self.assertEqual(param_dict['model'], self.client.get_power_supply_model(param_dict['key']))\n", "method_code": " def get_power_supply_model(self, id):\n power_supply = self._get_power_supply(id)\n return power_supply.model\n ", "context": "class UnityClient(object):\n @to_string\n def get_power_supply_model(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002035.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_power_supply_firmware_version", "tests": "import unittest\n\nclass Test_get_power_supply_firmware_version(unittest.TestCase):\n @ddt.data({'key': 'power_a', 'firmware_version': '0501'}, {'key': 'power_b', 'firmware_version': NONE_STRING})\n def test_get_power_supply_firmware_version(self, param_dict):\n self.client.get_power_supplies()\n self.assertEqual(param_dict['firmware_version'], self.client.get_power_supply_firmware_version(param_dict['key']))\n", "method_code": " def get_power_supply_firmware_version(self, id):\n power_supply = self._get_power_supply(id)\n return power_supply.firmware_version\n ", "context": "class UnityClient(object):\n @to_string\n def get_power_supply_firmware_version(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002036.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_power_supply_parent_enclosure", "tests": "import unittest\n\nclass Test_get_power_supply_parent_enclosure(unittest.TestCase):\n @ddt.data({'key': 'power_a', 'parent_enclosure': 'DPE, DAE'}, {'key': 'power_b', 'parent_enclosure': NONE_STRING})\n def test_get_power_supply_parent_enclosure(self, param_dict):\n self.client.get_power_supplies()\n self.assertEqual(param_dict['parent_enclosure'], self.client.get_power_supply_parent_enclosure(param_dict['key']))\n", "method_code": " def get_power_supply_parent_enclosure(self, id):\n power_supply = self._get_power_supply(id)\n parents = []\n if hasattr(power_supply, 'parent_dpe') and power_supply.parent_dpe:\n parents.append(power_supply.parent_dpe)\n if hasattr(power_supply, 'parent_dae') and power_supply.parent_dae:\n parents.append(power_supply.parent_dae)\n if parents:\n return ', '.join((x.name for x in parents))\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_power_supply_parent_enclosure(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002037.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_power_supply_sp", "tests": "import unittest\n\nclass Test_get_power_supply_sp(unittest.TestCase):\n @ddt.data({'key': 'power_a', 'storage_processor': 'SP A'}, {'key': 'power_b', 'storage_processor': NONE_STRING})\n def test_get_power_supply_sp(self, param_dict):\n self.client.get_power_supplies()\n self.assertEqual(param_dict['storage_processor'], self.client.get_power_supply_sp(param_dict['key']))\n", "method_code": " def get_power_supply_sp(self, id):\n power_supply = self._get_power_supply(id)\n return power_supply.storage_processor.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_power_supply_sp(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002038.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_power_supply_health_status", "tests": "import unittest\n\nclass Test_get_power_supply_health_status(unittest.TestCase):\n @ddt.data({'key': 'power_a', 'health': 'OK'}, {'key': 'power_b', 'health': NONE_STRING})\n def test_get_power_supply_health_status(self, param_dict):\n self.client.get_power_supplies()\n self.assertEqual(param_dict['health'], self.client.get_power_supply_health_status(param_dict['key']))\n", "method_code": " def get_power_supply_health_status(self, id):\n power_supply = self._get_power_supply(id)\n return power_supply.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_power_supply_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002039.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_fans", "tests": "import unittest\n\nclass Test_get_fans(unittest.TestCase):\n def test_get_fans(self):\n items = self.client.get_fans()\n self.assertEqual(4, len(items))\n self.assertEqual({'fan_a0', 'fan_a1', 'fan_a2', 'fan_b1'}, set(items))\n", "method_code": " def get_fans(self):\n self.fans = {fan.id: fan for fan in self.unity_system.get_fan()}\n return self.fans.keys()\n ", "context": "class UnityClient(object):\n def get_fans(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_fans", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002040.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_fan_name", "tests": "import unittest\n\nclass Test_get_fan_name(unittest.TestCase):\n @ddt.data({'key': 'fan_a0', 'name': 'DPE Cooling Module A0'}, {'key': 'fan_a1', 'name': NONE_STRING})\n def test_get_fan_name(self, param_dict):\n self.client.get_fans()\n self.assertEqual(param_dict['name'], self.client.get_fan_name(param_dict['key']))\n", "method_code": " def get_fan_name(self, id):\n fan = self._get_fan(id)\n return fan.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_fan_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002041.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_fan_slot_number", "tests": "import unittest\n\nclass Test_get_fan_slot_number(unittest.TestCase):\n @ddt.data({'key': 'fan_a0', 'slot_number': '0'}, {'key': 'fan_b1', 'slot_number': 'None'})\n def test_get_fan_slot_number(self, param_dict):\n self.client.get_fans()\n self.assertEqual(param_dict['slot_number'], self.client.get_fan_slot_number(param_dict['key']))\n", "method_code": " def get_fan_slot_number(self, id):\n fan = self._get_fan(id)\n return fan.slot_number\n ", "context": "class UnityClient(object):\n @to_string\n def get_fan_slot_number(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002042.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_fan_parent_enclosure", "tests": "import unittest\n\nclass Test_get_fan_parent_enclosure(unittest.TestCase):\n @ddt.data({'key': 'fan_a0', 'parent_enclosure': 'DPE, DAE 0 1'}, {'key': 'fan_a1', 'parent_enclosure': 'DPE'}, {'key': 'fan_a2', 'parent_enclosure': 'DAE 0 1'}, {'key': 'fan_b1', 'parent_enclosure': NONE_STRING})\n def test_get_fan_parent_enclosure(self, param_dict):\n self.client.get_fans()\n self.assertEqual(param_dict['parent_enclosure'], self.client.get_fan_parent_enclosure(param_dict['key']))\n", "method_code": " def get_fan_parent_enclosure(self, id):\n fan = self._get_fan(id)\n parents = []\n if hasattr(fan, 'parent_dpe') and fan.parent_dpe:\n parents.append(fan.parent_dpe)\n if hasattr(fan, 'parent_dae') and fan.parent_dae:\n parents.append(fan.parent_dae)\n if parents:\n return ', '.join((x.name for x in parents))\n else:\n return NONE_STRING\n ", "context": "class UnityClient(object):\n @to_string\n def get_fan_parent_enclosure(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002043.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_fan_health_status", "tests": "import unittest\n\nclass Test_get_fan_health_status(unittest.TestCase):\n @ddt.data({'key': 'fan_a0', 'health': 'OK'}, {'key': 'fan_b1', 'health': NONE_STRING})\n def test_get_fan_health_status(self, param_dict):\n self.client.get_fans()\n self.assertEqual(param_dict['health'], self.client.get_fan_health_status(param_dict['key']))\n", "method_code": " def get_fan_health_status(self, id):\n fan = self._get_fan(id)\n return fan.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_fan_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002044.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_bbus", "tests": "import unittest\n\nclass Test_get_bbus(unittest.TestCase):\n def test_get_bbus(self):\n items = self.client.get_bbus()\n self.assertEqual(2, len(items))\n self.assertEqual({'battery_spa', 'battery_spb'}, set(items))\n", "method_code": " def get_bbus(self):\n self.bbus = {bbu.id: bbu for bbu in self.unity_system.get_battery()}\n return self.bbus.keys()\n ", "context": "class UnityClient(object):\n def get_bbus(self): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_get_bbus", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002045.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_bbu_name", "tests": "import unittest\n\nclass Test_get_bbu_name(unittest.TestCase):\n @ddt.data({'key': 'battery_spa', 'name': 'SP A Battery 0'}, {'key': 'battery_spb', 'name': NONE_STRING})\n def test_get_bbu_name(self, param_dict):\n self.client.get_bbus()\n self.assertEqual(param_dict['name'], self.client.get_bbu_name(param_dict['key']))\n", "method_code": " def get_bbu_name(self, id):\n bbu = self._get_bbu(id)\n return bbu.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_bbu_name(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002046.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_bbu_manufacturer", "tests": "import unittest\n\nclass Test_get_bbu_manufacturer(unittest.TestCase):\n @ddt.data({'key': 'battery_spa', 'manufacturer': 'ACBEL POLYTECH INC.'}, {'key': 'battery_spb', 'manufacturer': NONE_STRING})\n def test_get_bbu_manufacturer(self, param_dict):\n self.client.get_bbus()\n self.assertEqual(param_dict['manufacturer'], self.client.get_bbu_manufacturer(param_dict['key']))\n", "method_code": " def get_bbu_manufacturer(self, id):\n bbu = self._get_bbu(id)\n return bbu.manufacturer\n ", "context": "class UnityClient(object):\n @to_string\n def get_bbu_manufacturer(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002047.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_bbu_model", "tests": "import unittest\n\nclass Test_get_bbu_model(unittest.TestCase):\n @ddt.data({'key': 'battery_spa', 'model': 'LITHIUM-ION, UNIVERSAL BOB'}, {'key': 'battery_spb', 'model': NONE_STRING})\n def test_get_bbu_model(self, param_dict):\n self.client.get_bbus()\n self.assertEqual(param_dict['model'], self.client.get_bbu_model(param_dict['key']))\n", "method_code": " def get_bbu_model(self, id):\n bbu = self._get_bbu(id)\n return bbu.model\n ", "context": "class UnityClient(object):\n @to_string\n def get_bbu_model(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002048.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_bbu_firmware_version", "tests": "import unittest\n\nclass Test_get_bbu_firmware_version(unittest.TestCase):\n @ddt.data({'key': 'battery_spa', 'firmware_version': '073.91'}, {'key': 'battery_spb', 'firmware_version': NONE_STRING})\n def test_get_bbu_firmware_version(self, param_dict):\n self.client.get_bbus()\n self.assertEqual(param_dict['firmware_version'], self.client.get_bbu_firmware_version(param_dict['key']))\n", "method_code": " def get_bbu_firmware_version(self, id):\n bbu = self._get_bbu(id)\n return bbu.firmware_version\n ", "context": "class UnityClient(object):\n @to_string\n def get_bbu_firmware_version(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002049.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_bbu_parent_sp", "tests": "import unittest\n\nclass Test_get_bbu_parent_sp(unittest.TestCase):\n @ddt.data({'key': 'battery_spa', 'parent_storage_processor': 'SP A'}, {'key': 'battery_spb', 'parent_storage_processor': NONE_STRING})\n def test_get_bbu_parent_sp(self, param_dict):\n self.client.get_bbus()\n self.assertEqual(param_dict['parent_storage_processor'], self.client.get_bbu_parent_sp(param_dict['key']))\n", "method_code": " def get_bbu_parent_sp(self, id):\n bbu = self._get_bbu(id)\n return bbu.parent_storage_processor.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_bbu_parent_sp(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_health_status(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002050.py"} {"focal_file": "snmpagent_unity/clients.py", "focal_class": null, "focal_method": "get_bbu_health_status", "tests": "import unittest\n\nclass Test_get_bbu_health_status(unittest.TestCase):\n @ddt.data({'key': 'battery_spa', 'health': 'OK'}, {'key': 'battery_spb', 'health': NONE_STRING})\n def test_get_bbu_health_status(self, param_dict):\n self.client.get_bbus()\n self.assertEqual(param_dict['health'], self.client.get_bbu_health_status(param_dict['key']))\n", "method_code": " def get_bbu_health_status(self, id):\n bbu = self._get_bbu(id)\n return bbu.health.value.name\n ", "context": "class UnityClient(object):\n @to_string\n def get_bbu_health_status(self, id): ...\n def __init__(self, host=None, username=None, password=None, port=443, cache_interval=None): ...\n def get_unity_client(cls, name, *args, **kwargs): ...\n def get_agent_version(self): ...\n def get_mib_version(self): ...\n def get_manufacturer(self): ...\n def get_model(self): ...\n def get_serial_number(self): ...\n def get_operation_environment_version(self): ...\n def get_mgmt_ip(self): ...\n def get_current_power(self): ...\n def get_avg_power(self): ...\n def get_number_of_sp(self): ...\n def get_number_of_enclosure(self): ...\n def get_number_of_power_supply(self): ...\n def get_number_of_fan(self): ...\n def get_number_of_disk(self): ...\n def get_number_of_frontend_port(self): ...\n def get_number_of_backend_port(self): ...\n def get_total_capacity(self): ...\n def get_used_capacity(self): ...\n def get_free_capacity(self): ...\n def get_total_iops(self): ...\n def get_read_iops(self): ...\n def get_write_iops(self): ...\n def get_total_byte_rate(self): ...\n def get_read_byte_rate(self): ...\n def get_write_byte_rate(self): ...\n def get_sps(self): ...\n def _get_sp(self, id): ...\n def get_sp_name(self, id): ...\n def get_sp_serial_number(self, id): ...\n def get_sp_health_status(self, id): ...\n def get_sp_utilization(self, id): ...\n def get_sp_block_total_iops(self, id): ...\n def get_sp_block_read_iops(self, id): ...\n def get_sp_block_write_iops(self, id): ...\n def get_sp_total_byte_rate(self, id): ...\n def get_sp_read_byte_rate(self, id): ...\n def get_sp_write_byte_rate(self, id): ...\n def get_sp_cache_dirty_size(self, id): ...\n def get_sp_block_cache_read_hit_ratio(self, id): ...\n def get_sp_block_cache_write_hit_ratio(self, id): ...\n def get_sp_fast_cache_read_hits(self, id): ...\n def get_sp_fast_cache_write_hits(self, id): ...\n def get_sp_fast_cache_read_hit_rate(self, id): ...\n def get_sp_fast_cache_write_hit_rate(self, id): ...\n def get_pools(self): ...\n def _get_pool(self, id): ...\n def get_pool_name(self, id): ...\n def get_pool_disk_types(self, id): ...\n def get_pool_raid_levels(self, id): ...\n def get_pool_fast_cache_status(self, id): ...\n def get_pool_number_of_disk(self, id): ...\n def get_pool_size_total(self, id): ...\n def get_pool_size_free(self, id): ...\n def get_pool_size_used(self, id): ...\n def get_pool_size_ultilization(self, id): ...\n def get_luns(self): ...\n def _get_lun(self, id): ...\n def get_lun_name(self, id): ...\n def get_lun_raid_type(self, id): ...\n def get_lun_size_allocated(self, id): ...\n def get_lun_size_total(self, id): ...\n def get_lun_health_status(self, id): ...\n def get_lun_fast_cache_status(self, id): ...\n def get_lun_default_sp(self, id): ...\n def get_lun_current_sp(self, id): ...\n def get_lun_response_time(self, id): ...\n def get_lun_queue_length(self, id): ...\n def get_lun_total_iops(self, id): ...\n def get_lun_read_iops(self, id): ...\n def get_lun_write_iops(self, id): ...\n def get_lun_total_byte_rate(self, id): ...\n def get_lun_read_byte_rate(self, id): ...\n def get_lun_write_byte_rate(self, id): ...\n def get_lun_utilization(self, id): ...\n def get_lun_host_access(self, id): ...\n def get_disks(self): ...\n def _get_disk(self, id): ...\n def get_disk_name(self, id): ...\n def get_disk_model(self, id): ...\n def get_disk_serial_number(self, id): ...\n def get_disk_version(self, id): ...\n def get_disk_type(self, id): ...\n def get_disk_slot_number(self, id): ...\n def get_disk_health_status(self, id): ...\n def get_disk_raw_size(self, id): ...\n def get_disk_current_pool(self, id): ...\n def get_disk_response_time(self, id): ...\n def get_disk_queue_length(self, id): ...\n def get_disk_total_iops(self, id): ...\n def get_disk_read_iops(self, id): ...\n def get_disk_write_iops(self, id): ...\n def get_disk_total_byte_rate(self, id): ...\n def get_disk_read_byte_rate(self, id): ...\n def get_disk_write_byte_rate(self, id): ...\n def get_disk_utilization(self, id): ...\n def get_frontend_ports(self): ...\n def _get_frontend_port(self, id): ...\n def get_frontend_port_id(self, id): ...\n def get_frontend_port_name(self, id): ...\n def get_frontend_port_address(self, id): ...\n def get_frontend_port_type(self, id): ...\n def get_frontend_port_current_speed(self, id): ...\n def get_frontend_port_supported_speed(self, id): ...\n def get_frontend_port_health_status(self, id): ...\n def get_frontend_port_total_iops(self, id): ...\n def get_frontend_port_read_iops(self, id): ...\n def get_frontend_port_write_iops(self, id): ...\n def get_frontend_port_total_byte_rate(self, id): ...\n def get_frontend_port_read_byte_rate(self, id): ...\n def get_frontend_port_write_byte_rate(self, id): ...\n def get_backend_ports(self): ...\n def _get_backend_port(self, id): ...\n def get_backend_port_name(self, id): ...\n def get_backend_port_type(self, id): ...\n def get_backend_port_port_number(self, id): ...\n def get_backend_port_current_speed(self, id): ...\n def get_backend_port_parent_io_module(self, id): ...\n def get_backend_port_parent_sp(self, id): ...\n def get_backend_port_health_status(self, id): ...\n def get_hosts(self): ...\n def _get_host(self, id): ...\n def get_host_name(self, id): ...\n def get_host_network_address(self, id): ...\n def get_host_initiators(self, id): ...\n def get_host_os_type(self, id): ...\n def get_host_assigned_volumes(self, id): ...\n def get_enclosures(self): ...\n def _get_enclosure(self, id): ...\n def get_enclosure_id(self, id): ...\n def get_enclosure_name(self, id): ...\n def get_enclosure_model(self, id): ...\n def get_enclosure_serial_number(self, id): ...\n def get_enclosure_part_number(self, id): ...\n def get_enclosure_health_status(self, id): ...\n def get_enclosure_current_power(self, id): ...\n def get_enclosure_avg_power(self, id): ...\n def get_enclosure_max_power(self, id): ...\n def get_enclosure_current_temperature(self, id): ...\n def get_enclosure_avg_temperature(self, id): ...\n def get_enclosure_max_temperature(self, id): ...\n def get_power_supplies(self): ...\n def _get_power_supply(self, id): ...\n def get_power_supply_name(self, id): ...\n def get_power_supply_manufacturer(self, id): ...\n def get_power_supply_model(self, id): ...\n def get_power_supply_firmware_version(self, id): ...\n def get_power_supply_parent_enclosure(self, id): ...\n def get_power_supply_sp(self, id): ...\n def get_power_supply_health_status(self, id): ...\n def get_fans(self): ...\n def _get_fan(self, id): ...\n def get_fan_name(self, id): ...\n def get_fan_slot_number(self, id): ...\n def get_fan_parent_enclosure(self, id): ...\n def get_fan_health_status(self, id): ...\n def get_bbus(self): ...\n def _get_bbu(self, id): ...\n def get_bbu_name(self, id): ...\n def get_bbu_manufacturer(self, id): ...\n def get_bbu_model(self, id): ...\n def get_bbu_firmware_version(self, id): ...\n def get_bbu_parent_sp(self, id): ...\n\n self.unity_system = storops.UnitySystem(host=host, username=username, password=password, port=port, retries=0, cache_interval=cache_interval)\n\n manager = CachedUnityClientManager()\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002051.py"} {"focal_file": "snmpagent_unity/agentd.py", "focal_class": null, "focal_method": "exists", "tests": "import unittest\n\nclass Test_exists(unittest.TestCase):\n @patches.psutil_process\n @patches.patch_get_pid_file\n def test_already_exists(self, fake_process):\n pid_file = agentd.WindowsDaemon.get_pid_file()\n self.addCleanup(cleanup_pid, pid_file)\n fake_process().cmdline = mock.Mock(return_value=['python', 'snmpagent_unity/agentd.py'])\n with open(pid_file, 'w') as f:\n f.write('1111')\n r = agentd.WindowsDaemon.exists()\n self.assertIsNotNone(r)\n", "method_code": " def exists(cls):\n pid_file = cls.get_pid_file()\n if os.path.exists(pid_file) and os.path.isfile(pid_file):\n with open(pid_file, 'r') as f:\n pid = int(f.read().splitlines()[0])\n try:\n process = psutil.Process(pid=pid)\n params = process.cmdline()\n if 'agentd.py' in params[1]:\n LOG.debug('The {} process(pid={}) is already running.'.format(SERVICE_NAME, pid))\n return process\n except psutil.NoSuchProcess:\n LOG.debug('The {} process(pid={}) is not running.'.format(SERVICE_NAME, pid))\n else:\n LOG.debug(\"The process(pid={}) doesn't look like a {} service. Not stopping it.\".format(pid, SERVICE_NAME))\n return None\n ", "context": "class BaseDaemon(object):\n @classmethod\n def exists(cls): ...\n def validate_conf(cls, agent_conf_file): ...\n def get_running_conf(cls): ...\n def get_pid_file(cls): ...\n def _launch_process(cls, conf_file): ...\n def start(cls, conf_file): ...\n def stop(cls): ...\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002052.py"} {"focal_file": "snmpagent_unity/agentd.py", "focal_class": null, "focal_method": "start", "tests": "import unittest\n\nclass Test_start(unittest.TestCase):\n @patches.subprocess\n @patches.patch_get_access_path()\n @patches.patch_get_pid_file\n def test_start(self, fake_popen):\n pid_file = agentd.WindowsDaemon.get_pid_file()\n self.addCleanup(cleanup_pid, pid_file)\n agentd.LinuxDaemon.start(self.default_agent_conf)\n self.assertEqual(sys.executable, fake_popen.args[0][0])\n self.assertEqual(self.default_agent_conf, fake_popen.args[0][2])\n", "method_code": " def start(cls, conf_file):\n p = cls.exists()\n if p:\n LOG.info('The {} Agent(pid={}) is already running. Not starting new one.'.format(SERVICE_NAME, p.pid))\n return 1\n cls.validate_conf(conf_file)\n p = cls._launch_process(conf_file)\n pid = p.pid\n LOG.info('Service {}(pid={}) started.'.format(SERVICE_NAME, pid))\n with open(cls.get_pid_file(), 'w') as f:\n f.write(str(pid))\n LOG.debug('{} is running with pid file: {}'.format(SERVICE_NAME, cls.get_pid_file()))\n return 0\n ", "context": "class BaseDaemon(object):\n @classmethod\n def start(cls, conf_file): ...\n def validate_conf(cls, agent_conf_file): ...\n def exists(cls): ...\n def get_running_conf(cls): ...\n def get_pid_file(cls): ...\n def _launch_process(cls, conf_file): ...\n def stop(cls): ...\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002053.py"} {"focal_file": "snmpagent_unity/agentd.py", "focal_class": null, "focal_method": "stop", "tests": "import unittest\n\nclass Test_stop(unittest.TestCase):\n @patches.psutil_process\n @patches.patch_get_pid_file\n def test_stop(self, fake_process):\n pid_file = agentd.WindowsDaemon.get_pid_file()\n self.addCleanup(cleanup_pid, pid_file)\n with open(pid_file, 'w') as f:\n f.write('1111')\n fake_process().cmdline = mock.Mock(return_value=['python', 'snmpagent_unity/agentd.py'])\n r = agentd.WindowsDaemon.stop()\n self.assertEqual(0, r)\n fake_process().terminate.assert_called_with()\n", "method_code": " def stop(cls):\n process = cls.exists()\n if process:\n try:\n process.terminate()\n LOG.info('Service {}(pid={}) stopped successfully.'.format(SERVICE_NAME, process.pid))\n ret = 0\n os.remove(cls.get_pid_file())\n except Exception as ex:\n LOG.error('Unable to kill {}(pid={}) : {}'.format(SERVICE_NAME, process.pid, ex))\n ret = 1\n else:\n LOG.info('Agent service does not exist, not started yet?')\n ret = 2\n return ret\n ", "context": "class BaseDaemon(object):\n @classmethod\n def stop(cls): ...\n def validate_conf(cls, agent_conf_file): ...\n def exists(cls): ...\n def get_running_conf(cls): ...\n def get_pid_file(cls): ...\n def _launch_process(cls, conf_file): ...\n def start(cls, conf_file): ...\n", "repository": "emc-openstack/snmp-agent", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002054.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "add_user", "tests": "import unittest\n\nclass Test_add_user(unittest.TestCase):\n def test_add_user(self):\n r = self.helper.add_user('for_test', 'MD5', 'password', 'DES', 'password')\n self.assertEqual(0, r)\n", "method_code": " def add_user(self, name, auth, auth_key, private=None, private_key=None):\n cmd = ['add-user', '--name', name, '--auth', auth, '--auth_key', auth_key]\n if private:\n cmd.extend(['--priv', private])\n if private_key:\n cmd.extend(['--priv_key', private_key])\n return cmd\n ", "context": "class Helper(object):\n @utils.cli_executor\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def __init__(self, conf_file=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def create_community(self, name): ...\n def delete_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def start_service(self): ...\n def stop_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_add_user", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002055.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "update_user", "tests": "import unittest\n\nclass Test_update_user(unittest.TestCase):\n def test_update_user(self):\n self.helper.add_user('for_update', 'SHA', 'password', 'AES', 'password')\n r = self.helper.update_user('for_update', 'SHA', 'password')\n self.assertEqual(0, r)\n", "method_code": " def update_user(self, name, auth, auth_key, private=None, private_key=None):\n cmd = ['update-user', '--name', name, '--auth', auth, '--auth_key', auth_key]\n if private:\n cmd.extend(['--priv', private])\n if private_key:\n cmd.extend(['--priv_key', private_key])\n return cmd\n ", "context": "class Helper(object):\n @utils.cli_executor\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def create_community(self, name): ...\n def delete_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def start_service(self): ...\n def stop_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_update_user", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002056.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "delete_user", "tests": "import unittest\n\nclass Test_delete_user(unittest.TestCase):\n def test_delete_user(self):\n self.helper.add_user('for_delete', 'SHA', 'password', 'AES', 'password')\n r = self.helper.delete_user('for_delete')\n self.assertEqual(0, r)\n", "method_code": " def delete_user(self, name):\n return ['delete-user', '--name', name]\n ", "context": "class Helper(object):\n @utils.cli_executor\n def delete_user(self, name): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def create_community(self, name): ...\n def delete_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def start_service(self): ...\n def stop_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_delete_user", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002057.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "create_community", "tests": "import unittest\n\nclass Test_create_community(unittest.TestCase):\n def test_create_community(self):\n r = self.helper.create_community('new_user')\n self.assertEqual(0, r)\n\n def test_create_community_already_exists(self):\n self.helper.create_community('first')\n r = self.helper.create_community('first')\n self.assertNotEqual(0, r)\n", "method_code": " def create_community(self, name):\n return ['create-community', '--name', name]\n ", "context": "class Helper(object):\n @utils.cli_executor\n def create_community(self, name): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def delete_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def start_service(self): ...\n def stop_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_create_community", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002058.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "delete_community", "tests": "import unittest\n\nclass Test_delete_community(unittest.TestCase):\n def test_delete_community(self):\n self.helper.create_community('to_delete')\n r = self.helper.delete_community('to_delete')\n self.assertEqual(0, r)\n", "method_code": " def delete_community(self, name):\n return ['delete-community', '--name', name]\n ", "context": "class Helper(object):\n @utils.cli_executor\n def delete_community(self, name): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def create_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def start_service(self): ...\n def stop_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_delete_community", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002059.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "list_users", "tests": "import unittest\n\nclass Test_list_users(unittest.TestCase):\n def test_list_users(self):\n self.helper.create_community('dummy_1')\n self.helper.create_community('dummy_2')\n r = self.helper.list_users()\n self.assertEqual(0, r)\n", "method_code": " def list_users(self):\n return ['list-users']\n ", "context": "class Helper(object):\n @utils.cli_executor\n def list_users(self): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def create_community(self, name): ...\n def delete_community(self, name): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def start_service(self): ...\n def stop_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_list_users", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002060.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "decrypt", "tests": "import unittest\n\nclass Test_decrypt(unittest.TestCase):\n def test_decrypt(self):\n _, tmp_file = self._create_encrypt_file()\n self.helper.decrypt(tmp_file)\n", "method_code": " def decrypt(self, conf_file=None):\n if not conf_file:\n conf_file = self.conf_file\n return ['decrypt', '--conf_file', conf_file]\n ", "context": "class Helper(object):\n @utils.cli_executor\n def decrypt(self, conf_file=None): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def create_community(self, name): ...\n def delete_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def start_service(self): ...\n def stop_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_decrypt", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002061.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "start_service", "tests": "import unittest\n\nclass Test_start_service(unittest.TestCase):\n def test_start_service(self):\n self.helper.create_community('for_start')\n r = self.helper.start_service()\n self.assertEqual(0, r)\n self.addCleanup(self.helper.stop_service)\n\n def test_restart_service(self):\n self.helper.create_community('for_restart')\n self.helper.start_service()\n r = self.helper.restart_service()\n self.assertEqual(0, r)\n self.addCleanup(self.helper.stop_service)\n", "method_code": " def start_service(self):\n return ['start', '--conf_file', self.conf_file]\n ", "context": "class Helper(object):\n @utils.cli_executor\n def start_service(self): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def create_community(self, name): ...\n def delete_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def stop_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_start_service", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002062.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "stop_service", "tests": "import unittest\n\nclass Test_stop_service(unittest.TestCase):\n def test_stop_service(self):\n self.helper.create_community('for_stop')\n self.helper.start_service()\n r = self.helper.stop_service()\n self.assertEqual(0, r)\n", "method_code": " def stop_service(self):\n return ['stop']\n ", "context": "class Helper(object):\n @utils.cli_executor\n def stop_service(self): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def create_community(self, name): ...\n def delete_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def start_service(self): ...\n def restart_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_stop_service", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002063.py"} {"focal_file": "snmpagent_unity/comptests/cli_helper.py", "focal_class": null, "focal_method": "restart_service", "tests": "import unittest\n\nclass Test_restart_service(unittest.TestCase):\n def test_restart_service_no_running(self):\n r = self.helper.restart_service()\n self.assertEqual(3, r)\n", "method_code": " def restart_service(self):\n return ['restart']\n ", "context": "class Helper(object):\n @utils.cli_executor\n def restart_service(self): ...\n def __init__(self, conf_file=None): ...\n def add_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def update_user(self, name, auth, auth_key, private=None, private_key=None): ...\n def delete_user(self, name): ...\n def create_community(self, name): ...\n def delete_community(self, name): ...\n def list_users(self): ...\n def encrypt(self, conf_file=None): ...\n def decrypt(self, conf_file=None): ...\n def start_service(self): ...\n def stop_service(self): ...\n def clear_access_data(cls): ...\n\n self.conf_file = conf_file\n", "repository": "emc-openstack/snmp-agent", "test_name": "test_restart_service_no_running", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002064.py"} {"focal_file": "wshubsapi/client_file_generator/client_file_generator.py", "focal_class": null, "focal_method": "_construct_api_path", "tests": "import unittest\n\nclass Test_construct_api_path(unittest.TestCase):\n def test_construct_api_path_returnParentPath(self):\n new_folder = os.path.join('test', 'new', 'folder', 'api.py')\n parent_path = ClientFileGenerator._construct_api_path(new_folder)\n self.assertEqual(parent_path, os.path.abspath(os.path.dirname(new_folder)))\n", "method_code": " def _construct_api_path(api_file_path):\n full_path = path.abspath(api_file_path)\n parent_dir = path.dirname(full_path)\n if not path.exists(parent_dir):\n os.makedirs(parent_dir)\n return parent_dir\n ", "context": "class ClientFileGenerator():\n @staticmethod\n def _construct_api_path(api_file_path): ...\n def __init__(self): ...\n", "repository": "JorgeGarciaIrazabal/WSHubsAPI", "test_name": "test_construct_api_path_returnParentPath", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002065.py"} {"focal_file": "wshubsapi/connected_clients_holder.py", "focal_class": null, "focal_method": "get_clients", "tests": "import unittest\n\nclass Test_get_clients(unittest.TestCase):\n def test_get_clients__returns_only_clients_with_even_ids(self):\n even_clients = self.clients_holder.get_clients(lambda x: x.ID % 2 == 0)\n self.assertEqual(len(list(even_clients)), 5)\n for client in even_clients:\n self.assertTrue(client.ID % 2 == 0)\n self.__check_clients_are_well_constructed(even_clients)\n", "method_code": " def get_clients(self, filter_function):\n clients = filter(filter_function, self.all_connected_clients.values())\n return ConnectedClientsGroup(list(clients), self.hub_name)\n ", "context": "class ConnectedClientsHolder():\n def get_clients(self, filter_function): ...\n def __init__(self, hub_instance): ...\n def get_all_clients(self): ...\n def get_other_clients(self, sender): ...\n def get_client(self, client_id): ...\n def get(self, filter_criteria): ...\n def get_subscribed_clients(self): ...\n def append_client(cls, client): ...\n def pop_client(cls, client_id): ...\n\n self.hub_instance = hub_instance\n self.hub_name = self.hub_instance.__class__.__HubName__\n self.hub_subscribers = []\n\n all_connected_clients = dict()\n", "repository": "JorgeGarciaIrazabal/WSHubsAPI", "test_name": "test_get_clients__returns_only_clients_with_even_ids", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002066.py"} {"focal_file": "wshubsapi/connected_clients_holder.py", "focal_class": null, "focal_method": "get_client", "tests": "import unittest\n\nclass Test_get_client(unittest.TestCase):\n def test_get_client__returns_client_with_ids(self):\n client3 = self.clients_holder.get_client(3)\n client5 = self.clients_holder.get_client(5)\n client7 = self.clients_holder.get_client(7)\n self.assertEqual(client3.ID, 3)\n self.assertEqual(client5.ID, 5)\n self.assertEqual(client7.ID, 7)\n", "method_code": " def get_client(self, client_id):\n \"\"\"\n :rtype: wshubsapi.client_in_hub.ClientInHub\n \"\"\"\n return ConnectedClientsGroup([self.all_connected_clients[client_id]], self.hub_name)[0]\n ", "context": "class ConnectedClientsHolder():\n def get_client(self, client_id): ...\n def __init__(self, hub_instance): ...\n def get_all_clients(self): ...\n def get_other_clients(self, sender): ...\n def get_clients(self, filter_function): ...\n def get(self, filter_criteria): ...\n def get_subscribed_clients(self): ...\n def append_client(cls, client): ...\n def pop_client(cls, client_id): ...\n\n self.hub_instance = hub_instance\n self.hub_name = self.hub_instance.__class__.__HubName__\n self.hub_subscribers = []\n\n all_connected_clients = dict()\n", "repository": "JorgeGarciaIrazabal/WSHubsAPI", "test_name": "test_get_client__returns_client_with_ids", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002067.py"} {"focal_file": "wshubsapi/connected_clients_holder.py", "focal_class": null, "focal_method": "get_subscribed_clients", "tests": "import unittest\n\nclass Test_get_subscribed_clients(unittest.TestCase):\n def test_get_subscribed_clients__returns_only_subscribed_clients(self):\n self.clients_holder.hub_instance.subscribe_to_hub(self.clients_holder.get_client(3))\n self.clients_holder.hub_instance.subscribe_to_hub(self.clients_holder.get_client(1))\n subscribed_clients = self.clients_holder.get_subscribed_clients()\n self.assertEqual(len(list(subscribed_clients)), 2)\n self.assertTrue(subscribed_clients[0].ID == 3)\n self.assertTrue(subscribed_clients[1].ID == 1)\n self.__check_clients_are_well_constructed(subscribed_clients)\n", "method_code": " def get_subscribed_clients(self):\n self.hub_subscribers = list(filter(lambda c: not c.api_is_closed, self.hub_subscribers))\n return ConnectedClientsGroup(self.hub_subscribers, self.hub_name)\n ", "context": "class ConnectedClientsHolder():\n def get_subscribed_clients(self): ...\n def __init__(self, hub_instance): ...\n def get_all_clients(self): ...\n def get_other_clients(self, sender): ...\n def get_clients(self, filter_function): ...\n def get_client(self, client_id): ...\n def get(self, filter_criteria): ...\n def append_client(cls, client): ...\n def pop_client(cls, client_id): ...\n\n self.hub_instance = hub_instance\n self.hub_name = self.hub_instance.__class__.__HubName__\n self.hub_subscribers = []\n\n all_connected_clients = dict()\n", "repository": "JorgeGarciaIrazabal/WSHubsAPI", "test_name": "test_get_subscribed_clients__returns_only_subscribed_clients", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002068.py"} {"focal_file": "wshubsapi/connected_clients_holder.py", "focal_class": null, "focal_method": "get_all_clients", "tests": "import unittest\n\nclass Test_get_all_clients(unittest.TestCase):\n def test_pop_client_removes_a_client_if_exists(self):\n old_clients_length = len(self.clients_holder.get_all_clients())\n removed_client = self.clients_holder.pop_client(self.clients_holder.get(1).ID)\n self.assertEqual(old_clients_length - 1, len(self.clients_holder.get_all_clients()))\n self.assertEqual(removed_client.ID, 1)\n", "method_code": " def get_all_clients(self):\n return ConnectedClientsGroup(list(self.all_connected_clients.values()), self.hub_name)\n ", "context": "class ConnectedClientsHolder():\n def get_all_clients(self): ...\n def __init__(self, hub_instance): ...\n def get_other_clients(self, sender): ...\n def get_clients(self, filter_function): ...\n def get_client(self, client_id): ...\n def get(self, filter_criteria): ...\n def get_subscribed_clients(self): ...\n def append_client(cls, client): ...\n def pop_client(cls, client_id): ...\n\n self.hub_instance = hub_instance\n self.hub_name = self.hub_instance.__class__.__HubName__\n self.hub_subscribers = []\n\n all_connected_clients = dict()\n", "repository": "JorgeGarciaIrazabal/WSHubsAPI", "test_name": "test_pop_client_removes_a_client_if_exists", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002069.py"} {"focal_file": "wshubsapi/hub.py", "focal_class": null, "focal_method": "_construct_unsuccessful_replay", "tests": "import unittest\n\nclass Test_construct_unsuccessful_replay(unittest.TestCase):\n def test_construct_unnecessary_replay_returns_unsuccessful_replay_instance(self):\n unsuccessful_replay = self.hub._construct_unsuccessful_replay('reply')\n self.assertIsInstance(unsuccessful_replay, UnsuccessfulReplay)\n self.assertEqual(unsuccessful_replay.reply, 'reply')\n", "method_code": " def _construct_unsuccessful_replay(reply):\n return UnsuccessfulReplay(reply)\n ", "context": "class Hub(object):\n @staticmethod\n def _construct_unsuccessful_replay(reply): ...\n def __init__(self): ...\n def subscribe_to_hub(self, _sender): ...\n def unsubscribe_from_hub(self, _sender): ...\n def get_subscribed_clients_ids(self): ...\n def clients(self): ...\n def client_functions(self): ...\n def client_functions(self, client_functions): ...\n def _define_client_functions(self): ...\n def get_instance(cls): ...\n def _client_to_clients_bridge(self, clients_ids, function, args): ...\n\n self._client_functions = self._define_client_functions()\n self._clients_holder = ConnectedClientsHolder(self)\n\n __HubName__ = None\n", "repository": "JorgeGarciaIrazabal/WSHubsAPI", "test_name": "test_construct_unnecessary_replay_returns_unsuccessful_replay_instance", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002070.py"} {"focal_file": "wshubsapi/hub.py", "focal_class": null, "focal_method": "get_subscribed_clients_ids", "tests": "import unittest\n\nclass Test_get_subscribed_clients_ids(unittest.TestCase):\n def test_hub_creation_starts_with_no_subscribed_clients(self):\n self.assertEqual(len(self.hub.get_subscribed_clients_ids()), 0)\n\n def test_get_subscribed_clients_returns_the_right_clients(self):\n\n def construct_sender(id_):\n connected_client_sender = flexmock(ConnectedClient(CommEnvironment(), None), ID=id_)\n return ClientInHub(connected_client_sender, self.hub.__HubName__)\n client_a = construct_sender('a')\n client_b = construct_sender('b')\n client_c = construct_sender('c')\n self.assertEqual(len(self.hub.get_subscribed_clients_ids()), 0)\n self.hub.subscribe_to_hub(client_a)\n self.assertEqual(self.hub.get_subscribed_clients_ids()[0], 'a')\n self.hub.subscribe_to_hub(client_b)\n self.assertEqual(self.hub.get_subscribed_clients_ids()[1], 'b')\n self.hub.subscribe_to_hub(client_c)\n self.assertEqual(self.hub.get_subscribed_clients_ids()[2], 'c')\n", "method_code": " def get_subscribed_clients_ids(self):\n return [c.ID for c in self._clients_holder.get_subscribed_clients()]\n ", "context": "class Hub(object):\n def get_subscribed_clients_ids(self): ...\n def __init__(self): ...\n def subscribe_to_hub(self, _sender): ...\n def unsubscribe_from_hub(self, _sender): ...\n def clients(self): ...\n def client_functions(self): ...\n def client_functions(self, client_functions): ...\n def _construct_unsuccessful_replay(reply): ...\n def _define_client_functions(self): ...\n def get_instance(cls): ...\n def _client_to_clients_bridge(self, clients_ids, function, args): ...\n\n self._client_functions = self._define_client_functions()\n self._clients_holder = ConnectedClientsHolder(self)\n\n __HubName__ = None\n", "repository": "JorgeGarciaIrazabal/WSHubsAPI", "test_name": "test_hub_creation_starts_with_no_subscribed_clients", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002071.py"} {"focal_file": "wshubsapi/utils.py", "focal_class": null, "focal_method": "is_function_for_ws_client", "tests": "import unittest\n\nclass Test_is_function_for_ws_client(unittest.TestCase):\n def test_is_function_for_ws_client_includes_standard_function(self):\n\n def this_is_a_new_function(test):\n print(test)\n self.assertTrue(is_function_for_ws_client(this_is_a_new_function), 'new function is detected')\n\n def test_is_function_for_ws_client__excludes_protected_and_private_functions(self):\n\n def _this_is_a_protected_function(test):\n print(test)\n\n def __this_is_a_private_function(test):\n print(test)\n self.assertFalse(is_function_for_ws_client(_this_is_a_protected_function), 'protected function is excluded')\n self.assertFalse(is_function_for_ws_client(__this_is_a_private_function), 'private function is excluded')\n\n def test_is_function_for_ws_client_excludes_already_existing_functions(self):\n self.assertFalse(is_function_for_ws_client(HubsInspector.HUBS_DICT), 'excludes existing functions')\n", "method_code": "def is_function_for_ws_client(method):\n\n def is_function():\n return inspect.ismethod(method) or inspect.isfunction(method)\n return is_function() and (not method.__name__.startswith('_')) and method.__name__", "context": "def is_function_for_ws_client(method): ...\ndef get_args(method, include_sender=False): ...\ndef get_defaults(method): ...\ndef is_function_for_ws_client(method): ...\ndef get_module_path(): ...\n", "repository": "JorgeGarciaIrazabal/WSHubsAPI", "test_name": "test_is_function_for_ws_client_includes_standard_function", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_002072.py"} {"focal_file": "be/round.py", "focal_class": null, "focal_method": "next_player", "tests": "import unittest\n\nclass Test_next_player(unittest.TestCase):\n def test_next_player(self):\n player1 = Player('1', CardCollection.from_string('9S 9H 9C 9D JS JH JC JD'))\n player2 = Player('2', CardCollection.from_string('2S 2H 2C 2D 10S 10H 10C 10D'))\n rnd = Round([player1, player2], [PlayerMove.from_string(player1, 'JH JC JD')])\n self.assertEqual(rnd.next_player(), player2)\n", "method_code": " def next_player(self):\n \"\"\"\n :return: next player to move, or None if the round is over.\n \"\"\"\n if not self.player_moves:\n return self.players[0] if self.players else None\n next_player_idx = (self.players.index(self.player_moves[-1].player) + 1) % len(self.players)\n pivoted = self.players[next_player_idx:] + self.players[:next_player_idx]\n try:\n player = next((player for player in pivoted if player.cards))\n except StopIteration:\n return None\n return player if player != self.player_moves[-1].player else None\n ", "context": "class Round():\n def next_player(self): ...\n def __init__(self, players, player_moves): ...\n def new(players): ...\n def append(self, player_move): ...\n\n self.players = players\n self.player_moves = player_moves\n self.move_type = get_move_type(player_moves[0].move) if player_moves else None\n", "repository": "0ddfell0w/cp", "test_name": "test_next_player", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002073.py"} {"focal_file": "raw_packet/Scanners/arp_scanner.py", "focal_class": null, "focal_method": "scan", "tests": "import unittest\n\nclass Test_scan(unittest.TestCase):\n def test01_scan(self):\n arp_scan_results = self.arp_scan.scan(timeout=1, retry=1, show_scan_percentage=False, exit_on_failure=False)\n self.assertIsNotNone(arp_scan_results)\n find_router: bool = False\n find_target: bool = False\n for arp_scan_result in arp_scan_results:\n if arp_scan_result['ip-address'] == self.variables.router.ipv4_address:\n self.assertEqual(arp_scan_result['mac-address'], self.variables.router.mac_address)\n self.assertIn(self.variables.router.vendor, arp_scan_result['vendor'])\n find_router = True\n if arp_scan_result['ip-address'] == self.variables.target.ipv4_address:\n self.assertEqual(arp_scan_result['mac-address'], self.variables.target.mac_address)\n self.assertIn(self.variables.target.vendor, arp_scan_result['vendor'])\n find_target = True\n self.assertTrue(find_router)\n self.assertTrue(find_target)\n", "method_code": " def scan(self, timeout: int=5, retry: int=5, target_ip_address: Union[None, str]=None, check_vendor: bool=True, exclude_ip_addresses: Union[None, List[str]]=None, exit_on_failure: bool=True, show_scan_percentage: bool=True) -> List[Dict[str, str]]:\n \"\"\"\n ARP scan on network interface\n :param timeout: Timeout in seconds (default: 5)\n :param retry: Retry number (default: 5)\n :param target_ip_address: Target IPv4 address (example: 192.168.0.1)\n :param check_vendor: Check vendor of hosts (default: True)\n :param exclude_ip_addresses: Exclude IPv4 address list (example: ['192.168.0.1','192.168.0.2'])\n :param exit_on_failure: Exit if alive hosts in network not found (default: True)\n :param show_scan_percentage: Show ARP scan progress percentage (default: True)\n :return: Result list of alive hosts (example: [{'mac-address': '01:23:45:67:89:0a',\n 'ip-address': '192.168.0.1',\n 'vendor': 'Raspberry Pi Foundation'}])\n \"\"\"\n try:\n self._results.clear()\n self._unique_results.clear()\n self._sorted_results.clear()\n self._mac_addresses.clear()\n self._quit = not show_scan_percentage\n self._target['ipv4-address'] = self._check_target_ip_address(target_ip_address)\n self._timeout = int(timeout)\n self._retry_number = int(retry)\n self._thread_manager.add_task(self._sniff)\n self._send()\n sleep(self._timeout)\n for index in range(len(self._results)):\n if self._results[index]['mac-address'] not in self._mac_addresses:\n self._unique_results.append(self._results[index])\n self._mac_addresses.append(self._results[index]['mac-address'])\n if exclude_ip_addresses is not None:\n self._results = self._unique_results\n self._unique_results = list()\n for index in range(len(self._results)):\n if self._results[index]['ip-address'] not in exclude_ip_addresses:\n self._unique_results.append(self._results[index])\n self._results = list()\n if check_vendor:\n for result_index in range(len(self._unique_results)):\n self._unique_results[result_index]['vendor'] = self._base.get_vendor_by_mac_address(self._unique_results[result_index]['mac-address'])\n self._sorted_results = sorted(self._unique_results, key=lambda ip: inet_aton(ip['ip-address']))\n except KeyboardInterrupt:\n self._base.print_info('Exit')\n exit(0)\n if len(self._unique_results) == 0:\n if exit_on_failure:\n self._base.print_error('Could not find allive hosts on interface: ', self._your['network-interface'])\n exit(1)\n return self._sorted_results\n ", "context": "class ArpScan():\n def scan(self, timeout: int=5, retry: int=5, target_ip_address: Union[None, str]=None, check_vendor: bool=True, exclude_ip_addresses: Union[None, List[str]]=None, exit_on_failure: bool=True, show_scan_percentage: bool=True) -> List[Dict[str, str]]: ...\n def __init__(self, network_interface: str) -> None: ...\n def get_mac_address(self, target_ip_address: str='192.168.0.1', timeout: int=5, retry: int=5, exit_on_failure: bool=True, show_scan_percentage: bool=False) -> str: ...\n def _analyze_packet(self, packet: Dict[str, Dict[str, str]]) -> None: ...\n def _sniff(self) -> None: ...\n def _send(self) -> None: ...\n def _check_target_ip_address(self, target_ip_address: Union[None, str]) -> Union[None, str]: ...\n\n self._your = self._base.get_interface_settings(interface_name=network_interface, required_parameters=['mac-address', 'ipv4-address', 'first-ipv4-address', 'last-ipv4-address'])\n", "repository": "raw-packet/raw-packet", "test_name": "test01_scan", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002074.py"} {"focal_file": "raw_packet/Scanners/arp_scanner.py", "focal_class": null, "focal_method": "get_mac_address", "tests": "import unittest\n\nclass Test_get_mac_address(unittest.TestCase):\n def test03_get_mac_address(self):\n mac_address = self.arp_scan.get_mac_address(target_ip_address=self.variables.router.ipv4_address, timeout=1, retry=1, show_scan_percentage=False, exit_on_failure=False)\n self.assertEqual(mac_address, self.variables.router.mac_address)\n mac_address = self.arp_scan.get_mac_address(target_ip_address=self.variables.target.ipv4_address, timeout=1, retry=1, show_scan_percentage=False, exit_on_failure=False)\n self.assertEqual(mac_address, self.variables.target.mac_address)\n", "method_code": " def get_mac_address(self, target_ip_address: str='192.168.0.1', timeout: int=5, retry: int=5, exit_on_failure: bool=True, show_scan_percentage: bool=False) -> str:\n \"\"\"\n Get MAC address of IP address on network interface\n :param timeout: Timeout in seconds (default: 3)\n :param retry: Retry number (default: 3)\n :param target_ip_address: Target IPv4 address (example: 192.168.0.1)\n :param exit_on_failure: Exit if MAC address of target IP address not found (default: True)\n :param show_scan_percentage: Show ARP scan progress percentage (default: True)\n :return: MAC address of target IP address (example: '01:23:45:67:89:0a')\n \"\"\"\n result_mac_address: str = 'ff:ff:ff:ff:ff:ff'\n try:\n self._results.clear()\n self._unique_results.clear()\n self._mac_addresses.clear()\n self._quit = not show_scan_percentage\n self._target['ipv4-address'] = self._check_target_ip_address(target_ip_address)\n self._timeout = int(timeout)\n self._retry_number = int(retry)\n self._thread_manager.add_task(self._sniff)\n self._send()\n sleep(self._timeout)\n if 'mac-address' in self._results[0].keys():\n result_mac_address = self._results[0]['mac-address']\n except IndexError:\n pass\n except KeyboardInterrupt:\n self._base.print_info('Exit')\n exit(0)\n if result_mac_address == 'ff:ff:ff:ff:ff:ff':\n if exit_on_failure:\n self._base.print_error('Could not find MAC address of IP address: ', target_ip_address)\n exit(1)\n return result_mac_address\n ", "context": "class ArpScan():\n def get_mac_address(self, target_ip_address: str='192.168.0.1', timeout: int=5, retry: int=5, exit_on_failure: bool=True, show_scan_percentage: bool=False) -> str: ...\n def __init__(self, network_interface: str) -> None: ...\n def scan(self, timeout: int=5, retry: int=5, target_ip_address: Union[None, str]=None, check_vendor: bool=True, exclude_ip_addresses: Union[None, List[str]]=None, exit_on_failure: bool=True, show_scan_percentage: bool=True) -> List[Dict[str, str]]: ...\n def _analyze_packet(self, packet: Dict[str, Dict[str, str]]) -> None: ...\n def _sniff(self) -> None: ...\n def _send(self) -> None: ...\n def _check_target_ip_address(self, target_ip_address: Union[None, str]) -> Union[None, str]: ...\n\n self._your = self._base.get_interface_settings(interface_name=network_interface, required_parameters=['mac-address', 'ipv4-address', 'first-ipv4-address', 'last-ipv4-address'])\n", "repository": "raw-packet/raw-packet", "test_name": "test03_get_mac_address", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002075.py"} {"focal_file": "raw_packet/Scanners/icmpv6_scanner.py", "focal_class": null, "focal_method": "scan", "tests": "import unittest\n\nclass Test_scan(unittest.TestCase):\n def test01_scan(self):\n icmpv6_scan_results = self.icmpv6_scan.scan(timeout=3, retry=3, exit_on_failure=False)\n self.assertIsNotNone(icmpv6_scan_results)\n self.assertTrue(len(icmpv6_scan_results) > 0)\n find_router: bool = False\n find_target: bool = False\n for icmpv6_scan_result in icmpv6_scan_results:\n if icmpv6_scan_result['ip-address'] == self.variables.router.ipv6_link_address:\n self.assertEqual(icmpv6_scan_result['mac-address'], self.variables.router.mac_address)\n self.assertIn(self.variables.router.vendor, icmpv6_scan_result['vendor'])\n find_router = True\n if icmpv6_scan_result['ip-address'] == self.variables.target.ipv6_link_address:\n self.assertEqual(icmpv6_scan_result['mac-address'], self.variables.target.mac_address)\n self.assertIn(self.variables.target.vendor, icmpv6_scan_result['vendor'])\n find_target = True\n self.assertTrue(find_router)\n self.assertTrue(find_target)\n", "method_code": " def scan(self, timeout: int=3, retry: int=3, target_mac_address: Union[None, str]=None, check_vendor: bool=True, exit_on_failure: bool=True, exclude_ipv6_addresses: List[str]=[]) -> List[Dict[str, str]]:\n \"\"\"\n Find alive IPv6 hosts in local network with echo (ping) request packets\n :param timeout: Timeout in seconds (default: 3)\n :param retry: Retry number (default: 3)\n :param target_mac_address: Target MAC address (example: 192.168.0.1)\n :param check_vendor: Check vendor of hosts (default: True)\n :param exit_on_failure: Exit if alive IPv6 hosts in network not found (default: True)\n :return: List of alive hosts in network (example: [{'mac-address': '01:23:45:67:89:0a',\n 'ip-address': 'fe80::1234:5678:90ab:cdef',\n 'vendor': 'Apple, Inc.'}])\n \"\"\"\n self._results.clear()\n self._unique_results.clear()\n self._mac_addresses.clear()\n if target_mac_address is not None:\n self._base.mac_address_validation(mac_address=target_mac_address, exit_on_failure=True)\n self._target['mac-address'] = target_mac_address\n self._timeout = int(timeout)\n self._retry_number = int(retry)\n self._icmpv6_identifier = randint(1, 65535)\n self._thread_manager.add_task(self._sniff)\n self._send()\n sleep(self._timeout)\n for index in range(len(self._results)):\n if self._results[index]['mac-address'] not in self._mac_addresses:\n self._unique_results.append(self._results[index])\n self._mac_addresses.append(self._results[index]['mac-address'])\n if check_vendor:\n for result_index in range(len(self._unique_results)):\n self._unique_results[result_index]['vendor'] = self._base.get_vendor_by_mac_address(self._unique_results[result_index]['mac-address'])\n if len(exclude_ipv6_addresses) > 0:\n results: List[Dict[str, str]] = list()\n for unique_result in self._unique_results:\n if unique_result['ip-address'] not in exclude_ipv6_addresses:\n results.append(unique_result)\n self._unique_results = results\n if len(self._unique_results) == 0:\n if exit_on_failure:\n self._base.error_text('Could not found alive IPv6 hosts on interface: ' + self._your['network-interface'])\n exit(1)\n return self._unique_results\n ", "context": "class ICMPv6Scan():\n def scan(self, timeout: int=3, retry: int=3, target_mac_address: Union[None, str]=None, check_vendor: bool=True, exit_on_failure: bool=True, exclude_ipv6_addresses: List[str]=[]) -> List[Dict[str, str]]: ...\n def __init__(self, network_interface: str) -> None: ...\n def _analyze_packet(self, packet: Dict) -> None: ...\n def _sniff(self) -> None: ...\n def _send(self) -> None: ...\n\n self._your = self._base.get_interface_settings(interface_name=network_interface, required_parameters=['mac-address', 'ipv6-link-address'])\n", "repository": "raw-packet/raw-packet", "test_name": "test01_scan", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002076.py"} {"focal_file": "raw_packet/Scanners/nmap_scanner.py", "focal_class": null, "focal_method": "scan", "tests": "import unittest\n\nclass Test_scan(unittest.TestCase):\n def test01_scan(self):\n scan_results = self.nmap_scanner.scan()\n self.assertIsNotNone(scan_results)\n for scan_result in scan_results:\n if scan_result.ipv4_address == self.variables.router.ipv4_address:\n self.assertEqual(scan_result.mac_address, self.variables.router.mac_address)\n self.assertIn(scan_result.vendor.lower(), self.variables.router.vendor.lower())\n if scan_result.ipv4_address == self.variables.target.ipv4_address:\n self.assertEqual(scan_result.mac_address, self.variables.target.mac_address)\n self.assertIn(scan_result.vendor.lower(), self.variables.target.vendor.lower())\n", "method_code": " def scan(self, exit_on_failure: bool=True, quiet: bool=False) -> Union[None, List[NamedTuple]]:\n try:\n network_devices: List[NamedTuple] = list()\n ipv4_address: str = ''\n mac_address: str = ''\n vendor: str = ''\n os: str = ''\n ports: List[int] = list()\n nmap_command: str = 'nmap ' + self.local_network + ' --open -n -O --osscan-guess -T5 -oX ' + self._nmap_scan_result\n if not quiet:\n self._base.print_info('Start nmap scan: ', nmap_command)\n if self._base.get_platform().startswith('Windows'):\n nmap_process = sub.Popen(nmap_command, shell=True, stdout=sub.PIPE, stderr=sub.STDOUT)\n else:\n nmap_process = sub.Popen([nmap_command], shell=True, stdout=sub.PIPE, stderr=sub.STDOUT)\n nmap_process.wait()\n assert isfile(self._nmap_scan_result), 'Not found nmap scan result file: ' + self._base.error_text(self._nmap_scan_result)\n nmap_report = ET.parse(self._nmap_scan_result)\n root_tree = nmap_report.getroot()\n for element in root_tree:\n try:\n assert element.tag == 'host'\n state = element.find('status').attrib['state']\n assert state == 'up'\n for address in element.findall('address'):\n if address.attrib['addrtype'] == 'ipv4':\n ipv4_address = address.attrib['addr']\n if address.attrib['addrtype'] == 'mac':\n mac_address = address.attrib['addr'].lower()\n try:\n vendor = address.attrib['vendor']\n except KeyError:\n pass\n for ports_info in element.find('ports'):\n if ports_info.tag == 'port':\n ports.append(ports_info.attrib['portid'])\n for os_info in element.find('os'):\n if os_info.tag == 'osmatch':\n try:\n os = os_info.attrib['name']\n except TypeError:\n pass\n break\n network_devices.append(self.Info(vendor=vendor, os=os, mac_address=mac_address, ipv4_address=ipv4_address, ports=ports))\n except AssertionError:\n pass\n remove(self._nmap_scan_result)\n assert len(network_devices) != 0, 'Could not find any devices on interface: ' + self._base.error_text(self._your['network-interface'])\n return network_devices\n except OSError:\n self._base.print_error('Something went wrong while trying to run ', 'nmap')\n if exit_on_failure:\n exit(2)\n except KeyboardInterrupt:\n self._base.print_info('Exit')\n exit(0)\n except AssertionError as Error:\n self._base.print_error(Error.args[0])\n if exit_on_failure:\n exit(1)\n return None\n ", "context": "class NmapScanner():\n def scan(self, exit_on_failure: bool=True, quiet: bool=False) -> Union[None, List[NamedTuple]]: ...\n def __init__(self, network_interface: str): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test01_scan", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002077.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_platform", "tests": "import unittest\n\nclass Test_get_platform(unittest.TestCase):\n def test06_get_platform(self):\n self.assertEqual(self.base.get_platform(), self.variables.your.platform)\n", "method_code": " def get_platform(self) -> str:\n \"\"\"\n Get your platform\n :return: Platform string (example: 'Windows 10' or 'Darwin 19.0.0' or 'Linux Ubuntu 18.04')\n \"\"\"\n if self._current_platform is None:\n linux_dist = linux_distribution()\n try:\n assert linux_dist[0] != '' and linux_dist[1] != '' and (linux_dist[0] != system())\n self._current_platform = str(system()) + ' ' + str(linux_dist[0]) + ' ' + str(linux_dist[1])\n except AssertionError:\n self._current_platform = str(system()) + ' ' + str(release())\n return self._current_platform\n ", "context": "class Base():\n def get_platform(self) -> str: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test06_get_platform", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002078.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "pack8", "tests": "import unittest\n\nclass Test_pack8(unittest.TestCase):\n def test07_pack8(self):\n self.assertEqual(self.base.pack8(1, False, 3, True), b'\\x01')\n self.assertIsNone(self.base.pack8('test', False, 3, False))\n", "method_code": " def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Pack 8 bit data\n :param data: Input data\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 3)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Packed 8 bit data\n \"\"\"\n try:\n return pack('B', data)\n except error:\n if not quiet:\n print('Bad value for 8 bit pack: ' + str(data))\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n @staticmethod\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test07_pack8", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002079.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "pack16", "tests": "import unittest\n\nclass Test_pack16(unittest.TestCase):\n def test08_pack16(self):\n self.assertEqual(self.base.pack16(1, False, 4, True), b'\\x00\\x01')\n self.assertIsNone(self.base.pack16('test', False, 4, False))\n", "method_code": " def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Pack 16 bit data\n :param data: Input data\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 4)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Packed 16 bit data\n \"\"\"\n try:\n return pack('!H', data)\n except error:\n if not quiet:\n print('Bad value for 16 bit pack: ' + str(data))\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n @staticmethod\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test08_pack16", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002080.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "pack32", "tests": "import unittest\n\nclass Test_pack32(unittest.TestCase):\n def test09_pack32(self):\n self.assertEqual(self.base.pack32(1, False, 5, True), b'\\x00\\x00\\x00\\x01')\n self.assertIsNone(self.base.pack32('test', False, 5, False))\n", "method_code": " def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Pack 32 bit data\n :param data: Input data\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 5)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Packed 32 bit data\n \"\"\"\n try:\n return pack('!I', data)\n except error:\n if not quiet:\n print('Bad value for 32 bit pack: ' + str(data))\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n @staticmethod\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test09_pack32", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002081.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "pack64", "tests": "import unittest\n\nclass Test_pack64(unittest.TestCase):\n def test10_pack64(self):\n self.assertEqual(self.base.pack64(1, False, 6, True), b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01')\n self.assertIsNone(self.base.pack64('test', False, 6, False))\n", "method_code": " def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Pack 64 bit data\n :param data: Input data\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 6)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Packed 64 bit data\n \"\"\"\n try:\n return pack('!Q', data)\n except error:\n if not quiet:\n print('Bad value for 64 bit pack: ' + str(data))\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n @staticmethod\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test10_pack64", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002082.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "network_interface_selection", "tests": "import unittest\n\nclass Test_network_interface_selection(unittest.TestCase):\n def test11_network_interface_selection(self):\n self.assertEqual(self.base.network_interface_selection(self.variables.your.network_interface), self.variables.your.network_interface)\n", "method_code": " def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str:\n \"\"\"\n Select network interface\n :param interface_name: Network interface name (example: 'eth0'; default: None)\n :param exclude_interface: Exclude network interface from list of interfaces (example: 'eth1'; default: None)\n :param only_wireless: Select network interface only from wireless interfaces (default: False)\n :param message: Print message before select network interface from table (example: 'Select network interface from table: ')\n :return: Network interface name (example: 'eth0')\n \"\"\"\n network_interface_index: int = 1\n if not only_wireless:\n available_network_interfaces: List[str] = self.list_of_network_interfaces()\n else:\n available_network_interfaces: List[str] = self.list_of_wireless_network_interfaces()\n if exclude_interface is not None:\n available_network_interfaces.remove(exclude_interface)\n if interface_name is not None:\n if interface_name in available_network_interfaces:\n self.get_interface_settings(interface_name=interface_name, required_parameters=[], quiet=True)\n return interface_name\n else:\n if not only_wireless:\n self.print_error('Network interface: ', interface_name, ' does not exist!')\n else:\n self.print_error('Wireless network interface: ', interface_name, ' does not exist!')\n exit(1)\n else:\n if 'lo' in available_network_interfaces:\n available_network_interfaces.remove('lo')\n if len(available_network_interfaces) > 1:\n if message is not None:\n self.print_warning(message)\n interfaces_pretty_table = PrettyTable([self.info_text('Index'), self.info_text('Interface name'), self.info_text('MAC address'), self.info_text('IPv4 address'), self.info_text('IPv6 link address')])\n for network_interface in available_network_interfaces:\n network_interface_settings = self.get_interface_settings(interface_name=network_interface, required_parameters=[], quiet=True)\n network_interface_mac_address: Union[None, str] = network_interface_settings['mac-address']\n if network_interface_mac_address is None:\n network_interface_mac_address = 'None'\n network_interface_ipv4_address: Union[None, str] = network_interface_settings['ipv4-address']\n if network_interface_ipv4_address is None:\n network_interface_ipv4_address = 'None'\n network_interface_ipv6_link_address: Union[None, str] = network_interface_settings['ipv6-link-address']\n if network_interface_ipv6_link_address is None:\n network_interface_ipv6_link_address = 'None'\n interfaces_pretty_table.add_row([str(network_interface_index), network_interface, network_interface_mac_address, network_interface_ipv4_address, network_interface_ipv6_link_address])\n network_interface_index += 1\n print(interfaces_pretty_table)\n network_interface_index -= 1\n print(self.c_warning + 'Select network interface from range (1-' + str(network_interface_index) + '): ', end='')\n current_network_interface_index = input()\n if not current_network_interface_index.isdigit():\n self.print_error('Your input data: ', current_network_interface_index, ' is not digit!')\n exit(1)\n else:\n current_network_interface_index = int(current_network_interface_index)\n if any([int(current_network_interface_index) < 1, int(current_network_interface_index) > network_interface_index]):\n self.print_error('Your number: ', current_network_interface_index, ' is not within range (', '1-' + str(network_interface_index), ')')\n exit(1)\n current_network_interface = ''\n try:\n current_network_interface = str(available_network_interfaces[current_network_interface_index - 1])\n except:\n self.print_error('This network interface has some problem!')\n exit(1)\n if not only_wireless:\n self.print_info('Your choose network interface: ', current_network_interface)\n else:\n self.print_info('Your choose wireless network interface: ', current_network_interface)\n return current_network_interface\n if len(available_network_interfaces) == 1:\n self.get_interface_settings(interface_name=available_network_interfaces[0], required_parameters=[], quiet=True)\n if not only_wireless:\n self.print_info('You have only one network interface: ', available_network_interfaces[0])\n else:\n self.print_info('You have only one wireless network interface: ', available_network_interfaces[0])\n return available_network_interfaces[0]\n if len(available_network_interfaces) == 0:\n if not only_wireless:\n self.print_error('Network interfaces not found!')\n else:\n self.print_error('Wireless network interfaces not found!')\n exit(1)\n ", "context": "class Base():\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test11_network_interface_selection", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002083.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_settings", "tests": "import unittest\n\nclass Test_get_interface_settings(unittest.TestCase):\n def test12_get_interface_settings(self):\n _your = self.base.get_interface_settings(self.variables.your.network_interface)\n self.assertIn('network-interface', _your.keys())\n self.assertIn('is-wireless', _your.keys())\n self.assertIn('essid', _your.keys())\n self.assertIn('bssid', _your.keys())\n self.assertIn('channel', _your.keys())\n self.assertIn('mac-address', _your.keys())\n self.assertIn('ipv4-address', _your.keys())\n self.assertIn('ipv6-link-address', _your.keys())\n self.assertIn('ipv6-global-address', _your.keys())\n self.assertIn('ipv6-global-addresses', _your.keys())\n self.assertIn('ipv4-netmask', _your.keys())\n self.assertIn('ipv4-network', _your.keys())\n self.assertIn('first-ipv4-address', _your.keys())\n self.assertIn('second-ipv4-address', _your.keys())\n self.assertIn('penultimate-ipv4-address', _your.keys())\n self.assertIn('last-ipv4-address', _your.keys())\n self.assertIn('ipv4-broadcast', _your.keys())\n self.assertIn('ipv4-gateway', _your.keys())\n self.assertIn('ipv6-gateway', _your.keys())\n self.assertEqual(self.variables.your.network_interface, _your['network-interface'])\n self.assertFalse(_your['is-wireless'])\n self.assertIsNone(_your['essid'])\n self.assertIsNone(_your['bssid'])\n self.assertIsNone(_your['channel'])\n self.assertEqual(self.variables.your.mac_address, _your['mac-address'])\n self.assertEqual(self.variables.your.ipv4_address, _your['ipv4-address'])\n self.assertEqual(self.variables.your.ipv6_link_address, _your['ipv6-link-address'])\n self.assertIsNotNone(_your['ipv6-global-address'])\n self.assertIn(self.variables.your.ipv6_global_address, _your['ipv6-global-addresses'])\n self.assertEqual(self.variables.ipv4.network_mask, _your['ipv4-netmask'])\n self.assertEqual(self.variables.ipv4.network, _your['ipv4-network'])\n self.assertEqual(self.variables.ipv4.first_address, _your['first-ipv4-address'])\n self.assertEqual(self.variables.ipv4.second_address, _your['second-ipv4-address'])\n self.assertEqual(self.variables.ipv4.penultimate_address, _your['penultimate-ipv4-address'])\n self.assertEqual(self.variables.ipv4.last_address, _your['last-ipv4-address'])\n self.assertEqual(self.variables.ipv4.broadcast, _your['ipv4-broadcast'])\n self.assertEqual(self.variables.router.ipv4_address, _your['ipv4-gateway'])\n self.assertEqual(self.variables.router.ipv6_link_address, _your['ipv6-gateway'])\n self.assertEqual(self.base.get_interface_settings(self.variables.bad.network_interface), {'network-interface': self.variables.bad.network_interface, 'is-wireless': False, 'essid': None, 'bssid': None, 'channel': None, 'mac-address': None, 'ipv4-address': None, 'ipv6-link-address': None, 'IPv6 global address': None, 'ipv6-global-addresses': [], 'ipv4-netmask': None, 'ipv4-network': None, 'first-ipv4-address': None, 'second-ipv4-address': None, 'penultimate-ipv4-address': None, 'last-ipv4-address': None, 'ipv4-broadcast': None, 'ipv4-gateway': None, 'ipv6-gateway': None})\n", "method_code": " def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]:\n \"\"\"\n Get network interface settings\n :param interface_name: Network interface name (default: 'eth0')\n :param required_parameters: Required Network interface parameters list (default: ['mac-address'])\n :param quiet: Quiet mode, if True no console output (default: True)\n :return: Network interface settings dictionary\n (example: {'network-interface': 'example-network-interface',\n 'is-wireless': False,\n 'essid': 'AP',\n 'bssid': '12:34:56:78:90:ab',\n 'channel': 1,\n 'mac-address': '12:34:56:78:90:ab',\n 'ipv4-address': '192.168.0.1',\n 'ipv6-link-address': 'fe80::1234:5678:90ab:cdef',\n 'ipv6-global-address': '2001:4860:4860::8888',\n 'ipv6-global-addresses': ['2001:4860:4860::8888', '2001:4860:4860::8844'],\n 'ipv4-netmask': '255.255.255.0',\n 'ipv4-network': '192.168.0.0/24',\n 'first-ipv4-address': '192.168.0.1',\n 'second-ipv4-address': '192.168.0.2',\n 'penultimate-ipv4-address': '192.168.0.253',\n 'last-ipv4-address': '192.168.0.254',\n 'ipv4-broadcast': '192.168.0.255',\n 'ipv4-gateway': '192.168.0.254',\n 'ipv6-gateway': 'fe80::1234:5678:8765:4321'})\n \"\"\"\n if interface_name not in self._network_interfaces_settings.keys():\n wireless_interface_settings: Dict[str, Union[None, int, float, str]] = self.get_wireless_interface_settings(interface_name=interface_name)\n self._network_interfaces_settings[interface_name]: Dict[str, Union[None, bool, int, float, str, List[str]]] = {'network-interface': interface_name, 'is-wireless': self.check_network_interface_is_wireless(interface_name=interface_name), 'essid': wireless_interface_settings['essid'], 'bssid': wireless_interface_settings['bssid'], 'channel': wireless_interface_settings['channel'], 'mac-address': self.get_interface_mac_address(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'ipv4-address': self.get_interface_ip_address(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'ipv6-link-address': self.get_interface_ipv6_link_address(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'ipv6-global-address': self.get_interface_ipv6_glob_address(interface_name=interface_name), 'ipv6-global-addresses': self.get_interface_ipv6_glob_addresses(interface_name=interface_name), 'ipv4-netmask': self.get_interface_netmask(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'ipv4-network': self.get_interface_network(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'first-ipv4-address': self.get_first_ip_on_interface(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'second-ipv4-address': self.get_second_ip_on_interface(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'penultimate-ipv4-address': self.get_penultimate_ip_on_interface(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'last-ipv4-address': self.get_last_ip_on_interface(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'ipv4-broadcast': self.get_interface_broadcast(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'ipv4-gateway': self.get_interface_ipv4_gateway(interface_name=interface_name, exit_on_failure=False, quiet=quiet), 'ipv6-gateway': self.get_interface_ipv6_gateway(interface_name=interface_name, exit_on_failure=False, quiet=quiet)}\n try:\n for required_parameter in required_parameters:\n if required_parameter in self._network_interfaces_settings[interface_name].keys():\n assert self._network_interfaces_settings[interface_name][required_parameter] is not None, 'Network interface: ' + self.error_text(interface_name) + ' does not have: ' + self.error_text(required_parameter)\n return self._network_interfaces_settings[interface_name]\n except AssertionError as Error:\n self.print_error(Error.args[0])\n exit(1)\n ", "context": "class Base():\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test12_get_interface_settings", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002084.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_mac_address", "tests": "import unittest\n\nclass Test_get_interface_mac_address(unittest.TestCase):\n def test13_get_interface_mac_address(self):\n self.assertEqual(self.base.get_interface_mac_address(self.variables.your.network_interface), self.variables.your.mac_address)\n self.assertIsNone(self.base.get_interface_mac_address(self.variables.bad.network_interface, False, 7))\n", "method_code": " def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get MAC address of the network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: True)\n :param exit_code: Set exit code integer (default: 7)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: MAC address string (example: '01:23:45:67:89:0a') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['mac-address'] is not None:\n return self._network_interfaces_settings[interface_name]['mac-address']\n try:\n return str(ifaddresses(interface_name)[AF_LINK][0]['addr'])\n except NameError:\n return get_mac_address(interface=interface_name)\n except ValueError:\n pass\n except KeyError:\n pass\n if not quiet:\n self.print_error('Network interface: ', interface_name, ' does not have MAC address!')\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test13_get_interface_mac_address", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002085.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_ip_address", "tests": "import unittest\n\nclass Test_get_interface_ip_address(unittest.TestCase):\n def test14_get_interface_ipv4_address(self):\n self.assertEqual(self.base.get_interface_ip_address(self.variables.your.network_interface, True, 8), self.variables.your.ipv4_address)\n self.assertIsNone(self.base.get_interface_ip_address(self.variables.bad.network_interface, False, 8))\n", "method_code": " def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get IPv4 address of the network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 8)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.1') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv4-address'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv4-address']\n try:\n if self.get_platform().startswith('Windows'):\n for adapter in self._windows_adapters:\n for ip in adapter.ips:\n if ip.nice_name == interface_name and ip.is_IPv4:\n return ip.ip\n return None\n else:\n return str(ifaddresses(interface_name)[AF_INET][0]['addr'])\n except ValueError:\n pass\n except KeyError:\n pass\n if not quiet:\n self.print_error('Network interface: ', interface_name, ' does not have IP address!')\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test14_get_interface_ipv4_address", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002086.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_ipv6_address", "tests": "import unittest\n\nclass Test_get_interface_ipv6_address(unittest.TestCase):\n def test15_get_interface_ipv6_address(self):\n self.assertIsNotNone(self.base.get_interface_ipv6_address(self.variables.your.network_interface, 0, True, 9))\n self.assertIsNone(self.base.get_interface_ipv6_address(self.variables.bad.network_interface, 0, False, 9))\n", "method_code": " def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get IPv6 address of the network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param address_index: Index of IPv6 address (default: 0)\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 9)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv6 address string (example: 'fd00::1') or None in case of error\n \"\"\"\n try:\n if self.get_platform().startswith('Windows'):\n ipv6_addresses: List[str] = list()\n for adapter in self._windows_adapters:\n for ip in adapter.ips:\n if ip.nice_name == interface_name and ip.is_IPv6:\n ipv6_addresses.append(ip.ip[0])\n return ipv6_addresses[address_index]\n else:\n ipv6_address = str(ifaddresses(interface_name)[AF_INET6][address_index]['addr'])\n ipv6_address = ipv6_address.replace('%' + interface_name, '', 1)\n except NameError:\n ipv6_address = '::1'\n except IndexError:\n ipv6_address = None\n except ValueError:\n ipv6_address = None\n except KeyError:\n ipv6_address = None\n if ipv6_address is None:\n if not quiet:\n self.print_error('Network interface: ', interface_name, ' does not have IPv6 address with index: ', str(address_index))\n if exit_on_failure:\n exit(exit_code)\n return ipv6_address\n ", "context": "class Base():\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test15_get_interface_ipv6_address", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002087.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_ipv6_link_address", "tests": "import unittest\n\nclass Test_get_interface_ipv6_link_address(unittest.TestCase):\n def test16_get_interface_ipv6_link_address(self):\n self.assertEqual(self.base.get_interface_ipv6_link_address(self.variables.your.network_interface, False, 10), self.variables.your.ipv6_link_address)\n self.assertIsNone(self.base.get_interface_ipv6_link_address(self.variables.bad.network_interface, False, 10))\n", "method_code": " def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get IPv6 link local address of the network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 10)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv6 link local address string (example: 'fe80::1') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv6-link-address'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv6-link-address']\n if interface_name == 'lo':\n return '::1'\n for address_index in range(0, 10, 1):\n ipv6_address = self.get_interface_ipv6_address(interface_name=interface_name, address_index=address_index, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n try:\n if ipv6_address.startswith('fe80::'):\n return ipv6_address\n except AttributeError:\n if not quiet:\n self.print_error('Network interface: ', interface_name, ' does not have IPv6 link local address!')\n if exit_on_failure:\n exit(exit_code)\n return None\n return None\n ", "context": "class Base():\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test16_get_interface_ipv6_link_address", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002088.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_ipv6_glob_address", "tests": "import unittest\n\nclass Test_get_interface_ipv6_glob_address(unittest.TestCase):\n def test17_get_interface_ipv6_glob_address(self):\n self.assertIsNotNone(self.base.get_interface_ipv6_glob_address(self.variables.your.network_interface))\n self.assertIsNone(self.base.get_interface_ipv6_glob_address(self.variables.bad.network_interface))\n", "method_code": " def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]:\n \"\"\"\n Get IPv6 global address of the network interface\n :param interface_name: Network interface name (default: 'eth0')\n :return: IPv6 global address string (example: 'fd00::1') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv6-global-address'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv6-global-address']\n address_index: int = 0\n ipv6_address: Union[None, str] = self.get_interface_ipv6_address(interface_name=interface_name, address_index=address_index, exit_on_failure=False, quiet=True)\n while ipv6_address is not None:\n if not ipv6_address.startswith('fe80::'):\n return ipv6_address\n address_index += 1\n ipv6_address: Union[None, str] = self.get_interface_ipv6_address(interface_name=interface_name, address_index=address_index, exit_on_failure=False, quiet=True)\n return None\n ", "context": "class Base():\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test17_get_interface_ipv6_glob_address", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002089.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_ipv6_glob_addresses", "tests": "import unittest\n\nclass Test_get_interface_ipv6_glob_addresses(unittest.TestCase):\n def test18_get_interface_ipv6_glob_addresses(self):\n self.assertIn(self.variables.your.ipv6_global_address, self.base.get_interface_ipv6_glob_addresses(self.variables.your.network_interface))\n self.assertEqual(len(self.base.get_interface_ipv6_glob_addresses(self.variables.bad.network_interface)), 0)\n", "method_code": " def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]:\n \"\"\"\n Get IPv6 global addresses list of the network interface\n :param interface_name: Network interface name (default: 'eth0')\n :return: IPv6 global addresses list (example: ['fd00::1', 'fd00::2'])\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv6-global-addresses'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv6-global-addresses']\n ipv6_addresses: List[str] = list()\n address_index: int = 0\n ipv6_address: Union[None, str] = self.get_interface_ipv6_address(interface_name=interface_name, address_index=address_index, exit_on_failure=False, quiet=True)\n while ipv6_address is not None:\n if not ipv6_address.startswith('fe80::'):\n ipv6_addresses.append(ipv6_address)\n address_index += 1\n ipv6_address: Union[None, str] = self.get_interface_ipv6_address(interface_name=interface_name, address_index=address_index, exit_on_failure=False, quiet=True)\n return ipv6_addresses\n ", "context": "class Base():\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test18_get_interface_ipv6_glob_addresses", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002090.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "make_ipv6_link_address", "tests": "import unittest\n\nclass Test_make_ipv6_link_address(unittest.TestCase):\n def test19_make_ipv6_link_address(self):\n self.assertEqual(self.base.make_ipv6_link_address('12:34:56:78:90:ab'), 'fe80::1034:56ff:fe78:90ab')\n self.assertIsNone(self.base.make_ipv6_link_address('12:34:56:78:90:abc', False, 12))\n", "method_code": " def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Make IPv6 link local address by MAC address\n :param mac_address: MAC address (default: '01:23:45:67:89:0a')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 12)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv6 link local address string (example: 'fe80::1') or None in case of error\n \"\"\"\n try:\n assert self.mac_address_validation(mac_address=mac_address, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet), 'Failed to make IPv6 link local address from MAC address: ' + self.error_text(str(mac_address))\n parts: List[str] = mac_address.split(':')\n parts.insert(3, 'ff')\n parts.insert(4, 'fe')\n parts[0] = '%x' % (int(parts[0], 16) ^ 2)\n ipv6_parts: List[str] = list()\n ipv6_parts_clear: List[str] = list()\n for index in range(0, len(parts), 2):\n ipv6_parts.append(''.join(parts[index:index + 2]))\n for ipv6_part in ipv6_parts:\n if ipv6_part.startswith('0'):\n ipv6_part = ipv6_part[1:]\n if ipv6_part.startswith('0'):\n ipv6_part = ipv6_part[1:]\n if ipv6_part.startswith('0'):\n ipv6_part = ipv6_part[1:]\n if ipv6_part.startswith('0'):\n ipv6_part = ':'\n ipv6_parts_clear.append(ipv6_part)\n return 'fe80::%s' % ':'.join(ipv6_parts_clear)\n except AssertionError as Error:\n error_text = Error.args[0]\n if not quiet:\n self.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class Base():\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test19_make_ipv6_link_address", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002091.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_netmask", "tests": "import unittest\n\nclass Test_get_interface_netmask(unittest.TestCase):\n def test20_get_interface_netmask(self):\n self.assertEqual(self.base.get_interface_netmask(self.variables.your.network_interface, True, 13), self.variables.ipv4.network_mask)\n self.assertIsNone(self.base.get_interface_netmask(self.variables.bad.network_interface, False, 13))\n", "method_code": " def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get network interface mask\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 13)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Network interface mask string (example: '255.255.255.0') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv4-netmask'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv4-netmask']\n try:\n if self.get_platform().startswith('Windows'):\n for adapter in self._windows_adapters:\n for ip in adapter.ips:\n if ip.nice_name == interface_name and ip.is_IPv4:\n bits = 4294967295 ^ (1 << 32 - ip.network_prefix) - 1\n return str(inet_ntoa(pack('>I', bits)))\n return None\n else:\n return str(ifaddresses(interface_name)[AF_INET][0]['netmask'])\n except ValueError:\n pass\n except KeyError:\n pass\n if not quiet:\n self.print_error('Network interface: ', interface_name, ' does not have network mask!')\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test20_get_interface_netmask", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002092.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_network", "tests": "import unittest\n\nclass Test_get_interface_network(unittest.TestCase):\n def test21_get_interface_network(self):\n self.assertEqual(self.base.get_interface_network(self.variables.your.network_interface, True, 14), self.variables.ipv4.network)\n self.assertIsNone(self.base.get_interface_network(self.variables.bad.network_interface, False, 14))\n", "method_code": " def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get IPv4 network on interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 14)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 network string (example: '192.168.1.0/24') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv4-network'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv4-network']\n try:\n netmask = self.get_interface_netmask(interface_name=interface_name, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ip_address = self.get_interface_ip_address(interface_name=interface_name, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ip = IPNetwork(ip_address + '/' + netmask)\n return str(ip[0]) + '/' + str(IPAddress(netmask).netmask_bits())\n except KeyError:\n pass\n except ValueError:\n pass\n except TypeError:\n pass\n if not quiet:\n self.print_error('Network interface: ', interface_name, ' does not have IPv4 address or network mask!')\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test21_get_interface_network", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002093.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_ip_on_interface_by_index", "tests": "import unittest\n\nclass Test_get_ip_on_interface_by_index(unittest.TestCase):\n def test22_get_ip_on_interface_by_index(self):\n self.assertEqual(self.base.get_ip_on_interface_by_index(self.variables.your.network_interface, 1, True, 15), self.variables.ipv4.first_address)\n self.assertIsNone(self.base.get_ip_on_interface_by_index(self.variables.bad.network_interface, 1, False, 15))\n", "method_code": " def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get IPv4 address on network interface by index of address\n :param interface_name: Network interface name (default: 'eth0')\n :param index: Index of IPv4 address integer (default: 1)\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 15)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.1') or None in case of error\n \"\"\"\n try:\n network: IPNetwork = IPNetwork(self.get_interface_network(interface_name=interface_name, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet))\n return str(network[index])\n except KeyError:\n pass\n except ValueError:\n pass\n except TypeError:\n pass\n if not quiet:\n self.print_error('Network interface: ', interface_name, ' does not have IPv4 address or network mask!')\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test22_get_ip_on_interface_by_index", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002094.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_first_ip_on_interface", "tests": "import unittest\n\nclass Test_get_first_ip_on_interface(unittest.TestCase):\n def test23_get_first_ip_on_interface(self):\n self.assertEqual(self.base.get_first_ip_on_interface(self.variables.your.network_interface, True, 16), self.variables.ipv4.first_address)\n self.assertIsNone(self.base.get_first_ip_on_interface(self.variables.bad.network_interface, False, 16))\n", "method_code": " def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get first IPv4 address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 16)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.1') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['first-ipv4-address'] is not None:\n return self._network_interfaces_settings[interface_name]['first-ipv4-address']\n return self.get_ip_on_interface_by_index(interface_name=interface_name, index=1, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class Base():\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test23_get_first_ip_on_interface", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002095.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_second_ip_on_interface", "tests": "import unittest\n\nclass Test_get_second_ip_on_interface(unittest.TestCase):\n def test24_get_second_ip_on_interface(self):\n self.assertEqual(self.base.get_second_ip_on_interface(self.variables.your.network_interface, True, 17), self.variables.ipv4.second_address)\n self.assertIsNone(self.base.get_second_ip_on_interface(self.variables.bad.network_interface, False, 17))\n", "method_code": " def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get second IPv4 address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 17)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.2') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['second-ipv4-address'] is not None:\n return self._network_interfaces_settings[interface_name]['second-ipv4-address']\n return self.get_ip_on_interface_by_index(interface_name=interface_name, index=2, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class Base():\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test24_get_second_ip_on_interface", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002096.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_penultimate_ip_on_interface", "tests": "import unittest\n\nclass Test_get_penultimate_ip_on_interface(unittest.TestCase):\n def test25_get_penultimate_ip_on_interface(self):\n self.assertEqual(self.base.get_penultimate_ip_on_interface(self.variables.your.network_interface, True, 18), self.variables.ipv4.penultimate_address)\n self.assertIsNone(self.base.get_penultimate_ip_on_interface(self.variables.bad.network_interface, False, 18))\n", "method_code": " def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get penultimate IPv4 address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 18)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.253') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['penultimate-ipv4-address'] is not None:\n return self._network_interfaces_settings[interface_name]['penultimate-ipv4-address']\n return self.get_ip_on_interface_by_index(interface_name=interface_name, index=-3, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class Base():\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test25_get_penultimate_ip_on_interface", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002097.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_last_ip_on_interface", "tests": "import unittest\n\nclass Test_get_last_ip_on_interface(unittest.TestCase):\n def test26_get_last_ip_on_interface(self):\n self.assertEqual(self.base.get_last_ip_on_interface(self.variables.your.network_interface, True, 19), self.variables.ipv4.last_address)\n self.assertIsNone(self.base.get_last_ip_on_interface(self.variables.bad.network_interface, False, 19))\n", "method_code": " def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get last IPv4 address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 19)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.254') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['last-ipv4-address'] is not None:\n return self._network_interfaces_settings[interface_name]['last-ipv4-address']\n return self.get_ip_on_interface_by_index(interface_name=interface_name, index=-2, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class Base():\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test26_get_last_ip_on_interface", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002098.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_random_ip_on_interface", "tests": "import unittest\n\nclass Test_get_random_ip_on_interface(unittest.TestCase):\n def test27_get_random_ip_on_interface(self):\n self.assertIsNotNone(self.base.get_random_ip_on_interface(self.variables.your.network_interface, True, 20))\n self.assertIsNone(self.base.get_random_ip_on_interface(self.variables.bad.network_interface, False, 20))\n", "method_code": " def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get random IPv4 address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 20)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.123') or None in case of error\n \"\"\"\n try:\n network = IPNetwork(self.get_interface_network(interface_name=interface_name, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet))\n return str(network[randint(2, len(network) - 3)])\n except KeyError:\n pass\n except ValueError:\n pass\n except TypeError:\n pass\n if not quiet:\n self.print_error('Network interface: ', interface_name, ' does not have IPv4 address or network mask!')\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test27_get_random_ip_on_interface", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002099.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_broadcast", "tests": "import unittest\n\nclass Test_get_interface_broadcast(unittest.TestCase):\n def test28_get_interface_broadcast(self):\n self.assertEqual(self.base.get_interface_broadcast(self.variables.your.network_interface, True, 21), self.variables.ipv4.broadcast)\n self.assertIsNone(self.base.get_interface_broadcast(self.variables.bad.network_interface, False, 21))\n", "method_code": " def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get IPv4 broadcast address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 21)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.255') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv4-broadcast'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv4-broadcast']\n return self.get_ip_on_interface_by_index(interface_name=interface_name, index=-1, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class Base():\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test28_get_interface_broadcast", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002100.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_gateway", "tests": "import unittest\n\nclass Test_get_interface_gateway(unittest.TestCase):\n def test29_get_interface_gateway(self):\n self.assertEqual(self.base.get_interface_gateway(self.variables.your.network_interface, AF_INET, True, 22), self.variables.router.ipv4_address)\n self.assertIsNone(self.base.get_interface_gateway(self.variables.bad.network_interface, AF_INET, False, 22))\n", "method_code": " def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get gateway address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param network_type: Set network type AF_INET for IPv4 network or AF_INET6 for IPv6 (default: AF_INET)\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 22)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Address string (example: '192.168.1.254') or None in case of error\n \"\"\"\n try:\n gateway_address = None\n if self.get_platform().startswith('Windows'):\n routes: Dict[str, str] = dict()\n route_table: List[str] = sub.check_output('route print', shell=True).decode().splitlines()\n if network_type == AF_INET:\n for output_string in route_table:\n if match('^ +[0-9.]{7,15} +[0-9.]{7,15} +[0-9.]{7,15} +[0-9.]{7,15} +\\\\d{1,3}$', output_string):\n address = output_string.split()\n routes[address[3]] = address[2]\n interface_address = self.get_interface_ip_address(interface_name=interface_name, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n if interface_address in routes.keys():\n return routes[interface_address]\n else:\n gws = gateways()\n for gw in gws:\n gateway_interface = gws[gw][network_type]\n gateway_ip, interface = (gateway_interface[0], gateway_interface[1])\n if interface == interface_name:\n gateway_address = gateway_ip\n break\n except KeyError:\n gateway_address = None\n except ValueError:\n gateway_address = None\n except IndexError:\n gateway_address = None\n if gateway_address is None:\n if not quiet:\n if network_type == AF_INET:\n if exit_on_failure:\n self.print_error('Network interface: ', interface_name, ' does not have IPv4 gateway!')\n else:\n self.print_warning('Network interface: ', interface_name, ' does not have IPv4 gateway!')\n if network_type == AF_INET6:\n if exit_on_failure:\n self.print_error('Network interface: ', interface_name, ' does not have IPv6 gateway!')\n else:\n self.print_warning('Network interface: ', interface_name, ' does not have IPv6 gateway!')\n if exit_on_failure:\n exit(exit_code)\n return gateway_address\n ", "context": "class Base():\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test29_get_interface_gateway", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002101.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_ipv4_gateway", "tests": "import unittest\n\nclass Test_get_interface_ipv4_gateway(unittest.TestCase):\n def test30_get_interface_ipv4_gateway(self):\n self.assertEqual(self.base.get_interface_ipv4_gateway(self.variables.your.network_interface, True, 23), self.variables.router.ipv4_address)\n self.assertIsNone(self.base.get_interface_ipv4_gateway(self.variables.bad.network_interface, False, 23))\n", "method_code": " def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get IPv4 gateway address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 23)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.254') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv4-gateway'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv4-gateway']\n return self.get_interface_gateway(interface_name=interface_name, network_type=AF_INET, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class Base():\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test30_get_interface_ipv4_gateway", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002102.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_interface_ipv6_gateway", "tests": "import unittest\n\nclass Test_get_interface_ipv6_gateway(unittest.TestCase):\n def test31_get_interface_ipv6_gateway(self):\n self.assertEqual(self.base.get_interface_ipv6_gateway(self.variables.your.network_interface, True, 24), self.variables.router.ipv6_link_address)\n self.assertIsNone(self.base.get_interface_ipv6_gateway(self.variables.bad.network_interface, False, 24))\n", "method_code": " def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get IPv6 gateway address on network interface\n :param interface_name: Network interface name (default: 'eth0')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 24)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv6 address string (example: 'fd00::1') or None in case of error\n \"\"\"\n if interface_name in self._network_interfaces_settings.keys():\n if self._network_interfaces_settings[interface_name]['ipv6-gateway'] is not None:\n return self._network_interfaces_settings[interface_name]['ipv6-gateway']\n return self.get_interface_gateway(interface_name=interface_name, network_type=AF_INET6, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class Base():\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test31_get_interface_ipv6_gateway", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002103.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "apt_list_installed_packages", "tests": "import unittest\n\nclass Test_apt_list_installed_packages(unittest.TestCase):\n def test32_apt_list_installed_packages(self):\n if self.base.get_platform().startswith('Linux'):\n self.assertIn(b'python3', self.base.apt_list_installed_packages(True, 25))\n self.assertNotIn(b'test_test_test', self.base.apt_list_installed_packages(True, 25))\n", "method_code": " def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Get output of bash command: apt list --installed\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 25)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: result bytes\n \"\"\"\n try:\n apt_list_command = sub.Popen(['apt list --installed'], shell=True, stdout=sub.PIPE, stderr=sub.PIPE)\n apt_list_out, apt_list_err = apt_list_command.communicate()\n assert apt_list_out is not None, 'Something else went wrong while trying to run command: ' + self.error_text('`apt list --installed`')\n self.os_installed_packages_list = apt_list_out\n return apt_list_out\n except OSError:\n error_text = 'Something else went wrong while trying to run command: ' + self.error_text('`apt list --installed`')\n except AssertionError as Error:\n error_text = Error.args[0]\n if not quiet:\n self.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test32_apt_list_installed_packages", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002104.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "check_installed_software", "tests": "import unittest\n\nclass Test_check_installed_software(unittest.TestCase):\n def test33_check_installed_software(self):\n if self.base.get_platform().startswith('Linux'):\n self.assertTrue(self.base.check_installed_software('python3', True, 26))\n self.assertFalse(self.base.check_installed_software('test_test_test', True, 26))\n", "method_code": " def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool:\n \"\"\"\n Check software is installed or not\n :param software_name: Name of software (default: 'apache2')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 26)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: True or False\n \"\"\"\n try:\n assert self.check_platform(exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet), 'This is not a Linux platform'\n assert not ('Kali' in linux_distribution() or 'Debian' in linux_distribution() or 'Ubuntu' in linux_distribution()), 'Unable to verify OS installed software. ' + 'This function works normal only in Debian, Ubuntu or Kali linux.'\n if self.os_installed_packages_list is None:\n self.apt_list_installed_packages(exit_on_failure)\n assert self.os_installed_packages_list is not None, 'Unable to verify OS installed software.'\n if software_name.encode(encoding='utf-8') in self.os_installed_packages_list:\n return True\n elif isfile('/bin/' + software_name) or isfile('/sbin/' + software_name) or isfile('/usr/bin/' + software_name) or isfile('/usr/sbin/' + software_name) or isfile('/usr/local/bin/' + software_name) or isfile('/usr/local/sbin/' + software_name):\n return True\n else:\n return False\n except AssertionError as Error:\n error_text = Error.args[0]\n if 'Debian, Ubuntu or Kali linux' in error_text:\n if not quiet:\n self.print_warning(error_text)\n if isfile('/bin/' + software_name) or isfile('/sbin/' + software_name) or isfile('/usr/bin/' + software_name) or isfile('/usr/sbin/' + software_name) or isfile('/usr/local/bin/' + software_name) or isfile('/usr/local/sbin/' + software_name):\n return True\n else:\n return False\n else:\n if not quiet:\n self.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return False\n ", "context": "class Base():\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test33_check_installed_software", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002105.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "ipv6_address_validation", "tests": "import unittest\n\nclass Test_ipv6_address_validation(unittest.TestCase):\n def test40_ipv6_address_validation(self):\n self.assertTrue(self.base.ipv6_address_validation('fd00::1', True, 28))\n self.assertFalse(self.base.ipv6_address_validation('fd00:::1', False, 28))\n", "method_code": " def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool:\n \"\"\"\n Validate IPv6 address string\n :param ipv6_address: IPv6 address string (example: 'fd00::1')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 28)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: True if a valid IPv6 address or False if not\n \"\"\"\n try:\n sock.inet_pton(sock.AF_INET6, ipv6_address)\n return True\n except sock.error:\n if not quiet:\n self.print_error('Failed to validate IPv6 address: ', str(ipv6_address))\n if exit_on_failure:\n exit(exit_code)\n return False\n ", "context": "class Base():\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test40_ipv6_address_validation", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002106.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "ip_address_validation", "tests": "import unittest\n\nclass Test_ip_address_validation(unittest.TestCase):\n def test41_ip_address_validation(self):\n self.assertTrue(self.base.ip_address_validation('192.168.1.1', True, 29))\n self.assertFalse(self.base.ip_address_validation('192.168.1.1.1', False, 29))\n", "method_code": " def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool:\n \"\"\"\n Validate IPv4 address string\n :param ip_address: IPv4 address string (example: '192.168.1.1')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 29)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: True if a valid IPv4 address or False if not\n \"\"\"\n try:\n sock.inet_aton(ip_address)\n return True\n except sock.error:\n if not quiet:\n self.print_error('Failed to validate IP address: ', str(ip_address))\n if exit_on_failure:\n exit(exit_code)\n return False\n ", "context": "class Base():\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test41_ip_address_validation", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002107.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "mac_address_validation", "tests": "import unittest\n\nclass Test_mac_address_validation(unittest.TestCase):\n def test42_mac_address_validation(self):\n self.assertTrue(self.base.mac_address_validation('01:23:45:67:89:0a', True, 30))\n self.assertFalse(self.base.mac_address_validation('01:23:45:67:89:0ab', False, 30))\n", "method_code": " def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool:\n \"\"\"\n Validate MAC address string\n :param mac_address: MAC address string (example: '01:23:45:67:89:0a')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 10)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: True if a valid MAC address or False if not\n \"\"\"\n if match('^([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$', mac_address):\n return True\n else:\n if not quiet:\n self.print_error('Failed to validate MAC address: ', str(mac_address))\n if exit_on_failure:\n exit(exit_code)\n return False\n ", "context": "class Base():\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test42_mac_address_validation", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002108.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "ip_address_in_range", "tests": "import unittest\n\nclass Test_ip_address_in_range(unittest.TestCase):\n def test43_ip_address_in_range(self):\n self.assertTrue(self.base.ip_address_in_range('192.168.1.2', '192.168.1.1', '192.168.1.3', True, 31))\n self.assertFalse(self.base.ip_address_in_range('192.168.1.4', '192.168.1.1', '192.168.1.3', False, 31))\n self.assertFalse(self.base.ip_address_in_range('192.168.1.4.5', '192.168.1.1', '192.168.1.3', False, 31))\n self.assertFalse(self.base.ip_address_in_range('192.168.1.4', '192.168.1.1.2', '192.168.1.3', False, 31))\n self.assertFalse(self.base.ip_address_in_range('192.168.1.4', '192.168.1.1', '192.168.1.3.4', False, 31))\n", "method_code": " def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool:\n \"\"\"\n Check IPv4 address in range\n :param ip_address: IPv4 address string (example: '192.168.1.2')\n :param first_ip_address: First IPv4 address in range (example: '192.168.1.1')\n :param last_ip_address: Last IPv4 address in range (example: '192.168.1.3')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 31)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: True if IPv4 address in range or False if not\n \"\"\"\n try:\n assert IPv4Address(first_ip_address) <= IPv4Address(ip_address) <= IPv4Address(last_ip_address), 'IP address: ' + self.error_text(str(ip_address)) + ' not in range: ' + self.error_text(str(first_ip_address) + ' - ' + str(last_ip_address))\n return True\n except AddressValueError:\n error_text = 'Bad IPv4 address: ' + self.error_text(str(ip_address))\n except AssertionError as Error:\n error_text = Error.args[0]\n if not quiet:\n self.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return False\n ", "context": "class Base():\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test43_ip_address_in_range", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002109.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "ip_address_in_network", "tests": "import unittest\n\nclass Test_ip_address_in_network(unittest.TestCase):\n def test44_ip_address_in_network(self):\n self.assertTrue(self.base.ip_address_in_network('192.168.1.1', '192.168.1.0/24', True, 32))\n self.assertFalse(self.base.ip_address_in_network('192.168.1.254', '192.168.1.0/27', False, 32))\n self.assertFalse(self.base.ip_address_in_network('192.168.1.1.1', '192.168.1.0/27', False, 32))\n self.assertFalse(self.base.ip_address_in_network('192.168.1.1', '192.168.1.0.0/24', False, 32))\n self.assertFalse(self.base.ip_address_in_network('192.168.1.1', '192.168.1.1/33', False, 32))\n", "method_code": " def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool:\n \"\"\"\n Check IPv4 address in network\n :param ip_address: IPv4 address string (example: '192.168.1.1')\n :param network: IPv4 network string (example: '192.168.1.0/24')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 32)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: True if IPv4 address in network or False if not\n \"\"\"\n try:\n assert IPAddress(ip_address) in IPNetwork(network), 'IPv4 address: ' + self.error_text(str(ip_address)) + ' not in IPv4 network: ' + self.error_text(str(network))\n return True\n except AddressValueError:\n error_text = 'Bad IPv4 address: ' + self.error_text(str(ip_address))\n except AddrFormatError:\n error_text = 'Bad IPv4 network: ' + self.error_text(str(network)) + ' or IPv4 address: ' + self.error_text(str(ip_address)) + ' not in IPv4 network: ' + self.error_text(str(network))\n except AssertionError as Error:\n error_text = Error.args[0]\n if not quiet:\n self.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return False\n ", "context": "class Base():\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test44_ip_address_in_network", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002110.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "ip_address_increment", "tests": "import unittest\n\nclass Test_ip_address_increment(unittest.TestCase):\n def test45_ip_address_increment(self):\n self.assertEqual(self.base.ip_address_increment(self.variables.ipv4.first_address, True, 33), self.variables.ipv4.second_address)\n self.assertIsNone(self.base.ip_address_increment('192.168.1.1.1', False, 33))\n", "method_code": " def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Increment IPv4 address\n :param ip_address: IPv4 address string (example: '192.168.1.1')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 33)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.2')\n \"\"\"\n try:\n return str(IPv4Address(ip_address) + 1)\n except AddressValueError:\n if quiet:\n self.print_error('Bad IPv4 address: ', str(ip_address))\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test45_ip_address_increment", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002111.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "ip_address_decrement", "tests": "import unittest\n\nclass Test_ip_address_decrement(unittest.TestCase):\n def test46_ip_address_decrement(self):\n self.assertEqual(self.base.ip_address_decrement(self.variables.ipv4.second_address, True, 34), self.variables.ipv4.first_address)\n self.assertIsNone(self.base.ip_address_decrement('192.168.1.1.1', False, 34))\n", "method_code": " def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Decrement IPv4 address\n :param ip_address: IPv4 address string (example: '192.168.1.2')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 33)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv4 address string (example: '192.168.1.1')\n \"\"\"\n try:\n return str(IPv4Address(ip_address) - 1)\n except AddressValueError:\n if quiet:\n self.print_error('Bad IPv4 address: ', str(ip_address))\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class Base():\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test46_ip_address_decrement", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002112.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "ip_address_compare", "tests": "import unittest\n\nclass Test_ip_address_compare(unittest.TestCase):\n def test47_ip_address_compare(self):\n self.assertFalse(self.base.ip_address_compare('192.168.1.1.1', '192.168.1.2', 'eq', False, 35))\n self.assertFalse(self.base.ip_address_compare('192.168.1.1', '192.168.1.2.2', 'eq', False, 35))\n self.assertTrue(self.base.ip_address_compare('192.168.1.1', '192.168.1.1', 'eq', True, 35))\n self.assertFalse(self.base.ip_address_compare('192.168.1.1', '192.168.1.2', 'eq', False, 35))\n self.assertTrue(self.base.ip_address_compare('192.168.1.1', '192.168.1.2', 'ne', True, 35))\n self.assertFalse(self.base.ip_address_compare('192.168.1.1', '192.168.1.1', 'ne', False, 35))\n self.assertTrue(self.base.ip_address_compare('192.168.1.2', '192.168.1.1', 'gt', True, 35))\n self.assertFalse(self.base.ip_address_compare('192.168.1.2', '192.168.1.2', 'gt', False, 35))\n self.assertTrue(self.base.ip_address_compare('192.168.1.2', '192.168.1.1', 'ge', True, 35))\n self.assertFalse(self.base.ip_address_compare('192.168.1.2', '192.168.1.3', 'ge', False, 35))\n self.assertTrue(self.base.ip_address_compare('192.168.1.1', '192.168.1.2', 'lt', True, 35))\n self.assertFalse(self.base.ip_address_compare('192.168.1.2', '192.168.1.2', 'lt', False, 35))\n self.assertTrue(self.base.ip_address_compare('192.168.1.1', '192.168.1.2', 'le', True, 35))\n self.assertFalse(self.base.ip_address_compare('192.168.1.2', '192.168.1.1', 'le', False, 35))\n", "method_code": " def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool:\n \"\"\"\n Compare IPv4 addresses\n :param first_ip_address: First IPv4 address for compare (example: 192.168.0.1)\n :param second_ip_address: Second IPv4 address for compare (example: 192.168.0.2)\n :param operator: eq - equal; ne - not equal; gt - greater; ge - greater or equal; lt - less; le - less or equal (default: eq)\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 33)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: True or False\n \"\"\"\n try:\n assert operator == 'eq' or operator == 'ne' or operator == 'gt' or (operator == 'ge') or (operator == 'lt') or (operator == 'le'), 'Bad operator: ' + self.error_text(str(operator)) + ' acceptable operator values: ' + self.info_text('eq - equal; ne - not equal; ' + 'gt - greater; ge - greater or equal; ' + 'lt - less; le - less or equal')\n if operator == 'eq':\n if IPv4Address(first_ip_address) == IPv4Address(second_ip_address):\n return True\n else:\n return False\n elif operator == 'ne':\n if IPv4Address(first_ip_address) != IPv4Address(second_ip_address):\n return True\n else:\n return False\n elif operator == 'gt':\n if IPv4Address(first_ip_address) > IPv4Address(second_ip_address):\n return True\n else:\n return False\n elif operator == 'ge':\n if IPv4Address(first_ip_address) >= IPv4Address(second_ip_address):\n return True\n else:\n return False\n elif operator == 'lt':\n if IPv4Address(first_ip_address) < IPv4Address(second_ip_address):\n return True\n else:\n return False\n elif operator == 'le':\n if IPv4Address(first_ip_address) <= IPv4Address(second_ip_address):\n return True\n else:\n return False\n except AssertionError as Error:\n error_text = Error.args[0]\n except AddressValueError:\n error_text = 'Bad ip address in input parameters'\n if not quiet:\n self.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return False\n ", "context": "class Base():\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test47_ip_address_compare", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002113.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "make_random_string", "tests": "import unittest\n\nclass Test_make_random_string(unittest.TestCase):\n def test48_make_random_string(self):\n self.assertEqual(len(self.base.make_random_string(8)), 8)\n", "method_code": " def make_random_string(self, length: int=8) -> str:\n \"\"\"\n Make random string from lowercase letter, uppercase letter and digits\n :param length: Length of string (default: 8)\n :return: Random string (example: d1dfJ3a032)\n \"\"\"\n return ''.join((choice(self.lowercase_letters + self.uppercase_letters + self.digits) for _ in range(length)))\n ", "context": "class Base():\n def make_random_string(self, length: int=8) -> str: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def get_system_name_servers() -> List[str]: ...\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test48_make_random_string", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002114.py"} {"focal_file": "raw_packet/Utils/base.py", "focal_class": null, "focal_method": "get_vendor_by_mac_address", "tests": "import unittest\n\nclass Test_get_vendor_by_mac_address(unittest.TestCase):\n def test50_get_vendor_by_mac_address(self):\n self.assertEqual(self.base.get_vendor_by_mac_address('00:00:01:23:45:67'), 'Xerox Corporation')\n", "method_code": " def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str:\n \"\"\"\n Get vendor of host by MAC address\n :param mac_address: MAC address of host (example: '01:23:45:67:89:0a')\n :return: Vendor string\n \"\"\"\n if not self.mac_address_validation(mac_address):\n return 'Unknown vendor'\n mac_address: str = mac_address.upper()\n for vendor_mac_prefix in self.vendors.keys():\n if mac_address.startswith(vendor_mac_prefix):\n return self.vendors[vendor_mac_prefix]\n return 'Unknown vendor'\n ", "context": "class Base():\n def get_vendor_by_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def __init__(self, admin_only: bool=True, available_platforms: List[str]=['Linux', 'Darwin', 'Windows']) -> None: ...\n def get_banner(self, script_name: Union[None, str]=None) -> str: ...\n def print_banner(self, script_name: Union[None, str]=None) -> None: ...\n def _color_print(self, color: str='blue', *strings: str) -> None: ...\n def _color_text(self, color: str='blue', string: str='') -> str: ...\n def print_info(self, *strings: str) -> None: ...\n def print_error(self, *strings: str) -> None: ...\n def print_warning(self, *strings: str) -> None: ...\n def print_success(self, *strings: str) -> None: ...\n def info_text(self, text: str) -> str: ...\n def error_text(self, text: str) -> str: ...\n def warning_text(self, text: str) -> str: ...\n def success_text(self, text: str) -> str: ...\n def get_platform(self) -> str: ...\n def check_platform(self, available_platforms: List[str]=['Linux', 'Darwin', 'Windows'], exit_on_failure: bool=True, exit_code: int=1, quiet: bool=False) -> bool: ...\n def check_user(exit_on_failure: bool=True, exit_code: int=2, quiet: bool=False) -> bool: ...\n def pack8(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=3, quiet: bool=False) -> Union[None, bytes]: ...\n def pack16(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=4, quiet: bool=False) -> Union[None, bytes]: ...\n def pack32(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=5, quiet: bool=False) -> Union[None, bytes]: ...\n def pack64(data: Union[int, str, bytes], exit_on_failure: bool=True, exit_code: int=6, quiet: bool=False) -> Union[None, bytes]: ...\n def list_of_network_interfaces(self) -> Union[None, List[str]]: ...\n def list_of_wireless_network_interfaces(self) -> List[str]: ...\n def network_interface_selection(self, interface_name: Union[None, str]=None, exclude_interface: Union[None, str]=None, only_wireless: bool=False, message: Union[None, str]=None) -> str: ...\n def check_network_interface_is_wireless(self, interface_name: str='wlan0') -> bool: ...\n def get_interface_settings(self, interface_name: str='eth0', required_parameters: List[str]=['mac-address'], quiet: bool=True) -> Dict[str, Union[None, str, List[str]]]: ...\n def get_wireless_interface_settings(self, interface_name: str='wlan0') -> Dict[str, Union[None, int, str]]: ...\n def get_interface_mac_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=7, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ip_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=8, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_address(self, interface_name: str='eth0', address_index: int=0, exit_on_failure: bool=False, exit_code: int=9, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_link_address(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=10, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_glob_address(self, interface_name: str='eth0') -> Union[None, str]: ...\n def get_interface_ipv6_glob_addresses(self, interface_name: str='eth0') -> List[str]: ...\n def make_ipv6_link_address(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=12, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_netmask(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=13, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_network(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=14, quiet: bool=False) -> Union[None, str]: ...\n def get_ip_on_interface_by_index(self, interface_name: str='eth0', index: int=1, exit_on_failure: bool=True, exit_code: int=15, quiet: bool=False) -> Union[None, str]: ...\n def get_first_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=16, quiet: bool=False) -> Union[None, str]: ...\n def get_second_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=17, quiet: bool=False) -> Union[None, str]: ...\n def get_penultimate_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=18, quiet: bool=False) -> Union[None, str]: ...\n def get_last_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=19, quiet: bool=False) -> Union[None, str]: ...\n def get_random_ip_on_interface(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=20, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_broadcast(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=21, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_gateway(self, interface_name: str='eth0', network_type: int=AF_INET, exit_on_failure: bool=True, exit_code: int=22, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv4_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=23, quiet: bool=False) -> Union[None, str]: ...\n def get_interface_ipv6_gateway(self, interface_name: str='eth0', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> Union[None, str]: ...\n def add_multicast_mac_address(self, interface_name: str='eth0', multicast_mac_address: str='33:33:00:00:00:02', exit_on_failure: bool=True, exit_code: int=24, quiet: bool=False) -> bool: ...\n def apt_list_installed_packages(self, exit_on_failure: bool=True, exit_code: int=25, quiet: bool=False) -> Union[None, bytes]: ...\n def check_installed_software(self, software_name: str='apache2', exit_on_failure: bool=True, exit_code: int=26, quiet: bool=False) -> bool: ...\n def check_process(process_name: str='systemd') -> int: ...\n def get_process_pid(self, process_name: str='systemd') -> int: ...\n def get_process_pid_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=27, quiet: bool=False) -> Union[None, List[int]]: ...\n def kill_process(self, process_pid: int) -> bool: ...\n def kill_process_by_name(self, process_name: str='apache2') -> bool: ...\n def kill_processes_by_listen_port(self, listen_port: int=80, listen_address: Union[None, str]=None, listen_proto: str='tcp') -> bool: ...\n def ipv6_address_validation(self, ipv6_address: str='fd00::1', exit_on_failure: bool=False, exit_code: int=28, quiet: bool=True) -> bool: ...\n def ip_address_validation(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=29, quiet: bool=True) -> bool: ...\n def mac_address_validation(self, mac_address: str='01:23:45:67:89:0a', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> bool: ...\n def mac_address_normalization(self, mac_address: str='AB:CD:EF:AB:CD:EF', exit_on_failure: bool=False, exit_code: int=30, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_in_range(self, ip_address: str='192.168.1.2', first_ip_address: str='192.168.1.1', last_ip_address: str='192.168.1.3', exit_on_failure: bool=False, exit_code: int=31, quiet: bool=False) -> bool: ...\n def ip_address_in_network(self, ip_address: str='192.168.1.1', network: str='192.168.1.0/24', exit_on_failure: bool=False, exit_code: int=32, quiet: bool=True) -> bool: ...\n def ip_address_increment(self, ip_address: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=33, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_decrement(self, ip_address: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=34, quiet: bool=False) -> Union[None, str]: ...\n def ip_address_compare(self, first_ip_address: str='192.168.1.1', second_ip_address: str='192.168.1.1', operator: str='eq', exit_on_failure: bool=False, exit_code: int=35, quiet: bool=False) -> bool: ...\n def make_random_string(self, length: int=8) -> str: ...\n def get_system_name_servers() -> List[str]: ...\n def macos_encode_mac_address(self, mac_address: str='01:23:45:67:89:0a') -> str: ...\n def exec_command_over_ssh(self, command: str='ifconfig', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', need_output: bool=True, exit_on_failure: bool=True) -> Union[None, bool, str]: ...\n def download_file_over_ssh(self, remote_path: str='/tmp/test.txt', local_path: str='test.txt', ssh_user: str='root', ssh_password: Union[None, str]=None, ssh_pkey: Union[None, RSAKey]=None, ssh_host: str='192.168.0.1', exit_on_failure: bool=True) -> Union[bool]: ...\n\n os_installed_packages_list = None\n _windows_mac_address_regex = compile('([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})')\n _windows_adapters = None\n", "repository": "raw-packet/raw-packet", "test_name": "test50_get_vendor_by_mac_address", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002115.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_random_mac", "tests": "import unittest\n\nclass Test_make_random_mac(unittest.TestCase):\n def test_ethernet_make_random_mac(self):\n self.assertTrue(self.base.mac_address_validation(self.ethernet.make_random_mac()))\n", "method_code": " def make_random_mac(self) -> str:\n \"\"\"\n Make random MAC address\n :return: Random MAC address string (example: '01:23:45:67:89:0a')\n \"\"\"\n mac_prefix = choice(self.macs)\n mac_suffix = ':'.join(('{0:02x}'.format(randint(0, 255), 'x') for _ in range(3)))\n return mac_prefix + ':' + mac_suffix\n ", "context": "class RawEthernet():\n def make_random_mac(self) -> str: ...\n def __init__(self): ...\n def __enter__(self): ...\n def convert_mac(self, mac_address: Union[str, bytes]='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=41, quiet: bool=False) -> Union[None, bytes, str]: ...\n def get_mac_prefix(self, mac_address: Union[str, bytes]='01:23:45:67:89:0a', prefix_length: int=3, exit_on_failure: bool=True, exit_code: int=42, quiet: bool=False) -> Union[None, str]: ...\n def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_header(self, source_mac: str='01:23:45:67:89:0a', destination_mac: str='01:23:45:67:89:0b', network_type: int=2048, exit_on_failure: bool=False, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_ethernet_make_random_mac", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002116.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "convert_mac", "tests": "import unittest\n\nclass Test_convert_mac(unittest.TestCase):\n def test_ethernet_convert_mac(self):\n self.assertEqual(self.ethernet.convert_mac('30:31:32:33:34:35', True, 41), b'012345')\n self.assertEqual(self.ethernet.convert_mac(b'012345', True, 41), '30:31:32:33:34:35')\n self.assertIsNone(self.ethernet.convert_mac('30:31:32:33:34:356', False, 41))\n self.assertIsNone(self.ethernet.convert_mac('30:31:32:33:34567', False, 41))\n self.assertIsNone(self.ethernet.convert_mac(b'01234', False, 41))\n", "method_code": " def convert_mac(self, mac_address: Union[str, bytes]='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=41, quiet: bool=False) -> Union[None, bytes, str]:\n \"\"\"\n Convert MAC address string or bytes to bytes\n :param mac_address: MAC address string or bytes (example: '01:23:45:67:89:0a' or b'\\x01#Eg\\x89\n ')\n :param exit_on_failure: Exit in case of error (default: True)\n :param exit_code: Set exit code integer (default: 41)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Result bytes or string (example: b'\\x01#Eg\\x89\n ' or '01:23:45:67:89:0a') or None if error\n \"\"\"\n try:\n if len(mac_address) == 17 and type(mac_address) == str:\n mac_address: str = str(mac_address).lower()\n assert search('([0-9a-f]{2}[:-]){5}([0-9a-f]{2})', mac_address), 'Bad MAC address: ' + self.base.error_text(str(mac_address))\n return unhexlify(mac_address.replace(':', ''))\n elif len(mac_address) == 6 and type(mac_address) == bytes:\n result_mac_address: str = ''\n for byte_of_address in mac_address:\n result_mac_address += '{:02x}'.format(byte_of_address) + ':'\n return result_mac_address[:-1].lower()\n else:\n raise AssertionError('Bad MAC address length: ' + self.base.error_text(str(len(mac_address))))\n except AssertionError as Error:\n if not quiet:\n self.base.print_error(Error.args[0])\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawEthernet():\n def convert_mac(self, mac_address: Union[str, bytes]='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=41, quiet: bool=False) -> Union[None, bytes, str]: ...\n def __init__(self): ...\n def __enter__(self): ...\n def make_random_mac(self) -> str: ...\n def get_mac_prefix(self, mac_address: Union[str, bytes]='01:23:45:67:89:0a', prefix_length: int=3, exit_on_failure: bool=True, exit_code: int=42, quiet: bool=False) -> Union[None, str]: ...\n def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_header(self, source_mac: str='01:23:45:67:89:0a', destination_mac: str='01:23:45:67:89:0b', network_type: int=2048, exit_on_failure: bool=False, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_ethernet_convert_mac", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002117.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "get_mac_prefix", "tests": "import unittest\n\nclass Test_get_mac_prefix(unittest.TestCase):\n def test_ethernet_get_mac_prefix(self):\n self.assertEqual(self.ethernet.get_mac_prefix('ab:cd:ef:01:23:45', 3, True, 42), 'ABCDEF')\n self.assertEqual(self.ethernet.get_mac_prefix(b'012345', 3, True, 42), '303132')\n self.assertIsNone(self.ethernet.get_mac_prefix('30:31:32:33:34:356', 3, False, 42))\n self.assertIsNone(self.ethernet.get_mac_prefix('30:31:32:33:34567', 3, False, 42))\n self.assertIsNone(self.ethernet.get_mac_prefix(b'01234', 3, False, 42))\n", "method_code": " def get_mac_prefix(self, mac_address: Union[str, bytes]='01:23:45:67:89:0a', prefix_length: int=3, exit_on_failure: bool=True, exit_code: int=42, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Get MAC address prefix string\n :param mac_address: MAC address string or bytes (example: 'ab:c3:45:67:89:0a' or b'«ÃEg\\x89\n ')\n :param prefix_length: Length bytes of prefix (default: 3)\n :param exit_on_failure: Exit in case of error (default: True)\n :param exit_code: Set exit code integer (default: 42)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: MAC address prefix string (example: 'ABC345') or None if error\n \"\"\"\n try:\n if len(mac_address) == 17 and type(mac_address) == str:\n mac_address: str = str(mac_address).lower()\n assert search('([0-9a-f]{2}[:-]){5}([0-9a-f]{2})', mac_address), 'Bad MAC address: ' + self.base.error_text(str(mac_address))\n result_mac_address: str = mac_address.replace(':', '')\n return result_mac_address[:prefix_length * 2].upper()\n elif len(mac_address) == 6 and type(mac_address) == bytes:\n result_mac_address: str = ''\n for byte_of_address in mac_address[0:prefix_length]:\n result_mac_address += '{:02x}'.format(byte_of_address)\n return result_mac_address.upper()\n else:\n raise AssertionError('Bad MAC address length: ' + self.base.error_text(str(len(mac_address))))\n except AssertionError as Error:\n if not quiet:\n self.base.print_error(Error.args[0])\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawEthernet():\n def get_mac_prefix(self, mac_address: Union[str, bytes]='01:23:45:67:89:0a', prefix_length: int=3, exit_on_failure: bool=True, exit_code: int=42, quiet: bool=False) -> Union[None, str]: ...\n def __init__(self): ...\n def __enter__(self): ...\n def make_random_mac(self) -> str: ...\n def convert_mac(self, mac_address: Union[str, bytes]='01:23:45:67:89:0a', exit_on_failure: bool=True, exit_code: int=41, quiet: bool=False) -> Union[None, bytes, str]: ...\n def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_header(self, source_mac: str='01:23:45:67:89:0a', destination_mac: str='01:23:45:67:89:0b', network_type: int=2048, exit_on_failure: bool=False, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def __exit__(self, exc_type, exc_val, exc_tb): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_ethernet_get_mac_prefix", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002118.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "parse_header", "tests": "import unittest\n\nclass Test_parse_header(unittest.TestCase):\n def test_ethernet_parse_header(self):\n self.assertEqual(self.ethernet.parse_header(b'6789@A012345\\x08\\x00', True, 43), {'destination': '36:37:38:39:40:41', 'source': '30:31:32:33:34:35', 'type': 2048})\n self.assertIsNone(self.ethernet.parse_header(b'6789@A012345\\x08\\x00\\x01', False, 43))\n\n def test_ipv4_parse_header(self):\n self.assertEqual(self.ipv4.parse_header(b'E\\x00\\x00\\x1c\\x01\\x00\\x00\\x00@\\x11\\xf6}' + b'\\xc0\\xa8\\x01\\x01\\xc0\\xa8\\x01\\x02', True, 49), {'version': 4, 'length': 5, 'dscp_ecn': 0, 'total-length': 28, 'identification': 256, 'flags': 0, 'fragment-offset': 0, 'time-to-live': 64, 'protocol': 17, 'checksum': 63101, 'source-ip': '192.168.1.1', 'destination-ip': '192.168.1.2'})\n self.assertIsNone(self.ipv4.parse_header(b'a\\x00\\x00\\x1c\\x8d/\\x00\\x00@\\x11jN' + b'\\xc0\\xa8\\x01\\x01\\xc0\\xa8\\x01\\x02', False, 49))\n self.assertIsNone(self.ipv4.parse_header(b'a\\x00\\x00\\x1c\\x8d/\\x00\\x00@\\x11jN' + b'\\xc0\\xa8\\x01\\x01\\xc0\\xa8\\x01', False, 49))\n\n def test_ipv6_parse_header(self):\n self.assertEqual(self.ipv6.parse_header(b'`\\x00\\x00\\x00\\x00\\x08\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02', True, 53), {'version': 6, 'traffic-class': 0, 'flow-label': 0, 'payload-length': 8, 'next-header': 17, 'hop-limit': 64, 'source-ip': 'fd00::1', 'destination-ip': 'fd00::2'})\n self.assertIsNone(self.ipv6.parse_header(b'`\\x00\\x00\\x00\\x00\\x08\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', False, 53))\n self.assertIsNone(self.ipv6.parse_header(b'E\\x00\\x00\\x00\\x00\\x08\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02', False, 53))\n\n def test_udp_parse_header(self):\n self.assertEqual(self.udp.parse_header(packet=b'\\x14\\xe9\\x14\\xe9\\x00\\x08\\xdc\\x07', exit_on_failure=True, exit_code=55), {'source-port': 5353, 'destination-port': 5353, 'length': 8, 'checksum': 56327})\n self.assertIsNone(self.udp.parse_header(packet=b'\\x14\\xe9\\x14\\xe9\\x00\\x08\\xdc', exit_on_failure=False, exit_code=55))\n", "method_code": " def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]:\n \"\"\"\n Parse Radiotap header\n :param packet: Bytes of packet\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 43)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Parsed Radiotap header dictionary (example: {'revision': 0, 'pad': 0, 'length': 12}) or None if error\n \"\"\"\n try:\n assert len(packet) >= self.header_length, 'Bad packet length: ' + self.base.error_text(str(len(packet))) + ' minimal Radiotap header length: ' + self.base.info_text(str(self.header_length))\n radiotap_detailed = unpack('2BHI', packet[:8])\n return {'revision': int(radiotap_detailed[0]), 'pad': int(radiotap_detailed[1]), 'length': int(radiotap_detailed[2]), 'flags': int(radiotap_detailed[3])}\n except AssertionError as Error:\n error_text = Error.args[0]\n except IndexError:\n error_text = 'Failed to parse Radiotap header!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawRadiotap():\n def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_header(self, revision: int=0, pad: int=0, length: int=8, present_flags: int=0, exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_ethernet_parse_header", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002119.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_header", "tests": "import unittest\n\nclass Test_make_header(unittest.TestCase):\n def test_ethernet_make_header(self):\n self.assertEqual(self.ethernet.make_header('30:31:32:33:34:35', '36:37:38:39:40:41', 2048, True, 44), b'6789@A012345\\x08\\x00')\n self.assertIsNone(self.ethernet.make_header('30:31:32:33:34567', '36:37:38:39:40:41', 2048, False, 44))\n self.assertIsNone(self.ethernet.make_header('30:31:32:33:34:56', '36:37:38:39:40123', 2048, False, 44))\n self.assertIsNone(self.ethernet.make_header('30:31:32:33:34:56', '36:37:38:39:40:41', 123123, False, 44))\n\n def test_ipv4_make_header(self):\n self.assertEqual(self.ipv4.make_header(source_ip='192.168.1.1', destination_ip='192.168.1.2', data_len=0, transport_protocol_len=8, transport_protocol_type=17, ttl=64, identification=1, exit_on_failure=True, exit_code=50), b'E\\x00\\x00\\x1c\\x01\\x00\\x00\\x00@\\x11\\xf6}\\xc0\\xa8\\x01\\x01\\xc0\\xa8\\x01\\x02')\n self.assertIsNone(self.ipv4.make_header(source_ip='192.168.1.300', destination_ip='192.168.1.2', data_len=0, transport_protocol_len=8, transport_protocol_type=17, ttl=64, identification=1, exit_on_failure=False, exit_code=50))\n self.assertIsNone(self.ipv4.make_header(source_ip='192.168.1.1', destination_ip='192.168.1.400', data_len=0, transport_protocol_len=8, transport_protocol_type=17, ttl=64, identification=1, exit_on_failure=False, exit_code=50))\n self.assertIsNone(self.ipv4.make_header(source_ip='192.168.1.1', destination_ip='192.168.1.2', data_len=0, transport_protocol_len=8, transport_protocol_type=17, ttl=64, identification=123123, exit_on_failure=False, exit_code=50))\n self.assertIsNone(self.ipv4.make_header(source_ip='192.168.1.1', destination_ip='192.168.1.2', data_len=123123, transport_protocol_len=8, transport_protocol_type=17, ttl=64, identification=1, exit_on_failure=False, exit_code=50))\n self.assertIsNone(self.ipv4.make_header(source_ip='192.168.1.1', destination_ip='192.168.1.2', data_len=0, transport_protocol_len=123123, transport_protocol_type=17, ttl=64, identification=1, exit_on_failure=False, exit_code=50))\n self.assertIsNone(self.ipv4.make_header(source_ip='192.168.1.1', destination_ip='192.168.1.2', data_len=0, transport_protocol_len=8, transport_protocol_type=123123, ttl=64, identification=1, exit_on_failure=False, exit_code=50))\n self.assertIsNone(self.ipv4.make_header(source_ip='192.168.1.1', destination_ip='192.168.1.2', data_len=0, transport_protocol_len=8, transport_protocol_type=17, ttl=123123, identification=1, exit_on_failure=False, exit_code=50))\n\n def test_ipv6_make_header(self):\n self.assertEqual(self.ipv6.make_header(source_ip='fd00::1', destination_ip='fd00::2', traffic_class=0, flow_label=0, payload_len=8, next_header=17, hop_limit=64, exit_on_failure=True, exit_code=54), b'`\\x00\\x00\\x00\\x00\\x08\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02')\n self.assertIsNone(self.ipv6.make_header(source_ip='fd00:::1', destination_ip='fd00::2', traffic_class=0, flow_label=0, payload_len=8, next_header=17, hop_limit=64, exit_on_failure=False, exit_code=54))\n self.assertIsNone(self.ipv6.make_header(source_ip='fd00::1', destination_ip='fd00:::2', traffic_class=0, flow_label=0, payload_len=8, next_header=17, hop_limit=64, exit_on_failure=False, exit_code=54))\n self.assertIsNone(self.ipv6.make_header(source_ip='fd00::1', destination_ip='fd00::2', traffic_class=123123123, flow_label=0, payload_len=8, next_header=17, hop_limit=64, exit_on_failure=False, exit_code=54))\n self.assertIsNone(self.ipv6.make_header(source_ip='fd00::1', destination_ip='fd00::2', traffic_class=0, flow_label=123123123123, payload_len=8, next_header=17, hop_limit=64, exit_on_failure=False, exit_code=54))\n self.assertIsNone(self.ipv6.make_header(source_ip='fd00::1', destination_ip='fd00::2', traffic_class=0, flow_label=0, payload_len=123123123123, next_header=17, hop_limit=64, exit_on_failure=False, exit_code=54))\n self.assertIsNone(self.ipv6.make_header(source_ip='fd00::1', destination_ip='fd00::2', traffic_class=0, flow_label=0, payload_len=8, next_header=123123123123123, hop_limit=64, exit_on_failure=False, exit_code=54))\n self.assertIsNone(self.ipv6.make_header(source_ip='fd00::1', destination_ip='fd00::2', traffic_class=0, flow_label=0, payload_len=8, next_header=17, hop_limit=123123123123123, exit_on_failure=False, exit_code=54))\n\n def test_udp_make_header(self):\n self.assertEqual(self.udp.make_header(source_port=5353, destination_port=5353, data_length=0, exit_on_failure=True, exit_code=56), b'\\x14\\xe9\\x14\\xe9\\x00\\x08\\x00\\x00')\n self.assertIsNone(self.udp.make_header(source_port=123123, destination_port=5353, data_length=0, exit_on_failure=False, exit_code=56))\n self.assertIsNone(self.udp.make_header(source_port=5353, destination_port=123123, data_length=0, exit_on_failure=False, exit_code=56))\n self.assertIsNone(self.udp.make_header(source_port=5353, destination_port=5353, data_length=123123, exit_on_failure=False, exit_code=56))\n", "method_code": " def make_header(self, revision: int=0, pad: int=0, length: int=8, present_flags: int=0, exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make Radiotap header\n :param revision: Radiotap header revision (default: 0)\n :param pad: Radiotap header pad (default: 0)\n :param length: Radiotap header length (default: 8)\n :param present_flags: Present flags (default: 0x00000000)\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 44)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes Radiotap of header or None if error\n \"\"\"\n error_text: str = 'Failed to make Radiotap header!'\n packet: bytes = b''\n try:\n assert length >= self.header_length, ' Minimal Radiotap header length - ' + self.base.error_text(str(self.header_length))\n packet += pack('B', revision)\n packet += pack('B', pad)\n packet += pack('H', length)\n packet += pack('I', present_flags)\n return packet\n except struct_error as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'revision' in traceback_text:\n error_text += ' Bad revision: ' + self.base.error_text(str(revision)) + ' revision must be in range: ' + self.base.info_text(str('0 - 255'))\n if 'pad' in traceback_text:\n error_text += ' Bad pad: ' + self.base.error_text(str(pad)) + ' pad must be in range: ' + self.base.info_text(str('0 - 255'))\n if 'length' in traceback_text:\n error_text += ' Bad length: ' + self.base.error_text(str(length)) + ' length must be in range: ' + self.base.info_text(str('12 - 65535'))\n if 'present_flags' in traceback_text:\n error_text += ' Bad present_flags: ' + self.base.error_text(str(present_flags)) + ' present_flags must be in range: ' + self.base.info_text(str('0 - 4294967295'))\n except AssertionError as Error:\n error_text += Error.args[0]\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawRadiotap():\n def make_header(self, revision: int=0, pad: int=0, length: int=8, present_flags: int=0, exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_ethernet_make_header", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002120.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "parse_packet", "tests": "import unittest\n\nclass Test_parse_packet(unittest.TestCase):\n def test_arp_parse_packet(self):\n self.assertEqual(self.arp.parse_packet(b'\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x01\\x01#Eg\\x89\\n\\xc0\\xa8\\x01\\x01\\x01' + b'#Eg\\x89\\x0b\\xc0\\xa8\\x01\\x02', True, 45), {'hardware-type': 1, 'protocol-type': 2048, 'hardware-size': 6, 'protocol-size': 4, 'opcode': 1, 'sender-mac': '01:23:45:67:89:0a', 'sender-ip': '192.168.1.1', 'target-mac': '01:23:45:67:89:0b', 'target-ip': '192.168.1.2'})\n self.assertIsNone(self.arp.parse_packet(b'\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x01\\x01#Eg\\x89\\n\\xc0\\xa8\\x01\\x01\\x01' + b'#Eg\\x89\\x0b\\xc0\\xa8\\x01\\x02\\x03', False, 45))\n\n def test_dns_parse_packet(self):\n self.assertEqual(self.dns.parse_packet(packet=b'\\x00\\x01\\x81\\x80\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x00' + b'\\x04test\\x03com\\x00\\x00\\x01\\x00\\x01\\x04test\\x03com\\x00' + b'\\x00\\x01\\x00\\x01\\x00\\x00\\xff\\xff\\x00\\x04\\xc0\\xa8\\x01\\x01', exit_on_failure=True, exit_code=67), {'additional-rrs': 0, 'answer-rrs': 1, 'authority-rrs': 0, 'questions': 1, 'flags': 33152, 'transaction-id': 1, 'answers': [{'address': '192.168.1.1', 'class': 1, 'name': 'test.com.', 'ttl': 65535, 'type': 1}], 'queries': [{'class': 1, 'name': 'test.com.', 'type': 1}]})\n", "method_code": " def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, bytes, Dict[Union[int, str], Union[int, bytes]]]]]:\n \"\"\"\n Parse IEEE 802.11 packet\n :param packet: Bytes of packet\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 43)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Parsed IEEE 802.11 packet dictionary or None if error\n \"\"\"\n try:\n assert len(packet) >= RawIEEE80211.packet_length + 2, 'Bad packet length: ' + self.base.error_text(str(len(packet))) + ' minimal IEEE 802.11 packet length: ' + self.base.info_text(str(self.packet_length + 2))\n iee80211_detailed = unpack('!2BH6s6s6s', packet[:self.packet_length - 2])\n sequence_and_fragment = unpack('H', packet[self.packet_length - 2:self.packet_length])[0]\n iee80211_parsed: Dict[str, Union[int, str, bytes, Dict[Union[int, str], Union[int, bytes]]]] = {'type': int(iee80211_detailed[0]), 'flags': int(iee80211_detailed[1]), 'duration': int(iee80211_detailed[2]), 'destination': self.eth.convert_mac(mac_address=iee80211_detailed[3], exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet), 'source': self.eth.convert_mac(mac_address=iee80211_detailed[4], exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet), 'bss id': self.eth.convert_mac(mac_address=iee80211_detailed[5], exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet), 'sequence number': int(sequence_and_fragment & 65520) >> 4, 'fragment number': int(sequence_and_fragment & 15)}\n if len(packet) > self.packet_length + 4:\n if iee80211_parsed['type'] == 128:\n fixed_parameters = unpack('!QHH', packet[self.packet_length:self.packet_length + 12])\n iee80211_parsed['timestamp'] = int(fixed_parameters[0])\n iee80211_parsed['beacon interval'] = int(fixed_parameters[1])\n iee80211_parsed['capabilities information'] = int(fixed_parameters[2])\n iee80211_parsed['tag']: Dict[int, bytes] = dict()\n position = self.packet_length + 12\n while position < len(packet) - 1:\n tag_number = int(unpack('B', packet[position:position + 1])[0])\n tag_length = int(unpack('B', packet[position + 1:position + 2])[0])\n tag_value = bytes(packet[position + 2:position + 2 + tag_length])\n iee80211_parsed['tag'][tag_number] = tag_value\n position += 2 + tag_length\n if iee80211_parsed['type'] == 136:\n if iee80211_parsed['flags'] == 1 or iee80211_parsed['flags'] == 2:\n iee80211_parsed['qos control'] = unpack('!H', packet[self.packet_length:self.packet_length + 2])[0]\n iee80211_parsed['logical-link control']: Dict[str, Union[int, bytes]] = dict()\n logical_link_control = unpack('3B', packet[self.packet_length + 2:self.packet_length + 5])\n iee80211_parsed['logical-link control']['dsap'] = int(logical_link_control[0])\n iee80211_parsed['logical-link control']['ssap'] = int(logical_link_control[1])\n iee80211_parsed['logical-link control']['control field'] = int(logical_link_control[2])\n iee80211_parsed['logical-link control']['organization code'] = bytes(packet[self.packet_length + 5:self.packet_length + 8])\n iee80211_parsed['logical-link control']['type'] = unpack('!H', packet[self.packet_length + 8:self.packet_length + 10])[0]\n if iee80211_parsed['logical-link control']['type'] == 34958:\n iee80211_parsed['802.11x authentication']: Dict[str, Union[int, bytes]] = dict()\n authentication = unpack('!2BHB2HQ', packet[self.packet_length + 10:self.packet_length + 27])\n iee80211_parsed['802.11x authentication']['version'] = int(authentication[0])\n iee80211_parsed['802.11x authentication']['type'] = int(authentication[1])\n iee80211_parsed['802.11x authentication']['length'] = int(authentication[2])\n iee80211_parsed['802.11x authentication']['key descriptor'] = int(authentication[3])\n iee80211_parsed['802.11x authentication']['key information'] = int(authentication[4])\n iee80211_parsed['802.11x authentication']['key length'] = int(authentication[5])\n iee80211_parsed['802.11x authentication']['replay counter'] = int(authentication[6])\n iee80211_parsed['802.11x authentication']['wpa key nonce'] = bytes(packet[self.packet_length + 27:self.packet_length + 59])\n iee80211_parsed['802.11x authentication']['key iv'] = bytes(packet[self.packet_length + 59:self.packet_length + 75])\n iee80211_parsed['802.11x authentication']['wpa key rsc'] = bytes(packet[self.packet_length + 75:self.packet_length + 83])\n iee80211_parsed['802.11x authentication']['wpa key id'] = bytes(packet[self.packet_length + 83:self.packet_length + 91])\n iee80211_parsed['802.11x authentication']['wpa key mic'] = bytes(packet[self.packet_length + 91:self.packet_length + 107])\n iee80211_parsed['802.11x authentication']['wpa key length'] = int(unpack('!H', packet[self.packet_length + 107:self.packet_length + 109])[0])\n iee80211_parsed['802.11x authentication']['wpa key data'] = bytes(packet[self.packet_length + 109:self.packet_length + 109 + iee80211_parsed['802.11x authentication']['wpa key length']])\n assert len(packet) - 4 == self.packet_length + 109 + iee80211_parsed['802.11x authentication']['wpa key length'], 'Bad 802.11x authentication packet'\n iee80211_parsed['frame check sequence'] = unpack('!I', packet[len(packet) - 4:len(packet)])[0]\n if iee80211_parsed['sequence number'] == 0 and iee80211_parsed['flags'] == 2:\n iee80211_parsed['802.11x authentication']['message number'] = 1\n if iee80211_parsed['sequence number'] == 0 and iee80211_parsed['flags'] == 1:\n iee80211_parsed['802.11x authentication']['message number'] = 2\n iee80211_parsed['802.11x authentication']['eapol'] = b''.join([packet[self.packet_length + 10:self.packet_length + 91], b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', pack('!H', iee80211_parsed['802.11x authentication']['wpa key length']), packet[self.packet_length + 109:len(packet) - 4]])\n if iee80211_parsed['sequence number'] == 1 and iee80211_parsed['flags'] == 2:\n iee80211_parsed['802.11x authentication']['message number'] = 3\n if iee80211_parsed['sequence number'] == 1 and iee80211_parsed['flags'] == 1:\n iee80211_parsed['802.11x authentication']['message number'] = 4\n else:\n iee80211_parsed['data'] = packet[self.packet_length:len(packet) - 4]\n iee80211_parsed['frame check sequence'] = unpack('!I', packet[len(packet) - 4:len(packet)])[0]\n else:\n iee80211_parsed['fixed parameters'] = packet[self.packet_length:len(packet)]\n return iee80211_parsed\n except AssertionError as Error:\n error_text = Error.args[0]\n except IndexError:\n error_text = 'Failed to parse IEEE 802.11 packet!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawIEEE80211():\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, bytes, Dict[Union[int, str], Union[int, bytes]]]]]: ...\n def make_packet(self, type: int=0, flags: int=0, duration: int=0, destination_address: str='01:23:45:67:89:0a', source_address: str='01:23:45:67:89:0b', bss_id: str='01:23:45:67:89:0b', fragment_number: int=0, sequence_number: int=0, data: Union[None, bytes]=None, frame_check_sequence: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def make_deauth(self, duration: int=14849, client_address: str='01:23:45:67:89:0a', bss_id: str='01:23:45:67:89:0b', fragment_number: int=0, sequence_number: int=0): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_arp_parse_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002121.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_packet", "tests": "import unittest\n\nclass Test_make_packet(unittest.TestCase):\n def test_arp_make_packet(self):\n self.assertEqual(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 1, 1, 2048, 6, 4, True, 46), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x06\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x01\\x01#Eg\\x89\\n\\xc0\\xa8' + b'\\x01\\x01\\x01#Eg\\x89\\x0b\\xc0\\xa8\\x01\\x02')\n self.assertIsNone(self.arp.make_packet('01:23:45:67:890ab', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 1, 1, 2048, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:890ab', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 1, 1, 2048, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0a', '01:23:45:67:890ab', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 1, 1, 2048, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0a', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:890ab', '192.168.1.2', 1, 1, 2048, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.300', '01:23:45:67:89:0b', '192.168.1.2', 1, 1, 2048, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.400', 1, 1, 2048, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 123123, 1, 2048, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 1, 123123, 2048, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 1, 1, 123123, 6, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 1, 1, 2048, 123123, 4, False, 46))\n self.assertIsNone(self.arp.make_packet('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', 1, 1, 2048, 6, 123123, False, 46))\n", "method_code": " def make_packet(self, type: int=0, flags: int=0, duration: int=0, destination_address: str='01:23:45:67:89:0a', source_address: str='01:23:45:67:89:0b', bss_id: str='01:23:45:67:89:0b', fragment_number: int=0, sequence_number: int=0, data: Union[None, bytes]=None, frame_check_sequence: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make IEEE 802.11 packet\n :param type: IEEE 802.11 type (default: 0)\n :param flags: IEEE 802.11 flags (default: 0)\n :param duration: Duration in microseconds (default: 0)\n :param destination_address: Destination address (example: '01:23:45:67:89:0a')\n :param source_address: Source address (example: '01:23:45:67:89:0b')\n :param bss_id: BSS ID (example: '01:23:45:67:89:0b')\n :param fragment_number: Fragment number (default: 0)\n :param sequence_number: Sequence number (default: 0)\n :param data: Bytes of IEEE 802.11 data\n :param frame_check_sequence: Bytes of frame check sequence\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 44)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of IEEE 802.11 packet or None if error\n \"\"\"\n error_text: str = 'Failed to make IEEE 802.11 packet!'\n packet: bytes = b''\n try:\n assert 0 <= fragment_number <= 15, ' Bad fragment_number: ' + self.base.error_text(str(fragment_number)) + ' fragment_number must be in range: ' + self.base.info_text(str('0 - 15'))\n assert 0 <= sequence_number <= 4095, ' Bad sequence_number: ' + self.base.error_text(str(sequence_number)) + ' sequence_number must be in range: ' + self.base.info_text(str('0 - 4095'))\n packet += pack('B', type)\n packet += pack('B', flags)\n packet += pack('!H', duration)\n packet += self.eth.convert_mac(mac_address=destination_address, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n packet += self.eth.convert_mac(mac_address=source_address, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n packet += self.eth.convert_mac(mac_address=bss_id, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n packet += pack('H', (sequence_number << 4) + fragment_number)\n if data is not None:\n packet += data\n if frame_check_sequence is not None:\n packet += frame_check_sequence\n radiotap_header = self.radio.make_header()\n return radiotap_header + packet\n except struct_error as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'type' in traceback_text:\n error_text += ' Bad type: ' + self.base.error_text(str(type)) + ' type must be in range: ' + self.base.info_text(str('0 - 255'))\n if 'flags' in traceback_text:\n error_text += ' Bad flags: ' + self.base.error_text(str(flags)) + ' flags must be in range: ' + self.base.info_text(str('0 - 255'))\n if 'duration' in traceback_text:\n error_text += ' Bad duration: ' + self.base.error_text(str(duration)) + ' duration must be in range: ' + self.base.info_text(str('0 - 65535'))\n except AssertionError as Error:\n error_text += Error.args[0]\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawIEEE80211():\n def make_packet(self, type: int=0, flags: int=0, duration: int=0, destination_address: str='01:23:45:67:89:0a', source_address: str='01:23:45:67:89:0b', bss_id: str='01:23:45:67:89:0b', fragment_number: int=0, sequence_number: int=0, data: Union[None, bytes]=None, frame_check_sequence: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=43, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, bytes, Dict[Union[int, str], Union[int, bytes]]]]]: ...\n def make_deauth(self, duration: int=14849, client_address: str='01:23:45:67:89:0a', bss_id: str='01:23:45:67:89:0b', fragment_number: int=0, sequence_number: int=0): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_arp_make_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002122.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_request", "tests": "import unittest\n\nclass Test_make_request(unittest.TestCase):\n def test_arp_make_request(self):\n self.assertEqual(self.arp.make_request('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', True, 47), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x06\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x01\\x01#Eg\\x89\\n' + b'\\xc0\\xa8\\x01\\x01\\x01#Eg\\x89\\x0b\\xc0\\xa8\\x01\\x02')\n", "method_code": " def make_request(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', sender_mac: str='01:23:45:67:89:0a', sender_ip: str='192.168.1.1', target_mac: str='01:23:45:67:89:0b', target_ip: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ARP request packet bytes\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0b')\n :param sender_mac: Sender MAC address string in ARP packet (example: '01:23:45:67:89:0a')\n :param sender_ip: Sender IP address string in ARP packet (example: '192.168.1.1')\n :param target_mac: Target MAC address string in ARP packet (example: '01:23:45:67:89:0b')\n :param target_ip: Target IP address string in ARP packet (example: '192.168.1.2')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 47)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of ARP request packet or None if error\n \"\"\"\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, sender_mac=sender_mac, sender_ip=sender_ip, target_mac=target_mac, target_ip=target_ip, opcode=1, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class RawARP():\n def make_request(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', sender_mac: str='01:23:45:67:89:0a', sender_ip: str='192.168.1.1', target_mac: str='01:23:45:67:89:0b', target_ip: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=False) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', sender_mac: str='01:23:45:67:89:0a', sender_ip: str='192.168.1.1', target_mac: str='01:23:45:67:89:0b', target_ip: str='192.168.1.2', opcode: int=1, hardware_type: int=1, protocol_type: int=2048, hardware_size: int=6, protocol_size: int=4, exit_on_failure: bool=False, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_response(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', sender_mac: str='01:23:45:67:89:0a', sender_ip: str='192.168.1.1', target_mac: str='01:23:45:67:89:0b', target_ip: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_arp_make_request", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002123.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_response", "tests": "import unittest\n\nclass Test_make_response(unittest.TestCase):\n def test_arp_make_response(self):\n self.assertEqual(self.arp.make_response('01:23:45:67:89:0a', '01:23:45:67:89:0b', '01:23:45:67:89:0a', '192.168.1.1', '01:23:45:67:89:0b', '192.168.1.2', True, 48), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x06\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x02\\x01#Eg\\x89\\n' + b'\\xc0\\xa8\\x01\\x01\\x01#Eg\\x89\\x0b\\xc0\\xa8\\x01\\x02')\n", "method_code": " def make_response(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', sender_mac: str='01:23:45:67:89:0a', sender_ip: str='192.168.1.1', target_mac: str='01:23:45:67:89:0b', target_ip: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ARP response packet bytes\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0b')\n :param sender_mac: Sender MAC address string in ARP packet (example: '01:23:45:67:89:0a')\n :param sender_ip: Sender IP address string in ARP packet (example: '192.168.1.1')\n :param target_mac: Target MAC address string in ARP packet (example: '01:23:45:67:89:0b')\n :param target_ip: Target IP address string in ARP packet (example: '192.168.1.2')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 48)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of ARP response packet or None if error\n \"\"\"\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, sender_mac=sender_mac, sender_ip=sender_ip, target_mac=target_mac, target_ip=target_ip, opcode=2, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n ", "context": "class RawARP():\n def make_response(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', sender_mac: str='01:23:45:67:89:0a', sender_ip: str='192.168.1.1', target_mac: str='01:23:45:67:89:0b', target_ip: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=False) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', sender_mac: str='01:23:45:67:89:0a', sender_ip: str='192.168.1.1', target_mac: str='01:23:45:67:89:0b', target_ip: str='192.168.1.2', opcode: int=1, hardware_type: int=1, protocol_type: int=2048, hardware_size: int=6, protocol_size: int=4, exit_on_failure: bool=False, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_request(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', sender_mac: str='01:23:45:67:89:0a', sender_ip: str='192.168.1.1', target_mac: str='01:23:45:67:89:0b', target_ip: str='192.168.1.2', exit_on_failure: bool=False, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_arp_make_response", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002124.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_random_ip", "tests": "import unittest\n\nclass Test_make_random_ip(unittest.TestCase):\n def test_ipv4_make_random_ip(self):\n self.assertTrue(self.base.ip_address_validation(self.ipv4.make_random_ip()))\n\n def test_ipv6_make_random_ip(self):\n self.assertTrue(self.base.ipv6_address_validation(self.ipv6.make_random_ip(octets=3, prefix='fd00::', exit_on_failure=True, exit_code=51)))\n self.assertIsNone(self.ipv6.make_random_ip(octets=1, prefix='fd00:::', exit_on_failure=False, exit_code=51))\n self.assertIsNone(self.ipv6.make_random_ip(octets=123, prefix='fd00::', exit_on_failure=False, exit_code=51))\n", "method_code": " def make_random_ip() -> str:\n \"\"\"\n Get random IPv4 address string\n :return: Random IPv4 address string (example: '123.123.123.123')\n \"\"\"\n return '.'.join((str(randint(0, 255)) for _ in range(4)))\n ", "context": "class RawIPv4():\n @staticmethod\n def make_random_ip() -> str: ...\n def _checksum(packet: bytes) -> int: ...\n def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=49, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_header(self, source_ip: str='192.168.1.1', destination_ip: str='192.168.1.2', data_len: int=0, transport_protocol_len: int=8, transport_protocol_type: int=17, ttl: int=64, identification: Union[None, int]=None, exit_on_failure: bool=False, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_ipv4_make_random_ip", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002125.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "pack_addr", "tests": "import unittest\n\nclass Test_pack_addr(unittest.TestCase):\n def test_ipv6_pack_addr(self):\n self.assertEqual(self.ipv6.pack_addr(ipv6_address='3132:3334::1', exit_on_failure=True, exit_code=52), b'1234\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01')\n self.assertIsNone(self.ipv6.pack_addr(ipv6_address='fd00:::1', exit_on_failure=False, exit_code=52))\n", "method_code": " def pack_addr(self, ipv6_address: str='::', exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Pack IPv6 address string to bytes\n :param ipv6_address: IPv6 address string (default: '::')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 52)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: IPv6 address bytes\n \"\"\"\n try:\n if ipv6_address == '::':\n return b''.join((pack('B', 0) for _ in range(16)))\n else:\n return inet_pton(AF_INET6, ipv6_address)\n except OSError:\n error_text = 'Failed to pack IPv6 address: ' + self.base.error_text(str(ipv6_address))\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawIPv6():\n def pack_addr(self, ipv6_address: str='::', exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]: ...\n def make_random_ip(self, octets: int=1, prefix: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, str]: ...\n def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=53, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_header(self, source_ip: str='fd00::1', destination_ip: str='fd00::2', traffic_class: int=0, flow_label: int=0, payload_len: int=8, next_header: int=17, hop_limit: int=64, exit_on_failure: bool=False, exit_code: int=54, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_ipv6_pack_addr", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002126.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_header_with_ipv6_checksum", "tests": "import unittest\n\nclass Test_make_header_with_ipv6_checksum(unittest.TestCase):\n def test_udp_make_header_with_ipv6_checksum(self):\n self.assertEqual(self.udp.make_header_with_ipv6_checksum(ipv6_src='fd00::1', ipv6_dst='fd00::2', port_src=5353, port_dst=5353, payload_len=0, payload_data=b'', exit_on_failure=True, exit_code=57), b'\\x14\\xe9\\x14\\xe9\\x00\\x08\\xdc\\x07')\n self.assertIsNone(self.udp.make_header_with_ipv6_checksum(ipv6_src='fd00:::1', ipv6_dst='fd00::2', port_src=5353, port_dst=5353, payload_len=0, payload_data=b'', exit_on_failure=False, exit_code=57))\n self.assertIsNone(self.udp.make_header_with_ipv6_checksum(ipv6_src='fd00::1', ipv6_dst='fd00:::2', port_src=5353, port_dst=5353, payload_len=0, payload_data=b'', exit_on_failure=False, exit_code=57))\n self.assertIsNone(self.udp.make_header_with_ipv6_checksum(ipv6_src='fd00::1', ipv6_dst='fd00::2', port_src=123123, port_dst=5353, payload_len=0, payload_data=b'', exit_on_failure=False, exit_code=57))\n self.assertIsNone(self.udp.make_header_with_ipv6_checksum(ipv6_src='fd00::1', ipv6_dst='fd00::2', port_src=5353, port_dst=123123, payload_len=0, payload_data=b'', exit_on_failure=False, exit_code=57))\n self.assertIsNone(self.udp.make_header_with_ipv6_checksum(ipv6_src='fd00::1', ipv6_dst='fd00::2', port_src=5353, port_dst=5353, payload_len=123123, payload_data=b'', exit_on_failure=False, exit_code=57))\n", "method_code": " def make_header_with_ipv6_checksum(self, ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', port_src: int=5353, port_dst: int=5353, payload_len: int=0, payload_data: bytes=b'', exit_on_failure: bool=False, exit_code: int=57, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make UDP header with checksum for 6 version Internet protocol\n :param ipv6_src: Source IPv6 address string (example: 'fd00::1')\n :param ipv6_dst: Destination IPv6 address string (example: 'fd00::1')\n :param port_src: Source UDP port integer (example: 5353)\n :param port_dst: Destination UDP port integer (example: 5353)\n :param payload_len: Length of payload integer (example: 0)\n :param payload_data: Payload data (example: b'')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 57)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of header\n \"\"\"\n error_text = 'Failed to make UDP header!'\n psh: bytes = b''\n header: bytes = b''\n try:\n data_length: int = payload_len + self.header_length\n header += pack('!H', port_src)\n header += pack('!H', port_dst)\n header += pack('!H', data_length)\n psh += self.ipv6.pack_addr(exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, ipv6_address=ipv6_src)\n psh += self.ipv6.pack_addr(exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, ipv6_address=ipv6_dst)\n psh += pack('!2B', 0, self.header_type)\n psh += pack('!H', data_length)\n udp_header: Union[None, bytes] = self.make_header(source_port=port_src, destination_port=port_dst, data_length=payload_len, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n checksum: int = self._checksum(psh + udp_header + payload_data)\n header += pack('!H', checksum)\n return header\n except struct_error as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'port_src' in traceback_text:\n error_text += ' Bad source port: ' + self.base.error_text(str(port_src)) + ' source port must be in range: ' + self.base.info_text('1 - 65535')\n if 'port_dst' in traceback_text:\n error_text += ' Bad destination port: ' + self.base.error_text(str(port_dst)) + ' destination port must be in range: ' + self.base.info_text('1 - 65535')\n if 'data_length' in traceback_text:\n error_text += ' Bad data length: ' + self.base.error_text(str(payload_len)) + ' data length must be in range: ' + self.base.info_text('1 - 65527')\n except TypeError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'ipv6_src' in traceback_text:\n error_text += ' Bad source IPv6 address: ' + self.base.error_text(str(ipv6_src)) + ' example IPv6 address: ' + self.base.info_text('fd00::1')\n if 'ipv6_dst' in traceback_text:\n error_text += ' Bad destination IPv6 address: ' + self.base.error_text(str(ipv6_dst)) + ' example IPv6 address: ' + self.base.info_text('fd00::1')\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawUDP():\n def make_header_with_ipv6_checksum(self, ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', port_src: int=5353, port_dst: int=5353, payload_len: int=0, payload_data: bytes=b'', exit_on_failure: bool=False, exit_code: int=57, quiet: bool=False) -> Union[None, bytes]: ...\n def _checksum(packet: bytes) -> int: ...\n def parse_header(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=55, quiet: bool=True) -> Union[None, Dict[str, Union[int, str]]]: ...\n def make_header(self, source_port: int=5353, destination_port: int=5353, data_length: int=0, exit_on_failure: bool=False, exit_code: int=56, quiet: bool=False) -> Union[None, bytes]: ...\n def make_header_with_ipv4_checksum(self, ipv4_src: str='192.168.0.2', ipv4_dst: str='192.168.0.1', port_src: int=5353, port_dst: int=5353, payload_len: int=0, payload_data: bytes=b'', exit_on_failure: bool=False, exit_code: int=57, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_udp_make_header_with_ipv6_checksum", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002127.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "get_top_level_domain", "tests": "import unittest\n\nclass Test_get_top_level_domain(unittest.TestCase):\n def test_dns_get_top_level_domain(self):\n self.assertEqual(self.dns.get_top_level_domain(name='www.test.com'), 'test.com')\n self.assertEqual(self.dns.get_top_level_domain(name='test'), 'test')\n", "method_code": " def get_top_level_domain(name: str='www.test.com') -> str:\n try:\n position: int = name.find('.')\n assert not position == -1, 'Could not find \".\" in domain name!'\n return name[position + 1:]\n except AssertionError:\n return name\n ", "context": "class RawDNS():\n @staticmethod\n def get_top_level_domain(name: str='www.test.com') -> str: ...\n def pack_dns_name(self, name: str='test.com', exit_on_failure: bool=False, exit_code: int=65, quiet: bool=False) -> Union[None, bytes]: ...\n def unpack_dns_name(self, packed_name: bytes=b'\\x04mail\\xc0\\x11', name: str='test.com', exit_on_failure: bool=False, exit_code: int=66, quiet: bool=False) -> Union[None, str]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=67, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, ip_ttl: int=64, udp_src_port: int=53, udp_dst_port: int=5353, transaction_id: int=1, flags: int=33152, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address: List[Dict[str, Union[int, str]]]=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}], name_servers={}, exit_on_failure: bool=False, exit_code: int=68, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv4_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=69, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv6_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='fd00::1', ip_dst: str='fd00::2', ip_ttl: int=64, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=70, quiet: bool=False) -> Union[None, bytes]: ...\n def make_a_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=71, quiet: bool=False) -> Union[None, bytes]: ...\n def make_aaaa_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=72, quiet: bool=False) -> Union[None, bytes]: ...\n def make_any_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=73, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ns_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=74, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dns_get_top_level_domain", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002128.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "pack_dns_name", "tests": "import unittest\n\nclass Test_pack_dns_name(unittest.TestCase):\n def test_dns_pack_dns_name(self):\n self.assertEqual(self.dns.pack_dns_name(name='test.com', exit_on_failure=True, exit_code=65), b'\\x04test\\x03com\\x00')\n self.assertIsNone(self.dns.pack_dns_name(name='AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + '.com', exit_on_failure=False, exit_code=65))\n", "method_code": " def pack_dns_name(self, name: str='test.com', exit_on_failure: bool=False, exit_code: int=65, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Convert DNS name to bytes\n :param name: Domain name string (example: 'test.com')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 65)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of domain name (example: b'\\x04test\\x03com\\x00') or None if error\n \"\"\"\n name_list: List[str] = str(name).split('.')\n result_name: bytes = b''\n try:\n for part_of_name in name_list:\n result_name += pack('!B%ds' % len(part_of_name), len(part_of_name), part_of_name.encode('utf-8'))\n except struct_error:\n if not quiet:\n self.base.print_error('Failed to pack domain name string: ', str(name))\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n return result_name + b'\\x00'\n ", "context": "class RawDNS():\n def pack_dns_name(self, name: str='test.com', exit_on_failure: bool=False, exit_code: int=65, quiet: bool=False) -> Union[None, bytes]: ...\n def get_top_level_domain(name: str='www.test.com') -> str: ...\n def unpack_dns_name(self, packed_name: bytes=b'\\x04mail\\xc0\\x11', name: str='test.com', exit_on_failure: bool=False, exit_code: int=66, quiet: bool=False) -> Union[None, str]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=67, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, ip_ttl: int=64, udp_src_port: int=53, udp_dst_port: int=5353, transaction_id: int=1, flags: int=33152, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address: List[Dict[str, Union[int, str]]]=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}], name_servers={}, exit_on_failure: bool=False, exit_code: int=68, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv4_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=69, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv6_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='fd00::1', ip_dst: str='fd00::2', ip_ttl: int=64, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=70, quiet: bool=False) -> Union[None, bytes]: ...\n def make_a_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=71, quiet: bool=False) -> Union[None, bytes]: ...\n def make_aaaa_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=72, quiet: bool=False) -> Union[None, bytes]: ...\n def make_any_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=73, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ns_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=74, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dns_pack_dns_name", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002129.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "unpack_dns_name", "tests": "import unittest\n\nclass Test_unpack_dns_name(unittest.TestCase):\n def test_dns_unpack_dns_name(self):\n self.assertEqual(self.dns.unpack_dns_name(packed_name=b'\\x03www\\x04test\\x03com\\x00'), 'www.test.com.')\n self.assertEqual(self.dns.unpack_dns_name(packed_name=b'\\x04mail\\xc0\\x11', name='pop3.test.com'), 'mail.test.com')\n self.assertEqual(self.dns.unpack_dns_name(packed_name=b'\\xc0\\x10', name='test.com'), 'test.com')\n self.assertEqual(self.dns.unpack_dns_name(packed_name=b'\\x03www\\xc0\\x0c', name='test.com'), 'www.test.com')\n", "method_code": " def unpack_dns_name(self, packed_name: bytes=b'\\x04mail\\xc0\\x11', name: str='test.com', exit_on_failure: bool=False, exit_code: int=66, quiet: bool=False) -> Union[None, str]:\n \"\"\"\n Under construction\n :param packed_name: Bytes of packed name (example: b'\\x04mailÀ\\x11')\n :param name: Domain name string (example: 'test.com')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 66)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Domain name string (example: 'mail.test.com') or None if error\n \"\"\"\n result_name: str = ''\n position: int = 0\n try:\n name_length = int(unpack('B', packed_name[0:1])[0])\n while name_length != 0:\n if packed_name[position:position + 2] == b'\\xc0\\x11':\n return result_name + self.get_top_level_domain(name)\n elif packed_name[position:position + 2] == b'\\xc0\\x10':\n return name\n elif packed_name[position:position + 2] == b'\\xc0\\x0c':\n return result_name + name\n else:\n result_name += packed_name[position + 1:position + name_length + 1].decode('utf-8') + '.'\n position += name_length + 1\n name_length = int(unpack('!B', packed_name[position:position + 1])[0])\n return result_name\n except struct_error:\n pass\n except UnicodeDecodeError:\n pass\n if not quiet:\n self.base.print_error('Failed to unpack domain name bytes: ', str(name))\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawDNS():\n def unpack_dns_name(self, packed_name: bytes=b'\\x04mail\\xc0\\x11', name: str='test.com', exit_on_failure: bool=False, exit_code: int=66, quiet: bool=False) -> Union[None, str]: ...\n def get_top_level_domain(name: str='www.test.com') -> str: ...\n def pack_dns_name(self, name: str='test.com', exit_on_failure: bool=False, exit_code: int=65, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=67, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, ip_ttl: int=64, udp_src_port: int=53, udp_dst_port: int=5353, transaction_id: int=1, flags: int=33152, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address: List[Dict[str, Union[int, str]]]=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}], name_servers={}, exit_on_failure: bool=False, exit_code: int=68, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv4_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=69, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv6_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='fd00::1', ip_dst: str='fd00::2', ip_ttl: int=64, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=70, quiet: bool=False) -> Union[None, bytes]: ...\n def make_a_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=71, quiet: bool=False) -> Union[None, bytes]: ...\n def make_aaaa_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=72, quiet: bool=False) -> Union[None, bytes]: ...\n def make_any_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=73, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ns_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=74, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dns_unpack_dns_name", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002130.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_ipv4_request_packet", "tests": "import unittest\n\nclass Test_make_ipv4_request_packet(unittest.TestCase):\n def test_dns_make_ipv4_request_packet(self):\n self.assertEqual(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x006\\x01\\x00\\x00\\x00@\\x11\\xf6c\\xc0\\xa8\\x01\\x01' + b'\\xc0\\xa8\\x01\\x02\\x14\\xe9\\x005\\x00\"\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x04test\\x03com\\x00\\x00\\x01\\x00\\x01')\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:890ab', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:890ab', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.300', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.400', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=123123, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=123123, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=123123123, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 123123, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 123123, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=123123))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv4_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'class': 1, 'type': 1}], flags=0))\n", "method_code": " def make_ipv4_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=69, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make DNS request packet for IPv4 network\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ip_src: Source IPv4 address string in Network header (example: '192.168.1.1')\n :param ip_dst: Destination IPv4 address string in Network header (example: '192.168.1.2')\n :param ip_ttl: TTL for IPv4 header (default: 64)\n :param ip_ident: Identification integer value for IPv4 header (optional value)\n :param udp_src_port: Source UDP port (example: 5353)\n :param udp_dst_port: Source UDP port (default: 53)\n :param transaction_id: DNS transaction id integer (example: 1)\n :param flags: DNS flags (default: 0)\n :param queries: List with DNS queries (example: [{'type': 1, 'class': 1, 'name': 'test.com'}])\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 69)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of packet or None if error\n \"\"\"\n error_text: str = 'Failed to make IPv4 DNS request packet!'\n packet: bytes = b''\n try:\n dns_packet: bytes = b''\n dns_packet += pack('!H', transaction_id)\n dns_packet += pack('!H', flags)\n dns_packet += pack('!H', len(queries))\n dns_packet += pack('!H', 0)\n dns_packet += pack('!H', 0)\n dns_packet += pack('!H', 0)\n for query in queries:\n dns_packet += self.pack_dns_name(query['name'])\n dns_packet += pack('!H', query['type'])\n dns_packet += pack('!H', query['class'])\n packet += self.eth.make_header(network_type=self.ipv4.header_type, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_mac=ethernet_src_mac, destination_mac=ethernet_dst_mac)\n packet += self.ipv4.make_header(data_len=len(dns_packet), transport_protocol_len=self.udp.header_length, transport_protocol_type=self.udp.header_type, ttl=ip_ttl, identification=ip_ident, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_ip=ip_src, destination_ip=ip_dst)\n packet += self.udp.make_header(data_length=len(dns_packet), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_port=udp_src_port, destination_port=udp_dst_port)\n return packet + dns_packet\n except TypeError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'destination_mac' in traceback_text:\n error_text += ' Bad source or destination MAC address!'\n if 'destination_ip' in traceback_text:\n error_text += ' Bad source or destination IP address!'\n if 'destination_port' in traceback_text:\n error_text += ' Bad source or destination UDP port!'\n except struct_error as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'transaction_id' in traceback_text:\n error_text += ' Bad transaction ID: ' + self.base.error_text(str(transaction_id)) + ' transaction ID must be in range: ' + self.base.info_text('1 - 65535')\n if 'flags' in traceback_text:\n error_text += ' Bad flags: ' + self.base.error_text(str(flags)) + ' flags must be in range: ' + self.base.info_text('1 - 65535')\n if 'type' in traceback_text:\n error_text += ' Query type be in range: ' + self.base.info_text('1 - 65535')\n if 'class' in traceback_text:\n error_text += ' Query class must be in range: ' + self.base.info_text('1 - 65535')\n except KeyError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'class' in traceback_text:\n error_text += ' Query class not find in queries!'\n if 'type' in traceback_text:\n error_text += ' Query type not find in queries!'\n if 'name' in traceback_text:\n error_text += ' Query name not find in queries!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class RawDNS():\n def make_ipv4_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=69, quiet: bool=False) -> Union[None, bytes]: ...\n def get_top_level_domain(name: str='www.test.com') -> str: ...\n def pack_dns_name(self, name: str='test.com', exit_on_failure: bool=False, exit_code: int=65, quiet: bool=False) -> Union[None, bytes]: ...\n def unpack_dns_name(self, packed_name: bytes=b'\\x04mail\\xc0\\x11', name: str='test.com', exit_on_failure: bool=False, exit_code: int=66, quiet: bool=False) -> Union[None, str]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=67, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, ip_ttl: int=64, udp_src_port: int=53, udp_dst_port: int=5353, transaction_id: int=1, flags: int=33152, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address: List[Dict[str, Union[int, str]]]=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}], name_servers={}, exit_on_failure: bool=False, exit_code: int=68, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv6_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='fd00::1', ip_dst: str='fd00::2', ip_ttl: int=64, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=70, quiet: bool=False) -> Union[None, bytes]: ...\n def make_a_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=71, quiet: bool=False) -> Union[None, bytes]: ...\n def make_aaaa_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=72, quiet: bool=False) -> Union[None, bytes]: ...\n def make_any_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=73, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ns_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=74, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dns_make_ipv4_request_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002131.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_ipv6_request_packet", "tests": "import unittest\n\nclass Test_make_ipv6_request_packet(unittest.TestCase):\n def test_dns_make_ipv6_request_packet(self):\n self.assertEqual(self.dns.make_ipv6_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00::1', ip_dst='fd00::2', ip_ttl=64, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x86\\xdd`\\x00\\x00\\x00\\x00\"\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x02\\x14\\xe9\\x005\\x00\"B)\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x04test\\x03com\\x00\\x00\\x01\\x00\\x01')\n self.assertIsNone(self.dns.make_ipv6_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00:::1', ip_dst='fd00::2', ip_ttl=64, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n self.assertIsNone(self.dns.make_ipv6_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00::1', ip_dst='fd00:::2', ip_ttl=64, udp_src_port=5353, udp_dst_port=53, transaction_id=1, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0))\n", "method_code": " def make_ipv6_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='fd00::1', ip_dst: str='fd00::2', ip_ttl: int=64, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=70, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make DNS request packet for IPv6 network\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ip_src: Source IPv6 address string in Network header (example: 'fd00::1')\n :param ip_dst: Destination IPv6 address string in Network header (example: 'fd00::2')\n :param ip_ttl: Hop limit for IPv6 header (default: 64)\n :param udp_src_port: Source UDP port (example: 5353)\n :param udp_dst_port: Source UDP port (default: 53)\n :param transaction_id: DNS transaction id integer (example: 1)\n :param flags: DNS flags (default: 0)\n :param queries: List with DNS queries (example: [{'type': 1, 'class': 1, 'name': 'test.com'}])\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 70)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of packet or None if error\n \"\"\"\n error_text: str = 'Failed to make IPv6 DNS request packet!'\n packet: bytes = b''\n try:\n dns_packet: bytes = b''\n dns_packet += pack('!H', transaction_id)\n dns_packet += pack('!H', flags)\n dns_packet += pack('!H', len(queries))\n dns_packet += pack('!H', 0)\n dns_packet += pack('!H', 0)\n dns_packet += pack('!H', 0)\n for query in queries:\n dns_packet += self.pack_dns_name(query['name'])\n dns_packet += pack('!H', query['type'])\n dns_packet += pack('!H', query['class'])\n packet += self.eth.make_header(network_type=self.ipv6.header_type, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_mac=ethernet_src_mac, destination_mac=ethernet_dst_mac)\n packet += self.ipv6.make_header(traffic_class=0, flow_label=0, payload_len=self.udp.header_length + len(dns_packet), next_header=self.udp.header_type, hop_limit=ip_ttl, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_ip=ip_src, destination_ip=ip_dst)\n packet += self.udp.make_header_with_ipv6_checksum(ipv6_src=ip_src, ipv6_dst=ip_dst, payload_len=len(dns_packet), payload_data=dns_packet, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, port_src=udp_src_port, port_dst=udp_dst_port)\n return packet + dns_packet\n except TypeError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'destination_mac' in traceback_text:\n error_text += ' Bad source or destination MAC address!'\n if 'destination_ip' in traceback_text:\n error_text += ' Bad source or destination IPv6 address!'\n if 'port_dst' in traceback_text:\n error_text += ' Bad source or destination UDP port!'\n except struct_error as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'transaction_id' in traceback_text:\n error_text += ' Bad transaction ID: ' + self.base.error_text(str(transaction_id)) + ' transaction ID must be in range: ' + self.base.info_text('1 - 65535')\n if 'flags' in traceback_text:\n error_text += ' Bad flags: ' + self.base.error_text(str(flags)) + ' flags must be in range: ' + self.base.info_text('1 - 65535')\n if 'type' in traceback_text:\n error_text += ' Query type be in range: ' + self.base.info_text('1 - 65535')\n if 'class' in traceback_text:\n error_text += ' Query class must be in range: ' + self.base.info_text('1 - 65535')\n except KeyError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'class' in traceback_text:\n error_text += ' Query class not find in queries!'\n if 'type' in traceback_text:\n error_text += ' Query type not find in queries!'\n if 'name' in traceback_text:\n error_text += ' Query name not find in queries!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class RawDNS():\n def make_ipv6_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='fd00::1', ip_dst: str='fd00::2', ip_ttl: int=64, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=70, quiet: bool=False) -> Union[None, bytes]: ...\n def get_top_level_domain(name: str='www.test.com') -> str: ...\n def pack_dns_name(self, name: str='test.com', exit_on_failure: bool=False, exit_code: int=65, quiet: bool=False) -> Union[None, bytes]: ...\n def unpack_dns_name(self, packed_name: bytes=b'\\x04mail\\xc0\\x11', name: str='test.com', exit_on_failure: bool=False, exit_code: int=66, quiet: bool=False) -> Union[None, str]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=67, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, ip_ttl: int=64, udp_src_port: int=53, udp_dst_port: int=5353, transaction_id: int=1, flags: int=33152, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address: List[Dict[str, Union[int, str]]]=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}], name_servers={}, exit_on_failure: bool=False, exit_code: int=68, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv4_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=69, quiet: bool=False) -> Union[None, bytes]: ...\n def make_a_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=71, quiet: bool=False) -> Union[None, bytes]: ...\n def make_aaaa_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=72, quiet: bool=False) -> Union[None, bytes]: ...\n def make_any_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=73, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ns_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=74, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dns_make_ipv6_request_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002132.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_response_packet", "tests": "import unittest\n\nclass Test_make_response_packet(unittest.TestCase):\n def test_dns_make_response_packet(self):\n self.assertEqual(self.dns.make_response_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_dst='192.168.1.2', ip_ttl=64, ip_ident=1, udp_src_port=53, udp_dst_port=5353, transaction_id=1, flags=33152, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}], name_servers={}, exit_on_failure=True), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x00F\\x01\\x00\\x00\\x00@\\x11\\xf6S\\xc0\\xa8\\x01\\x01' + b'\\xc0\\xa8\\x01\\x02\\x005\\x14\\xe9\\x002\\xb5{\\x00\\x01\\x81\\x80\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x00' + b'\\x04test\\x03com\\x00\\x00\\x01\\x00\\x01\\xc0\\x0c\\x00\\x01\\x00\\x01\\x00\\x00\\xff\\xff\\x00\\x04\\xc0' + b'\\xa8\\x01\\x01')\n self.assertEqual(self.dns.make_response_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00::1', ip_dst='fd00::2', ip_ttl=64, ip_ident=1, udp_src_port=53, udp_dst_port=5353, transaction_id=1, flags=33152, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address=[{'name': 'test.com', 'type': 28, 'class': 1, 'ttl': 65535, 'address': 'fd00::1'}], name_servers={}, exit_on_failure=True), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x86\\xdd`\\x00\\x00\\x00\\x00>\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x02\\x005\\x14\\xe9\\x00>\\x034\\x00\\x01\\x81\\x80\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x00\\x04' + b'test\\x03com\\x00\\x00\\x01\\x00\\x01\\xc0\\x0c\\x00\\x1c\\x00\\x01\\x00\\x00\\xff\\xff\\x00\\x10\\xfd\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01')\n self.assertIsNone(self.dns.make_response_packet(ethernet_src_mac='01:23:45:67:890ab', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00::1', ip_dst='fd00::2', ip_ttl=64, ip_ident=1, udp_src_port=53, udp_dst_port=5353, transaction_id=1, flags=0, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address=[{'name': 'test.com', 'type': 28, 'class': 1, 'ttl': 65535, 'address': 'fd00::1'}], name_servers={}, exit_on_failure=False))\n self.assertIsNone(self.dns.make_response_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00:::1', ip_dst='fd00::2', ip_ttl=64, ip_ident=1, udp_src_port=53, udp_dst_port=5353, transaction_id=1, flags=0, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address=[{'name': 'test.com', 'type': 28, 'class': 1, 'ttl': 65535, 'address': 'fd00::1'}], name_servers={}, exit_on_failure=False))\n self.assertIsNone(self.dns.make_response_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00::1', ip_dst='fd00::2', ip_ttl=64, ip_ident=1, udp_src_port=123123, udp_dst_port=5353, transaction_id=1, flags=0, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address=[{'name': 'test.com', 'type': 28, 'class': 1, 'ttl': 65535, 'address': 'fd00::1'}], name_servers={}, exit_on_failure=False))\n self.assertIsNone(self.dns.make_response_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00::1', ip_dst='fd00::2', ip_ttl=64, ip_ident=1, udp_src_port=53, udp_dst_port=5353, transaction_id=1, flags=0, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.300'}], name_servers={}, exit_on_failure=False))\n self.assertIsNone(self.dns.make_response_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='fd00::1', ip_dst='fd00::2', ip_ttl=64, ip_ident=1, udp_src_port=53, udp_dst_port=5353, transaction_id=1, flags=0, queries=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address=[{'name': 'test.com', 'type': 28, 'class': 1, 'ttl': 65535, 'address': 'fd00:::1'}], name_servers={}, exit_on_failure=False))\n\n def test_dhcpv4_make_response_packet(self):\n self.assertEqual(self.dhcpv4.make_response_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_ident=1, transaction_id=1, dhcp_message_type=2, your_client_ip='192.168.1.2', exit_on_failure=True, exit_code=78), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x01F\\x01\\x00\\x00\\x00@\\x11\\xb6\\xfe\\xc0\\xa8\\x01' + b'\\x01\\xff\\xff\\xff\\xff\\x00C\\x00D\\x012\\x00\\x00\\x02\\x01\\x06\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\xc0\\xa8\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01#Eg\\x89\\x0b\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00c\\x82Sc5\\x01\\x026\\x04\\xc0\\xa8\\x01\\x013\\x04\\x00\\x00\\xff\\xff\\x01\\x04\\xff\\xff\\xff' + b'\\x00\\x03\\x04\\xc0\\xa8\\x01\\x01\\x06\\x04\\xc0\\xa8\\x01\\x01\\xff\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n self.assertEqual(self.dhcpv4.make_response_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.1.1', ip_ident=1, transaction_id=1, dhcp_message_type=5, your_client_ip='192.168.1.2', exit_on_failure=True, exit_code=78), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x01F\\x01\\x00\\x00\\x00@\\x11\\xb6\\xfe\\xc0\\xa8\\x01' + b'\\x01\\xff\\xff\\xff\\xff\\x00C\\x00D\\x012\\x00\\x00\\x02\\x01\\x06\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\xc0\\xa8\\x01\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01#Eg\\x89\\x0b\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00c\\x82Sc5\\x01\\x056\\x04\\xc0\\xa8\\x01\\x013\\x04\\x00\\x00\\xff\\xff\\x01\\x04\\xff\\xff\\xff' + b'\\x00\\x03\\x04\\xc0\\xa8\\x01\\x01\\x06\\x04\\xc0\\xa8\\x01\\x01\\xff\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n", "method_code": " def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, ip_ttl: int=64, udp_src_port: int=53, udp_dst_port: int=5353, transaction_id: int=1, flags: int=33152, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address: List[Dict[str, Union[int, str]]]=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}], name_servers={}, exit_on_failure: bool=False, exit_code: int=68, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make DNS response packet\n :type queries: object\n :type answers_address: object\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ip_src: Source IPv4 or IPv6 address string in Network header (example: '192.168.1.1')\n :param ip_dst: Destination IPv4 or IPv6 address string in Network header (example: '192.168.1.2')\n :param ip_ttl: TTL for IPv4 header or hop limit for IPv6 header (default: 64)\n :param ip_ident: Identification integer value for IPv4 header (optional value)\n :param udp_src_port: Source UDP port (default: 53)\n :param udp_dst_port: Source UDP port (example: 5353)\n :param transaction_id: DNS transaction id integer (example: 1)\n :param flags: DNS flags (default: 0)\n :param queries: List with DNS queries (example: [{'type': 1, 'class': 1, 'name': 'test.com'}])\n :param answers_address: List with DNS answers address (example: [{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}])\n :param name_servers: Dictionary with name servers (Under constraction)\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 68)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of packet or None if error\n \"\"\"\n error_text: str = 'Failed to make DNS response packet!'\n packet: bytes = b''\n mail_server_preference: int = 10\n try:\n dns_packet: bytes = b''\n dns_packet += pack('!H', transaction_id)\n dns_packet += pack('!H', flags)\n dns_packet += pack('!H', len(queries))\n dns_packet += pack('!H', len(answers_address))\n dns_packet += pack('!H', len(name_servers.keys()))\n dns_packet += pack('!H', len(name_servers.keys()))\n query_name: str = ''\n for query in queries:\n query_name = query['name']\n if query_name.endswith('.'):\n query_name = query_name[:-1]\n dns_packet += self.pack_dns_name(query_name)\n dns_packet += pack('!H', query['type'])\n dns_packet += pack('!H', query['class'])\n for address in answers_address:\n if 'name' in address.keys():\n if len(queries) == 1 and query_name == address['name']:\n dns_packet += pack('!H', 49164)\n else:\n dns_packet += self.pack_dns_name(address['name'])\n else:\n dns_packet += pack('!H', 49164)\n dns_packet += pack('!H', address['type'])\n dns_packet += pack('!H', address['class'])\n dns_packet += pack('!I', address['ttl'])\n if int(address['type']) == 1:\n dns_packet += pack('!H', 4)\n dns_packet += pack('!4s', inet_aton(address['address']))\n elif int(address['type']) == 28:\n dns_packet += pack('!H', 16)\n dns_packet += pack('!16s', inet_pton(AF_INET6, address['address']))\n elif int(address['type']) == 2 or int(address['type']) == 12:\n domain: bytes = self.pack_dns_name(address['address'])\n dns_packet += pack('!H', len(domain))\n dns_packet += domain\n elif int(address['type']) == 15:\n domain: bytes = self.pack_dns_name(address['address'])\n dns_packet += pack('!H', len(domain) + 2)\n dns_packet += pack('!H', mail_server_preference)\n dns_packet += domain\n mail_server_preference += 10\n if self.base.ip_address_validation(ip_address=ip_src, exit_on_failure=False, quiet=True):\n packet += self.eth.make_header(network_type=self.ipv4.header_type, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_mac=ethernet_src_mac, destination_mac=ethernet_dst_mac)\n packet += self.ipv4.make_header(data_len=len(dns_packet), transport_protocol_len=self.udp.header_length, transport_protocol_type=self.udp.header_type, ttl=ip_ttl, identification=ip_ident, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_ip=ip_src, destination_ip=ip_dst)\n packet += self.udp.make_header_with_ipv4_checksum(ipv4_src=ip_src, ipv4_dst=ip_dst, payload_len=len(dns_packet), payload_data=dns_packet, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, port_src=udp_src_port, port_dst=udp_dst_port)\n elif self.base.ipv6_address_validation(ipv6_address=ip_src, exit_on_failure=False, quiet=True):\n packet += self.eth.make_header(network_type=self.ipv6.header_type, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_mac=ethernet_src_mac, destination_mac=ethernet_dst_mac)\n packet += self.ipv6.make_header(traffic_class=0, flow_label=0, payload_len=self.udp.header_length + len(dns_packet), next_header=self.udp.header_type, hop_limit=ip_ttl, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, source_ip=ip_src, destination_ip=ip_dst)\n packet += self.udp.make_header_with_ipv6_checksum(ipv6_src=ip_src, ipv6_dst=ip_dst, payload_len=len(dns_packet), payload_data=dns_packet, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet, port_src=udp_src_port, port_dst=udp_dst_port)\n else:\n raise TypeError('Unknown network!')\n return packet + dns_packet\n except TypeError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'ethernet_dst_mac' in traceback_text:\n error_text += ' Bad source or destination MAC address!'\n if 'Unknown network' in traceback_text:\n error_text += ' Bad source or destination IP address!'\n if 'udp_dst_port' in traceback_text:\n error_text += ' Bad source or destination UDP port!'\n except OSError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'inet_aton' in traceback_text:\n error_text += ' Bad IPv4 address in answers!'\n if 'inet_pton' in traceback_text:\n error_text += ' Bad IPv6 address in answer!'\n except struct_error as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'transaction_id' in traceback_text:\n error_text += ' Bad transaction ID: ' + self.base.error_text(str(transaction_id)) + ' transaction ID must be in range: ' + self.base.info_text('1 - 65535')\n if 'flags' in traceback_text:\n error_text += ' Bad flags: ' + self.base.error_text(str(flags)) + ' flags must be in range: ' + self.base.info_text('1 - 65535')\n if 'type' in traceback_text:\n error_text += ' Query type be in range: ' + self.base.info_text('1 - 65535')\n if 'class' in traceback_text:\n error_text += ' Query class must be in range: ' + self.base.info_text('1 - 65535')\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class RawDNS():\n def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, ip_ttl: int=64, udp_src_port: int=53, udp_dst_port: int=5353, transaction_id: int=1, flags: int=33152, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], answers_address: List[Dict[str, Union[int, str]]]=[{'name': 'test.com', 'type': 1, 'class': 1, 'ttl': 65535, 'address': '192.168.1.1'}], name_servers={}, exit_on_failure: bool=False, exit_code: int=68, quiet: bool=False) -> Union[None, bytes]: ...\n def get_top_level_domain(name: str='www.test.com') -> str: ...\n def pack_dns_name(self, name: str='test.com', exit_on_failure: bool=False, exit_code: int=65, quiet: bool=False) -> Union[None, bytes]: ...\n def unpack_dns_name(self, packed_name: bytes=b'\\x04mail\\xc0\\x11', name: str='test.com', exit_on_failure: bool=False, exit_code: int=66, quiet: bool=False) -> Union[None, str]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=67, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_ipv4_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=69, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ipv6_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='fd00::1', ip_dst: str='fd00::2', ip_ttl: int=64, udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, queries: List[Dict[str, Union[int, str]]]=[{'type': 1, 'class': 1, 'name': 'test.com'}], flags=0, exit_on_failure: bool=False, exit_code: int=70, quiet: bool=False) -> Union[None, bytes]: ...\n def make_a_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=71, quiet: bool=False) -> Union[None, bytes]: ...\n def make_aaaa_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=72, quiet: bool=False) -> Union[None, bytes]: ...\n def make_any_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=73, quiet: bool=False) -> Union[None, bytes]: ...\n def make_ns_query(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', udp_src_port: int=5353, udp_dst_port: int=53, transaction_id: int=1, name: str='test.com', flags: int=0, exit_on_failure: bool=False, exit_code: int=74, quiet: bool=False) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dns_make_response_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002133.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_host_unreachable_packet", "tests": "import unittest\n\nclass Test_make_host_unreachable_packet(unittest.TestCase):\n def test_icmpv4_make_host_unreachable_packet(self):\n self.assertEqual(self.icmpv4.make_host_unreachable_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.0.1', ip_dst='192.168.0.2', ip_ident=1), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x000\\x01\\x00\\x00\\x00@\\x01\\xf8y\\xc0\\xa8\\x00' + b'\\x01\\xc0\\xa8\\x00\\x02\\x03\\x01\\xfc\\xfe\\x00\\x00\\x00\\x00E\\x00\\x00\\x1c\\x01\\x00\\x00\\x00@\\x01' + b'\\xf8\\x8d\\xc0\\xa8\\x00\\x02\\xc0\\xa8\\x00\\x01')\n self.assertIsNone(self.icmpv4.make_host_unreachable_packet(ethernet_src_mac='01:23:45:67:89:0ab', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.0.1', ip_dst='192.168.0.2', ip_ident=1))\n self.assertIsNone(self.icmpv4.make_host_unreachable_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.0.1111', ip_dst='192.168.0.2', ip_ident=1))\n", "method_code": " def make_host_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv4 Host Unreachable packet\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0b')\n :param ip_src: Source IPv4 address string in Network header (example: '192.168.0.1')\n :param ip_dst: Destination IPv4 address string in Network header (example: '192.168.0.2')\n :param ip_ident: Identification integer value for IPv4 header (optional value)\n :param data: Bytes of ICMPv4 data or None (optional value)\n :return: Bytes of ICMPv4 Host Unreachable packet or None if error\n \"\"\"\n error_text: str = 'Failed to make ICMPv4 Host Unreachable packet!'\n icmp_data: bytes = b''\n try:\n if data is not None:\n ip_data = self.ip.make_header(source_ip=ip_dst, destination_ip=ip_src, data_len=len(data), transport_protocol_len=8, transport_protocol_type=17, ttl=64, identification=ip_ident)\n icmp_data += ip_data + data\n else:\n ip_data = self.ip.make_header(source_ip=ip_dst, destination_ip=ip_src, data_len=0, transport_protocol_len=8, transport_protocol_type=1, ttl=64, identification=ip_ident)\n icmp_data += ip_data\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ip_src=ip_src, ip_dst=ip_dst, ip_ident=ip_ident, icmp_type=3, icmp_code=1, data=icmp_data)\n except TypeError:\n error_text += ' Bad value in IPv4 header!'\n self.base.print_error(error_text)\n return None\n ", "context": "class RawICMPv4():\n def make_host_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def checksum(packet: bytes) -> int: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, quiet: bool=True): ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, icmp_type: int=1, icmp_code: int=1, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_udp_port_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, udp_src_port: int=53, udp_dst_port: int=53, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_ping_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, gateway_address: str='192.168.0.1', payload_ip_src: str='192.168.0.2', payload_ip_dst: str='192.168.0.3', payload_port_src=53, payload_port_dst=53) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv4_make_host_unreachable_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002134.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_udp_port_unreachable_packet", "tests": "import unittest\n\nclass Test_make_udp_port_unreachable_packet(unittest.TestCase):\n def test_icmpv4_make_udp_port_unreachable_packet(self):\n self.assertEqual(self.icmpv4.make_udp_port_unreachable_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.0.1', ip_dst='192.168.0.2', udp_src_port=5353, udp_dst_port=5353, ip_ident=1), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x008\\x01\\x00\\x00\\x00@\\x01\\xf8q\\xc0\\xa8\\x00\\x01' + b'\\xc0\\xa8\\x00\\x02\\x03\\x03\\xd3\"\\x00\\x00\\x00\\x00E\\x00\\x00$\\x01\\x00\\x00\\x00@\\x11\\xf8u\\xc0\\xa8' + b'\\x00\\x02\\xc0\\xa8\\x00\\x01\\x14\\xe9\\x14\\xe9\\x00\\x08\\x00\\x00')\n", "method_code": " def make_udp_port_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, udp_src_port: int=53, udp_dst_port: int=53, data: Union[None, bytes]=None) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv4 UDP Port Unreachable packet\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0b')\n :param ip_src: Source IPv4 address string in Network header (example: '192.168.0.1')\n :param ip_dst: Destination IPv4 address string in Network header (example: '192.168.0.2')\n :param ip_ident: Identification integer value for IPv4 header (optional value)\n :param udp_src_port: UDP source port (example: 53)\n :param udp_dst_port: UDP destination port (example: 53)\n :param data: Bytes of ICMPv4 data or None (optional value)\n :return: Bytes of ICMPv4 UDP Port Unreachable packet or None if error\n \"\"\"\n error_text: str = 'Failed to make ICMPv4 UDP Port Unreachable packet!'\n icmp_data: bytes = b''\n try:\n if data is not None:\n udp_data = self.udp.make_header(source_port=udp_src_port, destination_port=udp_dst_port, data_length=len(data))\n ip_data = self.ip.make_header(source_ip=ip_dst, destination_ip=ip_src, data_len=self.udp.header_length + len(data), transport_protocol_len=self.udp.header_length, transport_protocol_type=self.udp.header_type, ttl=64, identification=ip_ident)\n icmp_data += ip_data\n icmp_data += udp_data\n icmp_data += data\n else:\n udp_data = self.udp.make_header(source_port=udp_src_port, destination_port=udp_dst_port, data_length=0)\n ip_data = self.ip.make_header(source_ip=ip_dst, destination_ip=ip_src, data_len=self.udp.header_length, transport_protocol_len=self.udp.header_length, transport_protocol_type=self.udp.header_type, ttl=64, identification=ip_ident)\n icmp_data += ip_data\n icmp_data += udp_data\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ip_src=ip_src, ip_dst=ip_dst, ip_ident=ip_ident, icmp_type=3, icmp_code=3, data=icmp_data)\n except TypeError:\n pass\n self.base.print_error(error_text)\n return None\n ", "context": "class RawICMPv4():\n def make_udp_port_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, udp_src_port: int=53, udp_dst_port: int=53, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def checksum(packet: bytes) -> int: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, quiet: bool=True): ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, icmp_type: int=1, icmp_code: int=1, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_host_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_ping_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, gateway_address: str='192.168.0.1', payload_ip_src: str='192.168.0.2', payload_ip_dst: str='192.168.0.3', payload_port_src=53, payload_port_dst=53) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv4_make_udp_port_unreachable_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002135.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_ping_request_packet", "tests": "import unittest\n\nclass Test_make_ping_request_packet(unittest.TestCase):\n def test_icmpv4_make_ping_request_packet(self):\n self.assertEqual(self.icmpv4.make_ping_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.0.1', ip_dst='192.168.0.2', ip_ident=1, data=b'0123456789'), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x00&\\x01\\x00\\x00\\x00@\\x01\\xf8\\x83\\xc0\\xa8\\x00' + b'\\x01\\xc0\\xa8\\x00\\x02\\x08\\x00\\xf2\\xf5\\x00\\x00\\x00\\x000123456789')\n", "method_code": " def make_ping_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv4 Ping Request packet\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0b')\n :param ip_src: Source IPv4 address string in Network header (example: '192.168.0.1')\n :param ip_dst: Destination IPv4 address string in Network header (example: '192.168.0.2')\n :param ip_ident: Identification integer value for IPv4 header (optional value)\n :param data: Bytes of ICMPv4 data or None (optional value)\n :return: Bytes of ICMPv4 Ping Request packet or None if error\n \"\"\"\n if data is None:\n icmp_data = pack('!Q', int(time()))\n for index in range(0, 32, 1):\n icmp_data += pack('B', index)\n else:\n icmp_data = data\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ip_src=ip_src, ip_dst=ip_dst, ip_ident=ip_ident, icmp_type=8, icmp_code=0, data=icmp_data)\n ", "context": "class RawICMPv4():\n def make_ping_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def checksum(packet: bytes) -> int: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, quiet: bool=True): ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, icmp_type: int=1, icmp_code: int=1, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_host_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_udp_port_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, udp_src_port: int=53, udp_dst_port: int=53, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, gateway_address: str='192.168.0.1', payload_ip_src: str='192.168.0.2', payload_ip_dst: str='192.168.0.3', payload_port_src=53, payload_port_dst=53) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv4_make_ping_request_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002136.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_redirect_packet", "tests": "import unittest\n\nclass Test_make_redirect_packet(unittest.TestCase):\n def test_icmpv4_make_redirect_packet(self):\n self.assertEqual(self.icmpv4.make_redirect_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.0.1', ip_dst='192.168.0.2', ip_ttl=64, ip_ident=1, gateway_address='192.168.0.1', payload_ip_src='192.168.0.1', payload_ip_dst='192.168.0.2'), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x008\\x01\\x00\\x00\\x00@\\x01\\xf8q\\xc0\\xa8\\x00\\x01' + b'\\xc0\\xa8\\x00\\x02\\x05\\x019\\xe3\\xc0\\xa8\\x00\\x01E\\x00\\x00\\x1c\\x01\\x00\\x00\\x00@\\x11\\xf8}\\xc0' + b'\\xa8\\x00\\x01\\xc0\\xa8\\x00\\x02\\x005\\x005\\x00\\x08\\x00\\x00')\n self.assertIsNone(self.icmpv4.make_redirect_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.0.1', ip_dst='192.168.0.2', ip_ttl=64, ip_ident=1, gateway_address='192.168.0.1111', payload_ip_src='192.168.0.1', payload_ip_dst='192.168.0.2'))\n self.assertIsNone(self.icmpv4.make_redirect_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ip_src='192.168.0.1', ip_dst='192.168.0.2', ip_ttl=64, ip_ident=1, gateway_address='192.168.0.1', payload_ip_src='192.168.0.1111', payload_ip_dst='192.168.0.2'))\n", "method_code": " def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, gateway_address: str='192.168.0.1', payload_ip_src: str='192.168.0.2', payload_ip_dst: str='192.168.0.3', payload_port_src=53, payload_port_dst=53) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv4 Redirect packet\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0b')\n :param ip_src: Source IPv4 address string in Network header (example: '192.168.0.1')\n :param ip_dst: Destination IPv4 address string in Network header (example: '192.168.0.2')\n :param ip_ident: Identification integer value for IPv4 header (optional value)\n :param ip_ttl: TTL for IPv4 header (default: 64)\n :param gateway_address: IPv4 address of Gateway (example: '192.168.0.1')\n :param payload_ip_src: Source IPv4 address in ICMPv4 payload - client IPv4 address (example: '192.168.0.2')\n :param payload_ip_dst: Destination IPv4 address in ICMPv4 payload - server IPv4 address (example: '192.168.0.3')\n :param payload_port_src: Source port in ICMPv4 payload - client port (example: '53')\n :param payload_port_dst: Destination port in ICMPv4 payload - server port (example: '53')\n :return: Bytes of ICMPv4 Redirect packet or None if error\n \"\"\"\n error_text: str = 'Failed to make ICMPv4 Redirect packet!'\n icmp_data: bytes = b''\n try:\n ip_data: Union[None, bytes] = self.ip.make_header(source_ip=payload_ip_src, destination_ip=payload_ip_dst, data_len=0, transport_protocol_len=self.udp.header_length, transport_protocol_type=self.udp.header_type, ttl=ip_ttl, identification=ip_ident)\n udp_data: Union[None, bytes] = self.udp.make_header(source_port=payload_port_src, destination_port=payload_port_dst, data_length=0)\n icmp_data += inet_aton(gateway_address)\n icmp_data += ip_data\n icmp_data += udp_data\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ip_src=ip_src, ip_dst=ip_dst, ip_ident=ip_ident, icmp_type=5, icmp_code=1, data=icmp_data)\n except OSError:\n error_text += ' Bad gateway IPv4 address: ' + self.base.error_text(str(gateway_address))\n except TypeError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'udp_data' in traceback_text:\n error_text += ' Bad source or destination UDP port!'\n if 'ip_data' in traceback_text:\n error_text += ' Bad value in IPv4 header!'\n self.base.print_error(error_text)\n return None\n ", "context": "class RawICMPv4():\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ttl: int=64, ip_ident: Union[None, int]=None, gateway_address: str='192.168.0.1', payload_ip_src: str='192.168.0.2', payload_ip_dst: str='192.168.0.3', payload_port_src=53, payload_port_dst=53) -> Union[None, bytes]: ...\n def checksum(packet: bytes) -> int: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, quiet: bool=True): ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, icmp_type: int=1, icmp_code: int=1, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_host_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_udp_port_unreachable_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, udp_src_port: int=53, udp_dst_port: int=53, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def make_ping_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.0.1', ip_dst: str='192.168.0.2', ip_ident: Union[None, int]=None, data: Union[None, bytes]=None) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv4_make_redirect_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002137.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_discover_packet", "tests": "import unittest\n\nclass Test_make_discover_packet(unittest.TestCase):\n def test_dhcpv4_discover_packet(self):\n self.assertEqual(self.dhcpv4.make_discover_packet(ethernet_src_mac='01:23:45:67:89:0a', client_mac='01:23:45:67:89:0a', ip_ident=1, transaction_id=1, host_name='dhcp.discover.test', exit_on_failure=True, exit_code=76), b'\\xff\\xff\\xff\\xff\\xff\\xff\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x02<\\x01\\x00\\x00\\x00@\\x11w\\xb2\\x00' + b'\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\x00D\\x00C\\x02(\\x00\\x00\\x01\\x01\\x06\\x00\\x00\\x00\\x00\\x01\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01#Eg\\x89' + b'\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00c\\x82Sc5\\x01\\x01\\x0c\\x12dhcp.discover.test7\\xfe\\x01\\x02\\x03\\x04\\x05' + b'\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c' + b'\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefg' + b'hijklmnopqrstuvwxyz{|}~\\x7f\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e' + b'\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4' + b'\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba' + b'\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0' + b'\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6' + b'\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc' + b'\\xfd\\xfe\\xff\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00')\n", "method_code": " def make_discover_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: Union[None, str]=None, ip_dst: Union[None, str]=None, ip_ident: Union[None, int]=None, client_mac: str='01:23:45:67:89:0a', host_name: Union[None, str]=None, relay_agent_ip: Union[None, str]=None, transaction_id: Union[None, int]=None, exit_on_failure: bool=False, exit_code: int=76, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make DHCPv4 Discover packet\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (default: 'ff:ff:ff:ff:ff:ff')\n :param ip_src: Source IPv4 address string in Network header (default: '0.0.0.0')\n :param ip_dst: Destination IPv4 address string in Network header (default: '255.255.255.255')\n :param ip_ident: Identification integer value for IPv4 header (optional value)\n :param udp_src_port: Source UDP port (default: 68)\n :param udp_dst_port: Source UDP port (default: 67)\n :param client_mac: BOOTP CHADDR - Client hardware address (example: '01:23:45:67:89:0a')\n :param host_name: Client hostname (example: 'test')\n :param relay_agent_ip: BOOTP GIADDR - Relay agent IP address (default: '0.0.0.0')\n :param transaction_id: BOOTP Transaction ID integer (example: 1)\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 75)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of DHCPv4 Discover packet or None if error\n \"\"\"\n error_text: str = 'Failed to make DHCPv4 Discover packet!'\n try:\n if ethernet_dst_mac is None:\n ethernet_dst_mac = 'ff:ff:ff:ff:ff:ff'\n if ip_src is None:\n ip_src = '0.0.0.0'\n if ip_dst is None:\n ip_dst = '255.255.255.255'\n if relay_agent_ip is None:\n relay_agent_ip = '0.0.0.0'\n if transaction_id is None:\n transaction_id = randint(1, 4294967295)\n dhcp_options: bytes = pack('!3B', 53, 1, 1)\n if host_name is not None:\n host_name: bytes = host_name.encode('utf-8')\n dhcp_options += pack('!2B', 12, len(host_name)) + host_name\n dhcp_options += pack('!2B', 55, 254)\n for param in range(1, 255):\n dhcp_options += pack('B', param)\n dhcp_options += pack('B', 255)\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ip_src=ip_src, ip_dst=ip_dst, ip_ident=ip_ident, udp_src_port=68, udp_dst_port=67, bootp_message_type=1, bootp_transaction_id=transaction_id, bootp_flags=0, bootp_client_ip='0.0.0.0', bootp_your_client_ip='0.0.0.0', bootp_next_server_ip='0.0.0.0', bootp_relay_agent_ip=relay_agent_ip, bootp_client_hw_address=client_mac, dhcp_options=dhcp_options, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n except struct_error as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'host_name' in traceback_text:\n error_text += ' Bad host name! Maximum host name length: ' + self.base.info_text('255')\n except UnicodeEncodeError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'host_name' in traceback_text:\n error_text += ' Bad host name: ' + self.base.error_text(str(host_name))\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class RawDHCPv4():\n def make_discover_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: Union[None, str]=None, ip_dst: Union[None, str]=None, ip_ident: Union[None, int]=None, client_mac: str='01:23:45:67:89:0a', host_name: Union[None, str]=None, relay_agent_ip: Union[None, str]=None, transaction_id: Union[None, int]=None, exit_on_failure: bool=False, exit_code: int=76, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=74, quiet: bool=True): ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, udp_src_port: int=68, udp_dst_port: int=67, bootp_message_type: int=1, bootp_transaction_id: int=1, bootp_flags: int=0, bootp_client_ip: str='192.168.1.1', bootp_your_client_ip: str='192.168.1.1', bootp_next_server_ip: str='192.168.1.1', bootp_relay_agent_ip: str='192.168.1.1', bootp_client_hw_address: str='01:23:45:67:89:0a', dhcp_options: bytes=b'', padding: int=24, exit_on_failure: bool=False, exit_code: int=75, quiet: bool=False) -> Union[None, bytes]: ...\n def make_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: Union[None, str]=None, ip_dst: Union[None, str]=None, ip_ident: Union[None, int]=None, dhcp_message_type: int=3, client_mac: str='01:23:45:67:89:0a', client_ip: Union[None, str]=None, your_client_ip: Union[None, str]=None, relay_agent_ip: Union[None, str]=None, host_name: Union[None, str]=None, transaction_id: Union[None, int]=None, requested_ip: Union[None, str]=None, option_code: Union[None, int]=None, option_value: Union[None, bytes]=None, exit_on_failure: bool=False, exit_code: int=77, quiet: bool=False) -> Union[None, bytes]: ...\n def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: str='192.168.1.1', ip_dst: Union[None, str]=None, ip_ident: Union[None, int]=None, transaction_id: int=1, dhcp_message_type: int=2, your_client_ip: str='192.168.1.2', client_mac: Union[None, str]=None, dhcp_server_id: Union[None, str]=None, lease_time: int=65535, netmask: str='255.255.255.0', router: str='192.168.1.1', dns: str='192.168.1.1', payload_option_code=114, payload: Union[None, bytes]=None, proxy: Union[None, bytes]=None, domain: Union[None, bytes]=None, tftp: Union[None, str]=None, wins: Union[None, str]=None, exit_on_failure: bool=False, exit_code: int=78, quiet: bool=False) -> Union[None, bytes]: ...\n def make_offer_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: str='192.168.1.1', ip_dst: Union[None, str]=None, transaction_id: int=1, your_client_ip: str='192.168.1.2', client_mac: str='01:23:45:67:89:0b', dhcp_server_id: Union[None, str]=None, lease_time: int=600, netmask: str='255.255.255.0', router: Union[None, str]=None, dns: Union[None, str]=None) -> Union[None, bytes]: ...\n def make_ack_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: str='192.168.1.1', ip_dst: Union[None, str]=None, transaction_id: int=1, your_client_ip: str='192.168.1.2', client_mac: str='01:23:45:67:89:0b', dhcp_server_id: Union[None, str]=None, lease_time: int=600, netmask: str='255.255.255.0', router: Union[None, str]=None, dns: Union[None, str]=None) -> Union[None, bytes]: ...\n def make_release_packet(self, ethernet_src_mac: str='01:23:45:67:89:0b', ethernet_dst_mac: str='01:23:45:67:89:0a', ip_src: str='192.168.1.2', ip_dst: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=78, quiet: bool=False): ...\n def make_decline_packet(self, relay_mac, relay_ip, server_mac, server_ip, client_mac, requested_ip, transaction_id): ...\n def make_nak_packet(self, ethernet_src_mac: str='01:23:45:67:89:0b', ethernet_dst_mac: str='01:23:45:67:89:0a', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, transaction_id: int=1, your_client_ip: str='192.168.1.2', client_mac: str='01:23:45:67:89:0a', dhcp_server_id: Union[None, str]=None) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dhcpv4_discover_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002138.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_request_packet", "tests": "import unittest\n\nclass Test_make_request_packet(unittest.TestCase):\n def test_dhcpv4_make_request_packet(self):\n self.assertEqual(self.dhcpv4.make_request_packet(ethernet_src_mac='01:23:45:67:89:0a', client_mac='01:23:45:67:89:0a', ip_ident=1, transaction_id=1, requested_ip='192.168.1.1', host_name='dhcp.request.test', exit_on_failure=True, exit_code=77), b'\\xff\\xff\\xff\\xff\\xff\\xff\\x01#Eg\\x89\\n\\x08\\x00E\\x00\\x01J\\x01\\x00\\x00\\x00@\\x11x\\xa4\\x00' + b'\\x00\\x00\\x00\\xff\\xff\\xff\\xff\\x00D\\x00C\\x016\\x00\\x00\\x01\\x01\\x06\\x00\\x00\\x00\\x00\\x01\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01#Eg\\x89' + b'\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00c\\x82Sc5\\x01\\x032\\x04\\xc0\\xa8\\x01\\x01\\x0c\\x11dhcp.request.test7\\x07' + b'\\x01\\x02\\x03\\x06\\x1c\\x0f\\x1a\\xff\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n", "method_code": " def make_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: Union[None, str]=None, ip_dst: Union[None, str]=None, ip_ident: Union[None, int]=None, dhcp_message_type: int=3, client_mac: str='01:23:45:67:89:0a', client_ip: Union[None, str]=None, your_client_ip: Union[None, str]=None, relay_agent_ip: Union[None, str]=None, host_name: Union[None, str]=None, transaction_id: Union[None, int]=None, requested_ip: Union[None, str]=None, option_code: Union[None, int]=None, option_value: Union[None, bytes]=None, exit_on_failure: bool=False, exit_code: int=77, quiet: bool=False) -> Union[None, bytes]:\n error_text: str = 'Failed to make request DHCPv4 packet!'\n try:\n if ethernet_dst_mac is None:\n ethernet_dst_mac = 'ff:ff:ff:ff:ff:ff'\n if ip_src is None:\n ip_src = '0.0.0.0'\n if ip_dst is None:\n ip_dst = '255.255.255.255'\n if client_ip is None:\n client_ip = '0.0.0.0'\n if your_client_ip is None:\n your_client_ip = '0.0.0.0'\n if relay_agent_ip is None:\n relay_agent_ip = '0.0.0.0'\n if transaction_id is None:\n transaction_id = randint(1, 4294967295)\n dhcp_options: bytes = pack('!3B', 53, 1, dhcp_message_type)\n if requested_ip is not None:\n dhcp_options += pack('!2B4s', 50, 4, inet_aton(requested_ip))\n if host_name is not None:\n host_name: bytes = host_name.encode('utf-8')\n dhcp_options += pack('!2B', 12, len(host_name)) + host_name\n if option_value is not None and option_code is not None:\n dhcp_options += pack('!2B', option_code, len(option_value)) + option_value\n dhcp_options += pack('!2B', 55, 7)\n for param in [1, 2, 3, 6, 28, 15, 26]:\n dhcp_options += pack('B', param)\n dhcp_options += pack('B', 255)\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ip_src=ip_src, ip_dst=ip_dst, ip_ident=ip_ident, udp_src_port=68, udp_dst_port=67, bootp_message_type=1, bootp_transaction_id=transaction_id, bootp_flags=0, bootp_client_ip=client_ip, bootp_your_client_ip=your_client_ip, bootp_next_server_ip='0.0.0.0', bootp_relay_agent_ip=relay_agent_ip, bootp_client_hw_address=client_mac, dhcp_options=dhcp_options, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n except OSError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'requested_ip' in traceback_text:\n error_text += ' Bad requested IPv4 address: ' + self.base.error_text(str(requested_ip)) + ' example IPv4 address: ' + self.base.info_text('192.168.1.1')\n except struct_error as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'host_name' in traceback_text:\n error_text += ' Bad host name! Maximum host name length: ' + self.base.info_text('255')\n if 'dhcp_message_type' in traceback_text:\n error_text += ' Bad DHCPv4 message type: ' + self.base.error_text(str(dhcp_message_type)) + ' DHCPv4 message type must be in range: ' + self.base.info_text('1 - 255')\n if 'option_code' in traceback_text:\n error_text += ' Bad option code or value! Option code must be in range: ' + self.base.info_text('1 - 255') + ' maximum option value length: ' + self.base.info_text('255')\n except UnicodeEncodeError as Error:\n traceback_text: str = format_tb(Error.__traceback__)[0]\n if 'host_name' in traceback_text:\n error_text += ' Bad host name: ' + self.base.error_text(str(host_name))\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n return None\n ", "context": "class RawDHCPv4():\n def make_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: Union[None, str]=None, ip_dst: Union[None, str]=None, ip_ident: Union[None, int]=None, dhcp_message_type: int=3, client_mac: str='01:23:45:67:89:0a', client_ip: Union[None, str]=None, your_client_ip: Union[None, str]=None, relay_agent_ip: Union[None, str]=None, host_name: Union[None, str]=None, transaction_id: Union[None, int]=None, requested_ip: Union[None, str]=None, option_code: Union[None, int]=None, option_value: Union[None, bytes]=None, exit_on_failure: bool=False, exit_code: int=77, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=74, quiet: bool=True): ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, udp_src_port: int=68, udp_dst_port: int=67, bootp_message_type: int=1, bootp_transaction_id: int=1, bootp_flags: int=0, bootp_client_ip: str='192.168.1.1', bootp_your_client_ip: str='192.168.1.1', bootp_next_server_ip: str='192.168.1.1', bootp_relay_agent_ip: str='192.168.1.1', bootp_client_hw_address: str='01:23:45:67:89:0a', dhcp_options: bytes=b'', padding: int=24, exit_on_failure: bool=False, exit_code: int=75, quiet: bool=False) -> Union[None, bytes]: ...\n def make_discover_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: Union[None, str]=None, ip_dst: Union[None, str]=None, ip_ident: Union[None, int]=None, client_mac: str='01:23:45:67:89:0a', host_name: Union[None, str]=None, relay_agent_ip: Union[None, str]=None, transaction_id: Union[None, int]=None, exit_on_failure: bool=False, exit_code: int=76, quiet: bool=False) -> Union[None, bytes]: ...\n def make_response_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: str='192.168.1.1', ip_dst: Union[None, str]=None, ip_ident: Union[None, int]=None, transaction_id: int=1, dhcp_message_type: int=2, your_client_ip: str='192.168.1.2', client_mac: Union[None, str]=None, dhcp_server_id: Union[None, str]=None, lease_time: int=65535, netmask: str='255.255.255.0', router: str='192.168.1.1', dns: str='192.168.1.1', payload_option_code=114, payload: Union[None, bytes]=None, proxy: Union[None, bytes]=None, domain: Union[None, bytes]=None, tftp: Union[None, str]=None, wins: Union[None, str]=None, exit_on_failure: bool=False, exit_code: int=78, quiet: bool=False) -> Union[None, bytes]: ...\n def make_offer_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: str='192.168.1.1', ip_dst: Union[None, str]=None, transaction_id: int=1, your_client_ip: str='192.168.1.2', client_mac: str='01:23:45:67:89:0b', dhcp_server_id: Union[None, str]=None, lease_time: int=600, netmask: str='255.255.255.0', router: Union[None, str]=None, dns: Union[None, str]=None) -> Union[None, bytes]: ...\n def make_ack_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ip_src: str='192.168.1.1', ip_dst: Union[None, str]=None, transaction_id: int=1, your_client_ip: str='192.168.1.2', client_mac: str='01:23:45:67:89:0b', dhcp_server_id: Union[None, str]=None, lease_time: int=600, netmask: str='255.255.255.0', router: Union[None, str]=None, dns: Union[None, str]=None) -> Union[None, bytes]: ...\n def make_release_packet(self, ethernet_src_mac: str='01:23:45:67:89:0b', ethernet_dst_mac: str='01:23:45:67:89:0a', ip_src: str='192.168.1.2', ip_dst: str='192.168.1.1', exit_on_failure: bool=False, exit_code: int=78, quiet: bool=False): ...\n def make_decline_packet(self, relay_mac, relay_ip, server_mac, server_ip, client_mac, requested_ip, transaction_id): ...\n def make_nak_packet(self, ethernet_src_mac: str='01:23:45:67:89:0b', ethernet_dst_mac: str='01:23:45:67:89:0a', ip_src: str='192.168.1.1', ip_dst: str='192.168.1.2', ip_ident: Union[None, int]=None, transaction_id: int=1, your_client_ip: str='192.168.1.2', client_mac: str='01:23:45:67:89:0a', dhcp_server_id: Union[None, str]=None) -> Union[None, bytes]: ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dhcpv4_make_request_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002139.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_option", "tests": "import unittest\n\nclass Test_make_option(unittest.TestCase):\n def test_icmpv6_make_option(self):\n self.assertEqual(self.icmpv6.make_option(option_type=1, option_value=b'test_option_value'), b'\\x01\\x03\\x00\\x00\\x00\\x00\\x00test_option_value')\n", "method_code": " def make_option(self, option_type: int=1, option_value: bytes=b'', exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv6 option to bytes\n :param option_type: Set ICMPv6 option type integer (example: 1)\n :param option_value: Set ICMPv6 option value bytes (example: b'')\n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 44)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of ICMPv6 option\n \"\"\"\n try:\n assert not (len(option_value) + 2) / 8 > 255, 'ICMPv6 option value too big!' + ' Option type: ' + self.base.error_text(str(option_type)) + ' option value: ' + self.base.error_text(str(option_value))\n if (len(option_value) + 2) % 8 != 0:\n option_value = b''.join((pack('B', 0) for _ in range(8 - (len(option_value) + 2) % 8))) + option_value\n return pack('!2B', option_type, int((len(option_value) + 2) / 8)) + option_value\n except AssertionError as Error:\n error_text = Error.args[0]\n except struct_error:\n error_text = 'Failed to make IPCMv6 option!' + ' Option type: ' + self.base.error_text(str(option_type)) + ' option value: ' + self.base.error_text(str(option_value))\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawICMPv6():\n def make_option(self, option_type: int=1, option_value: bytes=b'', exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self) -> None: ...\n def checksum(packet: bytes) -> int: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=0, ipv6_hop_limit: int=255, icmpv6_type: int=0, icmpv6_code: int=0, icmpv6_body: bytes=b'', exit_on_failure: bool=True, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='33:33:00:00:00:02', ipv6_src: str='fd00::1', ipv6_dst: str='ff02::2', ipv6_flow=538065, need_source_link_layer_address: bool=False, source_link_layer_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', dns_address: str='fd00::1', domain_search: str='domain.local', prefix: Union[None, str]=None, ipv6_addr: Union[None, str]=None, mtu: int=1500, advertisement_interval: int=60000, src_link_layer_address: Union[None, str]=None, router_lifetime: int=0, reachable_time: int=0, retrans_timer: int=0, exit_on_failure: bool=True, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_solicitation_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, icmpv6_target_ipv6_address: Union[None, str]=None, icmpv6_source_mac_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=49, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, target_ipv6_address: str='fd00::2', flags: int=536870912, exit_on_failure: bool=True, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, data: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]: ...\n def make_multicast_listener_report_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, multicast_addresses: List[str]=['ff02::1', 'ff02::16'], exit_on_failure: bool=True, exit_code: int=53, quiet: bool=False) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', original_router_ipv6_address: str='fd00::1', victim_address_ipv6_address: str='fd00::2', new_router_ipv6_address: str='fd00::3', new_router_mac_address: Union[None, str]=None, redirected_ipv6_address: str='2001:4860:4860::8888', redirected_header: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=54, quiet: bool=False) -> Union[None, bytes]: ...\n\n self.types['Echo (ping) request'] = 128\n self.types['Echo (ping) reply'] = 129\n self.types['Router Solicitation'] = 133\n self.types['Router Advertisement'] = 134\n self.types['Neighbor Solicitation'] = 135\n self.types['Neighbor Advertisement'] = 136\n self.types['Redirect'] = 137\n self.types['Multicast listener report'] = 143\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv6_make_option", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002140.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_router_solicit_packet", "tests": "import unittest\n\nclass Test_make_router_solicit_packet(unittest.TestCase):\n def test_icmpv6_make_router_solicit_packet(self):\n self.assertEqual(self.icmpv6.make_router_solicit_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='33:33:00:00:00:02', ipv6_src='fd00::1', ipv6_dst='fd00::2', ipv6_flow=538065, need_source_link_layer_address=True, source_link_layer_address=None), b'33\\x00\\x00\\x00\\x02\\x01#Eg\\x89\\n\\x86\\xdd`\\x085\\xd1\\x00\\x10:\\xff\\xfd\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x02\\x85\\x00\\xb0\\x1a\\x00\\x00\\x00\\x00\\x01\\x01\\x01#Eg\\x89\\n')\n", "method_code": " def make_router_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='33:33:00:00:00:02', ipv6_src: str='fd00::1', ipv6_dst: str='ff02::2', ipv6_flow=538065, need_source_link_layer_address: bool=False, source_link_layer_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv6 Router Solicitation packet\n :param ethernet_src_mac: Source MAC address string in Ethernet header (example: '01:23:45:67:89:0a')\n :param ethernet_dst_mac: Destination MAC address string in Ethernet header (example: '01:23:45:67:89:0b')\n :param ipv6_src: Source IPv6 address string in IPv6 header (example: 'fd00::1')\n :param ipv6_dst: Destination IPv6 address string in IPv6 header (example: 'fd00::1')\n :param ipv6_flow: IPv6 flow label integer in IPv6 header (default: 0)\n :param need_source_link_layer_address: \n :param source_link_layer_address: \n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 47)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: Bytes of ICMPv6 Router Solicitation packet or None if error\n \"\"\"\n try:\n body = pack('I', 0)\n if need_source_link_layer_address:\n body += pack('!2B', 1, 1)\n if source_link_layer_address is None:\n body += self.eth.convert_mac(mac_address=ethernet_src_mac, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n else:\n body += self.eth.convert_mac(mac_address=source_link_layer_address, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ipv6_src=ipv6_src, ipv6_dst=ipv6_dst, ipv6_flow=ipv6_flow, icmpv6_type=self.types['Router Solicitation'], icmpv6_code=0, icmpv6_body=body)\n except TypeError:\n error_text = 'Failed to make IPCMv6 Router Solicitation packet!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawICMPv6():\n def make_router_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='33:33:00:00:00:02', ipv6_src: str='fd00::1', ipv6_dst: str='ff02::2', ipv6_flow=538065, need_source_link_layer_address: bool=False, source_link_layer_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self) -> None: ...\n def checksum(packet: bytes) -> int: ...\n def make_option(self, option_type: int=1, option_value: bytes=b'', exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=0, ipv6_hop_limit: int=255, icmpv6_type: int=0, icmpv6_code: int=0, icmpv6_body: bytes=b'', exit_on_failure: bool=True, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', dns_address: str='fd00::1', domain_search: str='domain.local', prefix: Union[None, str]=None, ipv6_addr: Union[None, str]=None, mtu: int=1500, advertisement_interval: int=60000, src_link_layer_address: Union[None, str]=None, router_lifetime: int=0, reachable_time: int=0, retrans_timer: int=0, exit_on_failure: bool=True, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_solicitation_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, icmpv6_target_ipv6_address: Union[None, str]=None, icmpv6_source_mac_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=49, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, target_ipv6_address: str='fd00::2', flags: int=536870912, exit_on_failure: bool=True, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, data: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]: ...\n def make_multicast_listener_report_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, multicast_addresses: List[str]=['ff02::1', 'ff02::16'], exit_on_failure: bool=True, exit_code: int=53, quiet: bool=False) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', original_router_ipv6_address: str='fd00::1', victim_address_ipv6_address: str='fd00::2', new_router_ipv6_address: str='fd00::3', new_router_mac_address: Union[None, str]=None, redirected_ipv6_address: str='2001:4860:4860::8888', redirected_header: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=54, quiet: bool=False) -> Union[None, bytes]: ...\n\n self.types['Echo (ping) request'] = 128\n self.types['Echo (ping) reply'] = 129\n self.types['Router Solicitation'] = 133\n self.types['Router Advertisement'] = 134\n self.types['Neighbor Solicitation'] = 135\n self.types['Neighbor Advertisement'] = 136\n self.types['Redirect'] = 137\n self.types['Multicast listener report'] = 143\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv6_make_router_solicit_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002141.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_router_advertisement_packet", "tests": "import unittest\n\nclass Test_make_router_advertisement_packet(unittest.TestCase):\n def test_icmpv6_make_router_advertisement_packet(self):\n self.assertEqual(self.icmpv6.make_router_advertisement_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ipv6_src='fd00::1', ipv6_dst='fd00::2', dns_address='fd00::1', domain_search='test.local', prefix='fd00::/64'), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x86\\xdd`\\x0bGU\\x00\\x80:\\xff\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x02\\x86\\x00\\xb3>@\\xc0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x04@\\xc0\\xff\\xff' + b'\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x00\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x01\\x01\\x01#Eg\\x89\\n\\x05\\x01\\x00\\x00\\x00\\x00\\x05\\xdc\\x19\\x03\\x00\\x00\\x00' + b'\\x00\\x17p\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x1f\\x04\\x00\\x00' + b'\\x00\\x00\\x17p\\x04test\\x05local\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x07\\x01' + b'\\x00\\x00\\x00\\x00\\xea`')\n", "method_code": " def make_router_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', dns_address: str='fd00::1', domain_search: str='domain.local', prefix: Union[None, str]=None, ipv6_addr: Union[None, str]=None, mtu: int=1500, advertisement_interval: int=60000, src_link_layer_address: Union[None, str]=None, router_lifetime: int=0, reachable_time: int=0, retrans_timer: int=0, exit_on_failure: bool=True, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv6 Router Advertisement packet\n :param ethernet_src_mac: \n :param ethernet_dst_mac: \n :param ipv6_src: \n :param ipv6_dst: \n :param dns_address: \n :param domain_search: \n :param prefix: \n :param ipv6_addr: \n :param mtu: \n :param advertisement_interval: \n :param src_link_layer_address: \n :param router_lifetime: \n :param reachable_time: \n :param retrans_timer: \n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 48)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: \n \"\"\"\n try:\n cur_hop_limit = 64\n flags = 192\n body = pack('!2BH2I', cur_hop_limit, flags, router_lifetime, reachable_time, retrans_timer)\n if src_link_layer_address is None:\n src_link_layer_address = ethernet_src_mac\n if prefix is not None:\n prefix_value = self.ipv6.pack_addr(ipv6_address=str(prefix.split('/')[0]), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n prefix_len = int(prefix.split('/')[1])\n body += self.make_option(option_type=3, option_value=pack('!2B3I', prefix_len, 192, 4294967295, 4294967295, 0) + prefix_value, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n if ipv6_addr is not None:\n body += self.make_option(option_type=17, option_value=pack('!2BI', 3, prefix_len, 0) + self.ipv6.pack_addr(ipv6_addr), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n body += self.make_option(option_type=1, option_value=self.eth.convert_mac(src_link_layer_address), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n body += self.make_option(option_type=5, option_value=pack('!H', mtu), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n body += self.make_option(option_type=25, option_value=pack('!H', 6000) + self.ipv6.pack_addr(dns_address), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n assert not len(domain_search) > 22, 'Too big domain search value: ' + self.base.error_text(domain_search)\n domain_search = self.dns.pack_dns_name(name=domain_search)\n padding = 24 - len(domain_search)\n domain_search += b''.join((pack('B', 0) for _ in range(padding)))\n body += self.make_option(option_type=31, option_value=pack('!I', 6000) + domain_search, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n body += self.make_option(option_type=7, option_value=pack('!H', advertisement_interval), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ipv6_src=ipv6_src, ipv6_dst=ipv6_dst, ipv6_flow=739157, icmpv6_type=self.types['Router Advertisement'], icmpv6_code=0, icmpv6_body=body)\n except AssertionError as Error:\n error_text = Error.args[0]\n except TypeError:\n error_text = 'Failed to make IPCMv6 Router Advertisement packet!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawICMPv6():\n def make_router_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', dns_address: str='fd00::1', domain_search: str='domain.local', prefix: Union[None, str]=None, ipv6_addr: Union[None, str]=None, mtu: int=1500, advertisement_interval: int=60000, src_link_layer_address: Union[None, str]=None, router_lifetime: int=0, reachable_time: int=0, retrans_timer: int=0, exit_on_failure: bool=True, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self) -> None: ...\n def checksum(packet: bytes) -> int: ...\n def make_option(self, option_type: int=1, option_value: bytes=b'', exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=0, ipv6_hop_limit: int=255, icmpv6_type: int=0, icmpv6_code: int=0, icmpv6_body: bytes=b'', exit_on_failure: bool=True, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='33:33:00:00:00:02', ipv6_src: str='fd00::1', ipv6_dst: str='ff02::2', ipv6_flow=538065, need_source_link_layer_address: bool=False, source_link_layer_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_solicitation_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, icmpv6_target_ipv6_address: Union[None, str]=None, icmpv6_source_mac_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=49, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, target_ipv6_address: str='fd00::2', flags: int=536870912, exit_on_failure: bool=True, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, data: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]: ...\n def make_multicast_listener_report_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, multicast_addresses: List[str]=['ff02::1', 'ff02::16'], exit_on_failure: bool=True, exit_code: int=53, quiet: bool=False) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', original_router_ipv6_address: str='fd00::1', victim_address_ipv6_address: str='fd00::2', new_router_ipv6_address: str='fd00::3', new_router_mac_address: Union[None, str]=None, redirected_ipv6_address: str='2001:4860:4860::8888', redirected_header: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=54, quiet: bool=False) -> Union[None, bytes]: ...\n\n self.types['Echo (ping) request'] = 128\n self.types['Echo (ping) reply'] = 129\n self.types['Router Solicitation'] = 133\n self.types['Router Advertisement'] = 134\n self.types['Neighbor Solicitation'] = 135\n self.types['Neighbor Advertisement'] = 136\n self.types['Redirect'] = 137\n self.types['Multicast listener report'] = 143\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv6_make_router_advertisement_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002142.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_neighbor_solicitation_packet", "tests": "import unittest\n\nclass Test_make_neighbor_solicitation_packet(unittest.TestCase):\n def test_icmpv6_make_neighbor_solicitation_packet(self):\n self.assertEqual(self.icmpv6.make_neighbor_solicitation_packet(ethernet_src_mac='01:23:45:67:89:0a', ipv6_src='fd00::1'), b'33\\x00\\x00\\x00\\x01\\x01#Eg\\x89\\n\\x86\\xdd`\\x00\\x00\\x00\\x00 :\\xff\\xfd\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x01\\x87\\x00\\xac\\x05\\x00\\x00\\x00\\x00\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x01\\x02\\x01\\x01#Eg\\x89\\n')\n", "method_code": " def make_neighbor_solicitation_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, icmpv6_target_ipv6_address: Union[None, str]=None, icmpv6_source_mac_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=49, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv6 Neighbor Solicitation packet\n :param ethernet_src_mac: \n :param ethernet_dst_mac: \n :param ipv6_src: \n :param ipv6_dst: \n :param icmpv6_target_ipv6_address: \n :param icmpv6_source_mac_address: \n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 49)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: \n \"\"\"\n try:\n body = pack('!I', 0)\n if icmpv6_target_ipv6_address is None:\n icmpv6_target_ipv6_address = 'ff02::1'\n body += self.ipv6.pack_addr(ipv6_address=icmpv6_target_ipv6_address, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n if icmpv6_source_mac_address is None:\n icmpv6_source_mac_address = ethernet_src_mac\n body += self.make_option(option_type=2, option_value=self.eth.convert_mac(icmpv6_source_mac_address), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n if ethernet_dst_mac is None:\n ethernet_dst_mac = '33:33:00:00:00:01'\n if ipv6_dst is None:\n ipv6_dst = 'ff02::1'\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ipv6_src=ipv6_src, ipv6_dst=ipv6_dst, ipv6_flow=0, icmpv6_type=self.types['Neighbor Solicitation'], icmpv6_code=0, icmpv6_body=body, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n except TypeError:\n error_text = 'Failed to make IPCMv6 Neighbor Solicitation packet!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawICMPv6():\n def make_neighbor_solicitation_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, icmpv6_target_ipv6_address: Union[None, str]=None, icmpv6_source_mac_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=49, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self) -> None: ...\n def checksum(packet: bytes) -> int: ...\n def make_option(self, option_type: int=1, option_value: bytes=b'', exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=0, ipv6_hop_limit: int=255, icmpv6_type: int=0, icmpv6_code: int=0, icmpv6_body: bytes=b'', exit_on_failure: bool=True, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='33:33:00:00:00:02', ipv6_src: str='fd00::1', ipv6_dst: str='ff02::2', ipv6_flow=538065, need_source_link_layer_address: bool=False, source_link_layer_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', dns_address: str='fd00::1', domain_search: str='domain.local', prefix: Union[None, str]=None, ipv6_addr: Union[None, str]=None, mtu: int=1500, advertisement_interval: int=60000, src_link_layer_address: Union[None, str]=None, router_lifetime: int=0, reachable_time: int=0, retrans_timer: int=0, exit_on_failure: bool=True, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, target_ipv6_address: str='fd00::2', flags: int=536870912, exit_on_failure: bool=True, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, data: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]: ...\n def make_multicast_listener_report_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, multicast_addresses: List[str]=['ff02::1', 'ff02::16'], exit_on_failure: bool=True, exit_code: int=53, quiet: bool=False) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', original_router_ipv6_address: str='fd00::1', victim_address_ipv6_address: str='fd00::2', new_router_ipv6_address: str='fd00::3', new_router_mac_address: Union[None, str]=None, redirected_ipv6_address: str='2001:4860:4860::8888', redirected_header: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=54, quiet: bool=False) -> Union[None, bytes]: ...\n\n self.types['Echo (ping) request'] = 128\n self.types['Echo (ping) reply'] = 129\n self.types['Router Solicitation'] = 133\n self.types['Router Advertisement'] = 134\n self.types['Neighbor Solicitation'] = 135\n self.types['Neighbor Advertisement'] = 136\n self.types['Redirect'] = 137\n self.types['Multicast listener report'] = 143\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv6_make_neighbor_solicitation_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002143.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_neighbor_advertisement_packet", "tests": "import unittest\n\nclass Test_make_neighbor_advertisement_packet(unittest.TestCase):\n def test_icmpv6_make_neighbor_advertisement_packet(self):\n self.assertEqual(self.icmpv6.make_neighbor_advertisement_packet(ethernet_src_mac='01:23:45:67:89:0a', ipv6_src='fd00::1', target_ipv6_address='fd00::2'), b'33\\x00\\x00\\x00\\x01\\x01#Eg\\x89\\n\\x86\\xdd`\\x00\\x00\\x00\\x00 :\\xff\\xfd\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x01\\x88\\x00\\x8d\\x06 \\x00\\x00\\x00\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x02\\x02\\x01\\x01#Eg\\x89\\n')\n", "method_code": " def make_neighbor_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, target_ipv6_address: str='fd00::2', flags: int=536870912, exit_on_failure: bool=True, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv6 Neighbor Advertisement packet\n :param ethernet_src_mac: \n :param ethernet_dst_mac: \n :param ipv6_src: \n :param ipv6_dst: \n :param target_ipv6_address: \n :param flags: \n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 50)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: \n \"\"\"\n try:\n body = pack('!I', flags)\n body += self.ipv6.pack_addr(ipv6_address=target_ipv6_address, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n body += self.make_option(option_type=2, option_value=self.eth.convert_mac(ethernet_src_mac), exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n if ethernet_dst_mac is None:\n ethernet_dst_mac = '33:33:00:00:00:01'\n if ipv6_dst is None:\n ipv6_dst = 'ff02::1'\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ipv6_src=ipv6_src, ipv6_dst=ipv6_dst, ipv6_flow=0, icmpv6_type=self.types['Neighbor Advertisement'], icmpv6_code=0, icmpv6_body=body, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n except TypeError:\n error_text = 'Failed to make IPCMv6 Neighbor Advertisement packet!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawICMPv6():\n def make_neighbor_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, target_ipv6_address: str='fd00::2', flags: int=536870912, exit_on_failure: bool=True, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self) -> None: ...\n def checksum(packet: bytes) -> int: ...\n def make_option(self, option_type: int=1, option_value: bytes=b'', exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=0, ipv6_hop_limit: int=255, icmpv6_type: int=0, icmpv6_code: int=0, icmpv6_body: bytes=b'', exit_on_failure: bool=True, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='33:33:00:00:00:02', ipv6_src: str='fd00::1', ipv6_dst: str='ff02::2', ipv6_flow=538065, need_source_link_layer_address: bool=False, source_link_layer_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', dns_address: str='fd00::1', domain_search: str='domain.local', prefix: Union[None, str]=None, ipv6_addr: Union[None, str]=None, mtu: int=1500, advertisement_interval: int=60000, src_link_layer_address: Union[None, str]=None, router_lifetime: int=0, reachable_time: int=0, retrans_timer: int=0, exit_on_failure: bool=True, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_solicitation_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, icmpv6_target_ipv6_address: Union[None, str]=None, icmpv6_source_mac_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=49, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, data: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]: ...\n def make_multicast_listener_report_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, multicast_addresses: List[str]=['ff02::1', 'ff02::16'], exit_on_failure: bool=True, exit_code: int=53, quiet: bool=False) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', original_router_ipv6_address: str='fd00::1', victim_address_ipv6_address: str='fd00::2', new_router_ipv6_address: str='fd00::3', new_router_mac_address: Union[None, str]=None, redirected_ipv6_address: str='2001:4860:4860::8888', redirected_header: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=54, quiet: bool=False) -> Union[None, bytes]: ...\n\n self.types['Echo (ping) request'] = 128\n self.types['Echo (ping) reply'] = 129\n self.types['Router Solicitation'] = 133\n self.types['Router Advertisement'] = 134\n self.types['Neighbor Solicitation'] = 135\n self.types['Neighbor Advertisement'] = 136\n self.types['Redirect'] = 137\n self.types['Multicast listener report'] = 143\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv6_make_neighbor_advertisement_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002144.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_echo_request_packet", "tests": "import unittest\n\nclass Test_make_echo_request_packet(unittest.TestCase):\n def test_icmpv6_make_echo_request_packet(self):\n self.assertEqual(self.icmpv6.make_echo_request_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ipv6_src='fd00::1', ipv6_dst='fd00::2', id=1, sequence=1), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x86\\xdd`\\x00\\x00\\x00\\x00@:\\xff\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x02\\x80\\x00\\x8ek\\x00\\x01\\x00\\x01\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c' + b'\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f ' + b'!\"#$%&\\'()*+,-./01234567')\n", "method_code": " def make_echo_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv6 Echo (ping) request packet\n :param ethernet_src_mac: \n :param ethernet_dst_mac: \n :param ipv6_src: \n :param ipv6_dst: \n :param id: \n :param sequence: \n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 51)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: \n \"\"\"\n try:\n body = pack('!2H', id, sequence)\n for index in range(0, 56, 1):\n body += pack('B', index)\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ipv6_src=ipv6_src, ipv6_dst=ipv6_dst, ipv6_flow=0, icmpv6_type=self.types['Echo (ping) request'], icmpv6_code=0, icmpv6_body=body, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n except TypeError:\n error_text = 'Failed to make ICMPv6 Echo (ping) request packet!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawICMPv6():\n def make_echo_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self) -> None: ...\n def checksum(packet: bytes) -> int: ...\n def make_option(self, option_type: int=1, option_value: bytes=b'', exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=0, ipv6_hop_limit: int=255, icmpv6_type: int=0, icmpv6_code: int=0, icmpv6_body: bytes=b'', exit_on_failure: bool=True, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='33:33:00:00:00:02', ipv6_src: str='fd00::1', ipv6_dst: str='ff02::2', ipv6_flow=538065, need_source_link_layer_address: bool=False, source_link_layer_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', dns_address: str='fd00::1', domain_search: str='domain.local', prefix: Union[None, str]=None, ipv6_addr: Union[None, str]=None, mtu: int=1500, advertisement_interval: int=60000, src_link_layer_address: Union[None, str]=None, router_lifetime: int=0, reachable_time: int=0, retrans_timer: int=0, exit_on_failure: bool=True, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_solicitation_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, icmpv6_target_ipv6_address: Union[None, str]=None, icmpv6_source_mac_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=49, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, target_ipv6_address: str='fd00::2', flags: int=536870912, exit_on_failure: bool=True, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, data: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]: ...\n def make_multicast_listener_report_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, multicast_addresses: List[str]=['ff02::1', 'ff02::16'], exit_on_failure: bool=True, exit_code: int=53, quiet: bool=False) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', original_router_ipv6_address: str='fd00::1', victim_address_ipv6_address: str='fd00::2', new_router_ipv6_address: str='fd00::3', new_router_mac_address: Union[None, str]=None, redirected_ipv6_address: str='2001:4860:4860::8888', redirected_header: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=54, quiet: bool=False) -> Union[None, bytes]: ...\n\n self.types['Echo (ping) request'] = 128\n self.types['Echo (ping) reply'] = 129\n self.types['Router Solicitation'] = 133\n self.types['Router Advertisement'] = 134\n self.types['Neighbor Solicitation'] = 135\n self.types['Neighbor Advertisement'] = 136\n self.types['Redirect'] = 137\n self.types['Multicast listener report'] = 143\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv6_make_echo_request_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002145.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_echo_reply_packet", "tests": "import unittest\n\nclass Test_make_echo_reply_packet(unittest.TestCase):\n def test_icmpv6_make_echo_reply_packet(self):\n self.assertEqual(self.icmpv6.make_echo_reply_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ipv6_src='fd00::1', ipv6_dst='fd00::2', id=1, sequence=1), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x86\\xdd`\\x00\\x00\\x00\\x00@:\\xff\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x02\\x81\\x00\\x8dk\\x00\\x01\\x00\\x01\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c' + b'\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f ' + b'!\"#$%&\\'()*+,-./01234567')\n", "method_code": " def make_echo_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, data: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]:\n \"\"\"\n Make ICMPv6 Echo (ping) reply packet\n :param ethernet_src_mac: \n :param ethernet_dst_mac: \n :param ipv6_src: \n :param ipv6_dst: \n :param id: \n :param sequence: \n :param data: \n :param exit_on_failure: Exit in case of error (default: False)\n :param exit_code: Set exit code integer (default: 52)\n :param quiet: Quiet mode, if True no console output (default: False)\n :return: \n \"\"\"\n try:\n body = pack('!2H', id, sequence)\n if data is None:\n for index in range(0, 56, 1):\n body += pack('B', index)\n else:\n body += data\n return self.make_packet(ethernet_src_mac=ethernet_src_mac, ethernet_dst_mac=ethernet_dst_mac, ipv6_src=ipv6_src, ipv6_dst=ipv6_dst, ipv6_flow=0, icmpv6_type=self.types['Echo (ping) reply'], icmpv6_code=0, icmpv6_body=body, exit_on_failure=exit_on_failure, exit_code=exit_code, quiet=quiet)\n except TypeError:\n error_text = 'Failed to make ICMPv6 Echo (ping) reply packet!'\n if not quiet:\n self.base.print_error(error_text)\n if exit_on_failure:\n exit(exit_code)\n else:\n return None\n ", "context": "class RawICMPv6():\n def make_echo_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, data: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=52, quiet: bool=False) -> Union[None, bytes]: ...\n def __init__(self) -> None: ...\n def checksum(packet: bytes) -> int: ...\n def make_option(self, option_type: int=1, option_value: bytes=b'', exit_on_failure: bool=True, exit_code: int=44, quiet: bool=False) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes, exit_on_failure: bool=False, exit_code: int=45, quiet: bool=True) -> Union[None, Dict[str, Union[int, str, Dict[str, Union[int, str]]]]]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=0, ipv6_hop_limit: int=255, icmpv6_type: int=0, icmpv6_code: int=0, icmpv6_body: bytes=b'', exit_on_failure: bool=True, exit_code: int=46, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='33:33:00:00:00:02', ipv6_src: str='fd00::1', ipv6_dst: str='ff02::2', ipv6_flow=538065, need_source_link_layer_address: bool=False, source_link_layer_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=47, quiet: bool=False) -> Union[None, bytes]: ...\n def make_router_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', dns_address: str='fd00::1', domain_search: str='domain.local', prefix: Union[None, str]=None, ipv6_addr: Union[None, str]=None, mtu: int=1500, advertisement_interval: int=60000, src_link_layer_address: Union[None, str]=None, router_lifetime: int=0, reachable_time: int=0, retrans_timer: int=0, exit_on_failure: bool=True, exit_code: int=48, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_solicitation_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, icmpv6_target_ipv6_address: Union[None, str]=None, icmpv6_source_mac_address: Union[None, str]=None, exit_on_failure: bool=True, exit_code: int=49, quiet: bool=False) -> Union[None, bytes]: ...\n def make_neighbor_advertisement_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, target_ipv6_address: str='fd00::2', flags: int=536870912, exit_on_failure: bool=True, exit_code: int=50, quiet: bool=False) -> Union[None, bytes]: ...\n def make_echo_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', id: int=1, sequence: int=1, exit_on_failure: bool=True, exit_code: int=51, quiet: bool=False) -> Union[None, bytes]: ...\n def make_multicast_listener_report_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, multicast_addresses: List[str]=['ff02::1', 'ff02::16'], exit_on_failure: bool=True, exit_code: int=53, quiet: bool=False) -> Union[None, bytes]: ...\n def make_redirect_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', original_router_ipv6_address: str='fd00::1', victim_address_ipv6_address: str='fd00::2', new_router_ipv6_address: str='fd00::3', new_router_mac_address: Union[None, str]=None, redirected_ipv6_address: str='2001:4860:4860::8888', redirected_header: Union[None, bytes]=None, exit_on_failure: bool=True, exit_code: int=54, quiet: bool=False) -> Union[None, bytes]: ...\n\n self.types['Echo (ping) request'] = 128\n self.types['Echo (ping) reply'] = 129\n self.types['Router Solicitation'] = 133\n self.types['Router Advertisement'] = 134\n self.types['Neighbor Solicitation'] = 135\n self.types['Neighbor Advertisement'] = 136\n self.types['Redirect'] = 137\n self.types['Multicast listener report'] = 143\n", "repository": "raw-packet/raw-packet", "test_name": "test_icmpv6_make_echo_reply_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002146.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "_make_duid", "tests": "import unittest\n\nclass Test_make_duid(unittest.TestCase):\n def test_dhcpv6_make_option(self):\n self.assertEqual(self.dhcpv6._make_duid(mac_address='01:23:45:67:89:0a'), b'\\x00\\x03\\x00\\x01\\x01#Eg\\x89\\n')\n", "method_code": " def _make_duid(self, mac_address: str='01:23:45:67:89:0a', timeval: Union[None, int]=None) -> Union[None, bytes]:\n error_text: str = 'Failed to make DHCPv6 DUID!'\n hardware_type: int = 1\n try:\n if timeval is None:\n duid_type: int = 3\n return pack('!2H', duid_type, hardware_type) + self.eth.convert_mac(mac_address)\n else:\n duid_type: int = 1\n return pack('!2HI', duid_type, hardware_type, timeval) + self.eth.convert_mac(mac_address)\n except TypeError:\n error_text += ' Bad MAC address: ' + self.base.error_text(str(mac_address))\n except struct_error:\n error_text += ' Bad timeval: ' + self.base.error_text(str(timeval))\n self.base.print_error(error_text)\n return None\n ", "context": "class RawDHCPv6():\n def _make_duid(self, mac_address: str='01:23:45:67:89:0a', timeval: Union[None, int]=None) -> Union[None, bytes]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, udp_src_port: int=546, udp_dst_port: int=547, dhcp_message_type: int=1, packet_body: bytes=b'', options: Union[None, Dict[int, bytes]]={14: b''}, options_raw: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes): ...\n def make_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_relay_forw_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, hop_count: int=10, link_addr: str='fd00::1', peer_addr: str='fd00::2', options: Union[None, Dict[int, bytes]]=None, options_raw: Union[None, bytes]=None): ...\n def make_advertise_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, server_duid_mac: Union[None, str]=None, cid: Union[None, bytes]=None, iaid: int=1, preference: Union[None, int]=None): ...\n def make_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, cid: Union[None, bytes]=None, server_duid_mac: Union[None, str]=None): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dhcpv6_make_option", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002147.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_solicit_packet", "tests": "import unittest\n\nclass Test_make_solicit_packet(unittest.TestCase):\n def test_dhcpv6_make_solicit_packet(self):\n self.assertEqual(self.dhcpv6.make_solicit_packet(ethernet_src_mac='01:23:45:67:89:0a', ipv6_src='fd00::1', transaction_id=1, client_mac_address='01:23:45:67:89:0a', option_request_list=[23, 24]), b'33\\x00\\x01\\x00\\x02\\x01#Eg\\x89\\n\\x86\\xdd`\\x00\\x00\\x00\\x00H\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x01\\x00\\x02\\x02\"\\x02#\\x00H.\\x01\\x01\\x00\\x00\\x01\\x00\\x03\\x00\\x18\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0e\\x00' + b'\\x00\\x00\\x08\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\n\\x00\\x03\\x00\\x01\\x01#Eg\\x89\\n\\x00\\x06\\x00\\x04' + b'\\x00\\x17\\x00\\x18')\n", "method_code": " def make_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]):\n if ethernet_dst_mac is None:\n ethernet_dst_mac = '33:33:00:01:00:02'\n if ipv6_dst is None:\n ipv6_dst = 'ff02::1:2'\n if 16777215 < transaction_id < 0:\n return None\n packet_body = pack('!L', transaction_id)[1:]\n options: Dict[int, bytes] = dict()\n options[3] = pack('!3Q', 0, 0, 0)\n options[14] = b''\n options[8] = pack('!H', 0)\n options[1] = self._make_duid(client_mac_address)\n option_request_string = b''\n for option_request in option_request_list:\n option_request_string += pack('!H', option_request)\n options[6] = option_request_string\n return self.make_packet(ethernet_src_mac, ethernet_dst_mac, ipv6_src, ipv6_dst, 0, 546, 547, 1, packet_body, options)\n ", "context": "class RawDHCPv6():\n def make_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def _make_duid(self, mac_address: str='01:23:45:67:89:0a', timeval: Union[None, int]=None) -> Union[None, bytes]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, udp_src_port: int=546, udp_dst_port: int=547, dhcp_message_type: int=1, packet_body: bytes=b'', options: Union[None, Dict[int, bytes]]={14: b''}, options_raw: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes): ...\n def make_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_relay_forw_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, hop_count: int=10, link_addr: str='fd00::1', peer_addr: str='fd00::2', options: Union[None, Dict[int, bytes]]=None, options_raw: Union[None, bytes]=None): ...\n def make_advertise_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, server_duid_mac: Union[None, str]=None, cid: Union[None, bytes]=None, iaid: int=1, preference: Union[None, int]=None): ...\n def make_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, cid: Union[None, bytes]=None, server_duid_mac: Union[None, str]=None): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dhcpv6_make_solicit_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002148.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_relay_forw_packet", "tests": "import unittest\n\nclass Test_make_relay_forw_packet(unittest.TestCase):\n def test_dhcpv6_make_relay_forw_packet(self):\n self.assertEqual(self.dhcpv6.make_relay_forw_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ipv6_src='fd00::1', ipv6_dst='fd00::2', ipv6_flow=1, hop_count=10, link_addr='fd00::2', peer_addr='fd00::3'), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x86\\xdd`\\x00\\x00\\x01\\x00*\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x02\\x02\"\\x02#\\x00*\\xfb?\\x0c\\n\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x02\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03')\n", "method_code": " def make_relay_forw_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, hop_count: int=10, link_addr: str='fd00::1', peer_addr: str='fd00::2', options: Union[None, Dict[int, bytes]]=None, options_raw: Union[None, bytes]=None):\n error_text: str = 'Failed to make DHCPv6 Relay-forw packet!'\n try:\n assert hop_count <= 32, ' Maximum hop count limit = 32'\n packet_body = pack('!B', hop_count) + self.ipv6.pack_addr(link_addr) + self.ipv6.pack_addr(peer_addr)\n return self.make_packet(ethernet_src_mac, ethernet_dst_mac, ipv6_src, ipv6_dst, ipv6_flow, 546, 547, 12, packet_body, options, options_raw)\n except AssertionError as Error:\n error_text += Error.args[0]\n self.base.print_error(error_text)\n return None\n ", "context": "class RawDHCPv6():\n def make_relay_forw_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, hop_count: int=10, link_addr: str='fd00::1', peer_addr: str='fd00::2', options: Union[None, Dict[int, bytes]]=None, options_raw: Union[None, bytes]=None): ...\n def _make_duid(self, mac_address: str='01:23:45:67:89:0a', timeval: Union[None, int]=None) -> Union[None, bytes]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, udp_src_port: int=546, udp_dst_port: int=547, dhcp_message_type: int=1, packet_body: bytes=b'', options: Union[None, Dict[int, bytes]]={14: b''}, options_raw: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes): ...\n def make_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_advertise_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, server_duid_mac: Union[None, str]=None, cid: Union[None, bytes]=None, iaid: int=1, preference: Union[None, int]=None): ...\n def make_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, cid: Union[None, bytes]=None, server_duid_mac: Union[None, str]=None): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dhcpv6_make_relay_forw_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002149.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_advertise_packet", "tests": "import unittest\n\nclass Test_make_advertise_packet(unittest.TestCase):\n def test_dhcpv6_make_advertise_packet(self):\n self.assertEqual(self.dhcpv6.make_advertise_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ipv6_src='fd00::1', ipv6_dst='fd00::2', transaction_id=1, dns_address='fd00::1', domain_search='test.local', ipv6_address='fd00::2'), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x86\\xdd`\\n\\x1b\\x82\\x00\\x84\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x02\\x02#\\x02\"\\x00\\x84n\\xf4\\x02\\x00\\x00\\x01\\x00\\x01\\x00\\n\\x00\\x03\\x00\\x01\\x01#Eg' + b'\\x89\\x0b\\x00\\x02\\x00\\n\\x00\\x03\\x00\\x01\\x01#Eg\\x89\\n\\x00\\x14\\x00\\x00\\x00\\x17\\x00\\x10\\xfd' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x18\\x00\\x0c\\x04test\\x05' + b'local\\x00\\x00R\\x00\\x04\\x00\\x00\\x00<\\x00\\x03\\x00(\\x00\\x00\\x00\\x01\\x00\\x00T`\\x00\\x00\\x87' + b'\\x00\\x00\\x05\\x00\\x18\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\xff' + b'\\xff\\xff\\xff\\xff\\xff\\xff\\xff')\n", "method_code": " def make_advertise_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, server_duid_mac: Union[None, str]=None, cid: Union[None, bytes]=None, iaid: int=1, preference: Union[None, int]=None):\n if 16777215 < transaction_id < 0:\n return None\n packet_body = pack('!L', transaction_id)[1:]\n options: Dict[int, bytes] = dict()\n if cid is not None:\n options[1] = cid\n elif client_duid_timeval is None:\n options[1] = self._make_duid(ethernet_dst_mac)\n else:\n options[1] = self._make_duid(ethernet_dst_mac, client_duid_timeval)\n if server_duid_mac is None:\n options[2] = self._make_duid(ethernet_src_mac)\n else:\n options[2] = self._make_duid(server_duid_mac)\n if preference is not None:\n options[7] = pack('!B', preference)\n options[20] = b''\n options[23] = self.ipv6.pack_addr(dns_address)\n options[24] = self.dns.pack_dns_name(domain_search)\n options[82] = pack('!I', 60)\n options[3] = pack('!3I2H', iaid, 3000, 4800, 5, 24) + self.ipv6.pack_addr(ipv6_address) + pack('!2I', 4294967295, 4294967295)\n return self.make_packet(ethernet_src_mac, ethernet_dst_mac, ipv6_src, ipv6_dst, 662402, 547, 546, 2, packet_body, options)\n ", "context": "class RawDHCPv6():\n def make_advertise_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, server_duid_mac: Union[None, str]=None, cid: Union[None, bytes]=None, iaid: int=1, preference: Union[None, int]=None): ...\n def _make_duid(self, mac_address: str='01:23:45:67:89:0a', timeval: Union[None, int]=None) -> Union[None, bytes]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, udp_src_port: int=546, udp_dst_port: int=547, dhcp_message_type: int=1, packet_body: bytes=b'', options: Union[None, Dict[int, bytes]]={14: b''}, options_raw: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes): ...\n def make_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_relay_forw_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, hop_count: int=10, link_addr: str='fd00::1', peer_addr: str='fd00::2', options: Union[None, Dict[int, bytes]]=None, options_raw: Union[None, bytes]=None): ...\n def make_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, cid: Union[None, bytes]=None, server_duid_mac: Union[None, str]=None): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dhcpv6_make_advertise_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002150.py"} {"focal_file": "raw_packet/Utils/network.py", "focal_class": null, "focal_method": "make_reply_packet", "tests": "import unittest\n\nclass Test_make_reply_packet(unittest.TestCase):\n def test_dhcpv6_make_reply_packet(self):\n self.assertEqual(self.dhcpv6.make_reply_packet(ethernet_src_mac='01:23:45:67:89:0a', ethernet_dst_mac='01:23:45:67:89:0b', ipv6_src='fd00::1', ipv6_dst='fd00::2', transaction_id=1, dns_address='fd00::1', domain_search='test.local', ipv6_address='fd00::2'), b'\\x01#Eg\\x89\\x0b\\x01#Eg\\x89\\n\\x86\\xdd`\\n\\x1b\\x82\\x00\\x84\\x11@\\xfd\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + b'\\x00\\x00\\x02\\x02#\\x02\"\\x00\\x84i\\xf4\\x07\\x00\\x00\\x01\\x00\\x01\\x00\\n\\x00\\x03\\x00\\x01\\x01#Eg' + b'\\x89\\x0b\\x00\\x02\\x00\\n\\x00\\x03\\x00\\x01\\x01#Eg\\x89\\n\\x00\\x14\\x00\\x00\\x00\\x17\\x00\\x10\\xfd' + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x18\\x00\\x0c\\x04test\\x05' + b'local\\x00\\x00R\\x00\\x04\\x00\\x00\\x00<\\x00\\x03\\x00(\\x00\\x00\\x00\\x01\\x00\\x00T`\\x00\\x00\\x87' + b'\\x00\\x00\\x05\\x00\\x18\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\xff' + b'\\xff\\xff\\xff\\xff\\xff\\xff\\xff')\n", "method_code": " def make_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, cid: Union[None, bytes]=None, server_duid_mac: Union[None, str]=None):\n if 16777215 < transaction_id < 0:\n return None\n packet_body = pack('!L', transaction_id)[1:]\n options = {}\n if cid is not None:\n options[1] = cid\n elif client_duid_timeval is None:\n options[1] = self._make_duid(ethernet_dst_mac)\n else:\n options[1] = self._make_duid(ethernet_dst_mac, client_duid_timeval)\n if server_duid_mac is None:\n options[2] = self._make_duid(ethernet_src_mac)\n else:\n options[2] = self._make_duid(server_duid_mac)\n options[20] = b''\n options[23] = self.ipv6.pack_addr(dns_address)\n options[24] = self.dns.pack_dns_name(domain_search)\n options[82] = pack('!I', 60)\n options[3] = pack('!3I2H', 1, 3000, 4800, 5, 24) + self.ipv6.pack_addr(ipv6_address) + pack('!2I', 4294967295, 4294967295)\n return self.make_packet(ethernet_src_mac, ethernet_dst_mac, ipv6_src, ipv6_dst, 662402, 547, 546, 7, packet_body, options)\n ", "context": "class RawDHCPv6():\n def make_reply_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, cid: Union[None, bytes]=None, server_duid_mac: Union[None, str]=None): ...\n def _make_duid(self, mac_address: str='01:23:45:67:89:0a', timeval: Union[None, int]=None) -> Union[None, bytes]: ...\n def make_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, udp_src_port: int=546, udp_dst_port: int=547, dhcp_message_type: int=1, packet_body: bytes=b'', options: Union[None, Dict[int, bytes]]={14: b''}, options_raw: Union[None, bytes]=None) -> Union[None, bytes]: ...\n def parse_packet(self, packet: bytes): ...\n def make_solicit_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_request_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: Union[None, str]=None, ipv6_src: str='fd00::1', ipv6_dst: Union[None, str]=None, transaction_id: int=1, client_mac_address: str='01:23:45:67:89:0a', option_request_list: List[int]=[23, 24]): ...\n def make_relay_forw_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', ipv6_flow: int=1, hop_count: int=10, link_addr: str='fd00::1', peer_addr: str='fd00::2', options: Union[None, Dict[int, bytes]]=None, options_raw: Union[None, bytes]=None): ...\n def make_advertise_packet(self, ethernet_src_mac: str='01:23:45:67:89:0a', ethernet_dst_mac: str='01:23:45:67:89:0b', ipv6_src: str='fd00::1', ipv6_dst: str='fd00::2', transaction_id: int=1, dns_address: str='fd00::1', domain_search: str='domain.local', ipv6_address: str='fd00::2', client_duid_timeval: Union[None, int]=None, server_duid_mac: Union[None, str]=None, cid: Union[None, bytes]=None, iaid: int=1, preference: Union[None, int]=None): ...\n", "repository": "raw-packet/raw-packet", "test_name": "test_dhcpv6_make_reply_packet", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002151.py"} {"focal_file": "news_parser.py", "focal_class": null, "focal_method": "compile_huge_strs", "tests": "import unittest\n\nclass Test_compile_huge_strs(unittest.TestCase):\n def test_compile_huge_strs(self):\n terminator = '..[[[___]]]'\n terminator_for_parsing = '[[[___]]]'\n texts = ['7 февраля Дом-музей А. Л. Чижевского', '169,90руб -6% 11% Четвертина', 'И вот сейчас при поддержке Г. Г. Фоминой']\n huge_strs = compile_huge_strs(texts, 2)\n should_be = ['7 февраля Дом-музей А. Л. Чижевского' + terminator + '169,90руб -6% 11% Четвертина' + terminator, 'И вот сейчас при поддержке Г. Г. Фоминой' + terminator]\n self.assertEqual(huge_strs, should_be)\n", "method_code": "def compile_huge_strs(texts, huge_str_size=250):\n \"\"\"Create a list of concated strings with a total of huge_str_size in each chunk to pass to tomita for processing\n Args:\n texts: list of texts to compile into huge strings.\n Returns:\n A list of huge strings made of texts separated by a special terminator.\n \"\"\"\n huge_strs = []\n cur_pos = 0\n num = huge_str_size\n while cur_pos <= len(texts):\n huge_strs.append(''.join([text + terminator for text in texts[cur_pos:num]]))\n cur_pos = num\n num = cur_pos + huge_str_size\n return huge_strs", "context": "def compile_huge_strs(texts, huge_str_size=250): ...\ndef pdebug(*args): ...\ndef combinations(n, m): ...\ndef fuzzy_levenshtein(w1, w2): ...\ndef compile_huge_strs(texts, huge_str_size=250): ...\ndef decompile_huge_strs(tomita_output_chunks): ...\ndef post_process_tomita_facts(facts): ...\ndef parse_tomita_output(text): ...\ndef get_overlaps(facts1, facts2): ...\ndef preprocess(text): ...\ndef read_input(fname): ...\ndef tomita_parse(text): ...\ndef extract_facts(news): ...\ndef compare_and_output(news, fname): ...\ndef main(argv): ...\n", "repository": "btseytlin/news-parser", "test_name": "test_compile_huge_strs", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002152.py"} {"focal_file": "news_parser.py", "focal_class": null, "focal_method": "decompile_huge_strs", "tests": "import unittest\n\nclass Test_decompile_huge_strs(unittest.TestCase):\n def test_decompile_huge_strs(self):\n terminator = '..[[[___]]]'\n terminator_for_parsing = '[[[___]]]'\n output_chunks = ['7 февраля Дом-музей А. Л. Чижевского' + terminator + '169,90руб -6% 11% Четвертина' + terminator, 'И вот сейчас при поддержке Г. Г. Фоминой' + terminator]\n source_texts = decompile_huge_strs(output_chunks)\n should_be = ['7 февраля Дом-музей А. Л. Чижевского..', '169,90руб -6% 11% Четвертина..', 'И вот сейчас при поддержке Г. Г. Фоминой..']\n self.assertEqual(source_texts, should_be)\n", "method_code": "def decompile_huge_strs(tomita_output_chunks):\n lists_of_texts = [stdout_data.split(terminator_for_parsing) for stdout_data in tomita_output_chunks]\n huge_list = []\n for l in lists_of_texts:\n for text in l:\n if text != '':\n huge_list.append(text)\n return huge_list", "context": "def decompile_huge_strs(tomita_output_chunks): ...\ndef pdebug(*args): ...\ndef combinations(n, m): ...\ndef fuzzy_levenshtein(w1, w2): ...\ndef compile_huge_strs(texts, huge_str_size=250): ...\ndef decompile_huge_strs(tomita_output_chunks): ...\ndef post_process_tomita_facts(facts): ...\ndef parse_tomita_output(text): ...\ndef get_overlaps(facts1, facts2): ...\ndef preprocess(text): ...\ndef read_input(fname): ...\ndef tomita_parse(text): ...\ndef extract_facts(news): ...\ndef compare_and_output(news, fname): ...\ndef main(argv): ...\n", "repository": "btseytlin/news-parser", "test_name": "test_decompile_huge_strs", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002153.py"} {"focal_file": "news_parser.py", "focal_class": null, "focal_method": "preprocess", "tests": "import unittest\n\nclass Test_preprocess(unittest.TestCase):\n def test_preprocess(self):\n text = '\" ...7 февраля Дом-музей А. Л. Чижевского приглашает всех калужан и гостей города на День открытых дверей. Вход в музей свободный. \" '\n clear = '7 февраля Дом-музей А. Л. Чижевского приглашает всех калужан и гостей города на День открытых дверей. Вход в музей свободный.'\n self.assertEqual(preprocess(text), clear)\n", "method_code": "def preprocess(text):\n \"\"\"Strip useless whitespaces and trailing \" from text.\n\n Args:\n text: String to preprocess.\n Returns:\n Processed text.\n \"\"\"\n text = text.strip('\\n \"\\t').lstrip('.')\n text = re.sub('[{}\\\\]\\\\[;]', '', text)\n return text", "context": "def preprocess(text): ...\ndef pdebug(*args): ...\ndef combinations(n, m): ...\ndef fuzzy_levenshtein(w1, w2): ...\ndef compile_huge_strs(texts, huge_str_size=250): ...\ndef decompile_huge_strs(tomita_output_chunks): ...\ndef post_process_tomita_facts(facts): ...\ndef parse_tomita_output(text): ...\ndef get_overlaps(facts1, facts2): ...\ndef preprocess(text): ...\ndef read_input(fname): ...\ndef tomita_parse(text): ...\ndef extract_facts(news): ...\ndef compare_and_output(news, fname): ...\ndef main(argv): ...\n", "repository": "btseytlin/news-parser", "test_name": "test_preprocess", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002154.py"} {"focal_file": "news_parser.py", "focal_class": null, "focal_method": "parse_tomita_output", "tests": "import unittest\n\nclass Test_parse_tomita_output(unittest.TestCase):\n def test_parse_tomita_output(self):\n text = '\\n Курс рубля близок к фундаментальным уровням , риска для финансовой стабильности нет , считает глава российского Центробанка Эльвира Набиуллина \\n\\n S\\n\\n {\\n\\n Name = курс\\n\\n }\\n\\n S\\n\\n {\\n\\n Name = рубль\\n\\n }\\n\\n A\\n\\n {\\n\\n Name = близок\\n\\n }\\n\\n PR\\n\\n {\\n\\n Name = к\\n\\n }\\n\\n A\\n\\n {\\n\\n Name = фундаментальный\\n\\n }\\n\\n S\\n\\n {\\n\\n Name = уровень\\n\\n }\\n\\n S\\n\\n {\\n\\n Name = риск\\n\\n }\\n\\n PR\\n\\n {\\n\\n Name = для\\n\\n }\\n\\n A\\n\\n {\\n\\n Name = финансовая\\n\\n }\\n\\n S\\n\\n {\\n\\n Name = стабильность\\n\\n }\\n\\n ADV\\n\\n {\\n\\n Name = нет\\n\\n }\\n\\n PART\\n\\n {\\n\\n Name = нет\\n\\n }\\n\\n S\\n\\n {\\n\\n Name = нет\\n\\n }\\n\\n V\\n\\n {\\n\\n Name = считать\\n\\n }\\n\\n S\\n\\n {\\n\\n Name = глава\\n\\n }\\n\\n A\\n\\n {\\n\\n Name = российский\\n\\n }\\n\\n EntityName\\n\\n {\\n\\n Name = Центробанк\\n\\n }\\n\\n EntityName\\n\\n {\\n\\n Name = Эльвира Набиуллина\\n\\n }\\n\\n '\n facts_dict = {'EntityName': ['эльвира набиуллина', 'центробанк'], 'ADV': ['нет'], 'V': ['считать'], 'PR': ['к', 'для'], 'A': ['близок', 'фундаментальный', 'финансовая', 'российский'], 'S': ['глава', 'уровень', 'риск', 'стабильность', 'курс', 'рубль']}\n dict1 = parse_tomita_output(text)\n dict2 = facts_dict\n diffkeys = [k for k in dict1 if not sorted(dict1[k]) == sorted(dict2[k])]\n self.assertEqual(len(diffkeys) == 0, True)\n", "method_code": "def parse_tomita_output(text):\n \"\"\"Parse tomita text output to extract fact types and facts.\n\n Args:\n text: String to parse.\n\n Returns:\n Dictionary of format {'fact_type': [fact1, fact2 ... factn] }\n \"\"\"\n facts = {}\n clearing_text = str(text)\n max_iters = 50\n iteration = 0\n while clearing_text.find('{') != -1:\n iteration += 1\n if iteration >= max_iters:\n pdebug('[ERROR]COULDNT PARSE TOMITA OUTOUT:')\n pdebug(text)\n pdebug('/[ERROR]')\n print('Couldnt parse text')\n break\n opening_brace = clearing_text.find('{')\n if not opening_brace:\n break\n closing_brace = clearing_text.find('}', opening_brace)\n if not closing_brace:\n break\n fact_type = re.search('(\\\\w+\\\\s+)(?=\\\\s+\\\\{)', clearing_text[:closing_brace])\n if not fact_type:\n continue\n fact_type = fact_type.group(0).strip()\n fact_body = clearing_text[opening_brace - 1:closing_brace + 1]\n fact_text = fact_body[fact_body.find('=') + 1:-1].strip()\n if not fact_type in facts.keys():\n facts[fact_type] = []\n facts[fact_type].append(fact_text)\n clearing_text = clearing_text.replace(fact_body, '')\n return post_process_tomita_facts(facts)", "context": "def parse_tomita_output(text): ...\ndef pdebug(*args): ...\ndef combinations(n, m): ...\ndef fuzzy_levenshtein(w1, w2): ...\ndef compile_huge_strs(texts, huge_str_size=250): ...\ndef decompile_huge_strs(tomita_output_chunks): ...\ndef post_process_tomita_facts(facts): ...\ndef parse_tomita_output(text): ...\ndef get_overlaps(facts1, facts2): ...\ndef preprocess(text): ...\ndef read_input(fname): ...\ndef tomita_parse(text): ...\ndef extract_facts(news): ...\ndef compare_and_output(news, fname): ...\ndef main(argv): ...\n", "repository": "btseytlin/news-parser", "test_name": "test_parse_tomita_output", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002155.py"} {"focal_file": "news_parser.py", "focal_class": null, "focal_method": "get_overlaps", "tests": "import unittest\n\nclass Test_get_overlaps(unittest.TestCase):\n def test_get_overlaps(self):\n facts1 = {'EntityName': ['эльвира набиуллина', 'центробанк'], 'ADV': ['нет'], 'V': ['считать'], 'PR': ['к', 'для'], 'A': ['близок', 'фундаментальный', 'финансовая', 'российский'], 'S': ['глава', 'уровень', 'риск', 'стабильность', 'курс', 'рубль']}\n facts2 = {'ADV': ['да', 'сейчас'], 'V': ['заявить', 'передавать', 'пойду', 'стать', 'уточнил', 'полагать'], 'EntityName': ['банк россия', 'набиуллин', 'эльвира набиуллина', 'тасс'], 'S': ['рубль', 'курс', 'глава'], 'A': ['обоснованный', 'близок', 'фундаментально', 'текущий', 'должен'], 'APRO': ['этот', 'свой'], 'ADVPRO': ['что', 'куда'], 'PART': ['не'], 'PR': ['к', 'при'], 'CONJ': ['чтобы']}\n overlaps = get_overlaps(facts1, facts2)\n self.assertEqual(overlaps, {'ADV': 0, 'V': 0, 'EntityName': 1, 'S': 3, 'A': 1, 'PR': 1})\n", "method_code": "def get_overlaps(facts1, facts2):\n \"\"\"Find how many exactly or fuzzy same facts of each type exist in fact1 and fact2.\n\n Args:\n facts1, facts2: dictionaries of facts of format {'fact_type':[fact1, fact2 ... factn]}\n Returns:\n Dictionary of format {fact_type:overlap_number}\n \"\"\"\n overlaps = {}\n for key in facts1.keys():\n if key in facts2.keys():\n overlaps[key] = len(frozenset(facts1[key]).intersection(facts2[key]))\n if key == 'EntityName' and seek_partial_matches:\n for fact in facts1[key]:\n for fact1 in facts2[key]:\n if fact != fact1:\n if fuzzy_levenshtein(fact, fact1):\n overlaps[key] += 1\n return overlaps", "context": "def get_overlaps(facts1, facts2): ...\ndef pdebug(*args): ...\ndef combinations(n, m): ...\ndef fuzzy_levenshtein(w1, w2): ...\ndef compile_huge_strs(texts, huge_str_size=250): ...\ndef decompile_huge_strs(tomita_output_chunks): ...\ndef post_process_tomita_facts(facts): ...\ndef parse_tomita_output(text): ...\ndef get_overlaps(facts1, facts2): ...\ndef preprocess(text): ...\ndef read_input(fname): ...\ndef tomita_parse(text): ...\ndef extract_facts(news): ...\ndef compare_and_output(news, fname): ...\ndef main(argv): ...\n", "repository": "btseytlin/news-parser", "test_name": "test_get_overlaps", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002156.py"} {"focal_file": "couchstore_test.py", "focal_class": null, "focal_method": "addBulkDocs", "tests": "import unittest\n\nclass Test_addBulkDocs(unittest.TestCase):\n def testBulkDocs(self):\n self.addBulkDocs(1000)\n for i in xrange(1000):\n self.assertEqual(self.store[self.expectedKey(i)], self.expectedValue(i))\n", "method_code": " def addBulkDocs(self, n):\n ids = [self.expectedKey(i) for i in xrange(n)]\n datas = [self.expectedValue(i) for i in xrange(n)]\n self.store.save_multi(ids, datas)\n ", "context": "class CouchStoreTest(unittest.TestCase):\n def addBulkDocs(self, n): ...\n def setUp(self): ...\n def tearDown(self): ...\n def testBasicSave(self): ...\n def testMissingKey(self): ...\n def testBadKey(self): ...\n def testInfo(self): ...\n def testInfoBySequence(self): ...\n def testMissingSequence(self): ...\n def testNoContents(self): ...\n def testMetadata(self): ...\n def testMetadataSave(self): ...\n def testCompression(self): ...\n def expectedKey(self, i): ...\n def expectedValue(self, i): ...\n def addDocs(self, n): ...\n def testMultipleDocs(self): ...\n def testBulkDocs(self): ...\n def testDelete(self): ...\n def testChangesSince(self): ...\n def testForAllDocs(self): ...\n def testDocumetInfoRepr(self): ...\n def testForSomeDocs(self): ...\n def testLocalDocs(self): ...\n def testSizedBuf(self): ...\n def testBinaryMeta(self): ...\n def testMultipleMeta(self): ...\n def testMultipleMetaStruct(self): ...\n", "repository": "pavel-paulau/pycouchstore", "test_name": "testBulkDocs", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002157.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_languages", "tests": "import unittest\n\nclass Test_get_languages(unittest.TestCase):\n def test_get_language(self):\n \"\"\"\n TEDScraper.get_languagesから帰ってくる結果の長さが0でない場合True\n \"\"\"\n available_language = TEDScraper.get_languages()\n self.assertIsNot(len(available_language), 0)\n", "method_code": " def get_languages():\n \"\"\"\n Return available language, the symbol and number of talk\n \n :rtype list\n \"\"\"\n soup = TEDScraper.make_soup(TEDScraper.LANG_URL)\n lang_div = soup.find_all('div', {'class': 'languages__list__language'})\n lang_info = []\n for ld in lang_div:\n lang_type = ld.find('a').get_text()\n lang_symbol = ld.find('a').attrs['href'].replace('/talks?language=', '')\n lang_talks = ld.get_text().strip().replace(lang_type, '')\n lang_talks = re.match('\\\\d*', lang_talks)\n lang_talks = lang_talks.group()\n lang_info.append({'lang_type': lang_type, 'lang_symbol': lang_symbol, 'lang_talks': lang_talks})\n return lang_info\n ", "context": "class TEDScraper():\n @staticmethod\n def get_languages(): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_language", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002158.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_talk_titles", "tests": "import unittest\n\nclass Test_get_talk_titles(unittest.TestCase):\n def test_get_talk_titles(self):\n talk_titles = TEDScraperTest.ts.get_talk_titles(TEDScraperTest.soup)\n self.assertIsNot(len(talk_titles), 0)\n", "method_code": " def get_talk_titles(self, ta_soup):\n \"\"\"\n Get talk title\n \n :param bs4.BeautifulSoup soup:\n :rtype: list\n \"\"\"\n talk_titles = ta_soup.find_all('div', {'class': 'talk-link'})\n talk_titles = [self._find_talk_title(tt) for tt in talk_titles]\n return talk_titles\n ", "context": "class TEDScraper():\n def get_talk_titles(self, ta_soup): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_talk_titles", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002159.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_all_talk_page_list", "tests": "import unittest\n\nclass Test_get_all_talk_page_list(unittest.TestCase):\n def test_get_all_talk_page_list(self):\n page_list = TEDScraperTest.ts.get_all_talk_page_list()\n self.assertIsNot(len(page_list), 0)\n", "method_code": " def get_all_talk_page_list(self):\n \"\"\"\n Get all talk list page\n \n :rtype: list\n \"\"\"\n target_url = TEDScraper.BASE_URL\n page_list = []\n page_counter = 1\n page_list.append(target_url)\n while True:\n ta_soup = TEDScraper.make_soup(target_url)\n next_link = self.get_next_talk_list_a(ta_soup)\n if next_link is None:\n break\n page_counter += 1\n print('[ FIND ] Now page: {}'.format(page_counter))\n print(' {}'.format(next_link))\n target_url = next_link\n page_list.append(next_link)\n return page_list\n ", "context": "class TEDScraper():\n def get_all_talk_page_list(self): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_all_talk_page_list", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002160.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_talk_posted_date", "tests": "import unittest\n\nclass Test_get_talk_posted_date(unittest.TestCase):\n def test_get_talk_posted_date(self):\n talk_posted_date = TEDScraperTest.ts.get_talk_posted_date(TEDScraperTest.soup)\n self.assertIsNot(len(talk_posted_date), 0)\n", "method_code": " def get_talk_posted_date(self, ta_soup):\n \"\"\"\n Return a list of talk's posted date\n \n :param bs4.BeautifulSoup soup:\n :rtype: list\n \"\"\"\n posted_dates = ta_soup.find_all('div', {'class': 'talk-link'})\n posted_dates = [self._find_talk_posted_date(tpd) for tpd in posted_dates]\n posted_dates = [self._convert_date2str(tpd) for tpd in posted_dates]\n return posted_dates\n ", "context": "class TEDScraper():\n def get_talk_posted_date(self, ta_soup): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_talk_posted_date", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002161.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_talk_links", "tests": "import unittest\n\nclass Test_get_talk_links(unittest.TestCase):\n def test_get_talk_links(self):\n talk_links = TEDScraperTest.ts.get_talk_links(TEDScraperTest.soup)\n self.assertIsNot(len(talk_links), 0)\n", "method_code": " def get_talk_links(self, ta_soup):\n \"\"\"\n Get the link to each talk from the current talk list,\n and return a list of the link\n \n :param bs4.BeautifulSoup soup:\n :rtype: List\n \"\"\"\n talk_links = ta_soup.find_all('div', {'class': 'talk-link'})\n talk_addresses = [self._find_talk_a(tl) for tl in talk_links]\n talk_addresses = [urljoin(TEDScraper.BASE_URL, ta) for ta in talk_addresses]\n return talk_addresses\n ", "context": "class TEDScraper():\n def get_talk_links(self, ta_soup): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_talk_links", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002162.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_talk_topics", "tests": "import unittest\n\nclass Test_get_talk_topics(unittest.TestCase):\n def test_get_talk_topics(self):\n talk_links = TEDScraperTest.ts.get_talk_links(TEDScraperTest.soup)\n talk_topics = []\n for talk_link in talk_links:\n t_soup = TEDScraper.make_soup(talk_link)\n talk_topics.append(TEDScraperTest.ts.get_talk_topics(t_soup))\n for tt in talk_topics:\n if len(tt) == 0:\n self.assertFalse(len(tt) == 0)\n break\n", "method_code": " def get_talk_topics(self, ta_soup):\n \"\"\"\n Return a list of the topics of the target talk\n \n :param bs4.BeautifulSoup soup:\n :rtype: list\n \"\"\"\n talk_topics_items = self._find_talk_topics(ta_soup)\n topic_list = []\n for tti in talk_topics_items:\n topic = tti.find('a')\n if topic is not None:\n topic = topic.get_text().strip()\n topic_list.append(topic)\n return topic_list\n ", "context": "class TEDScraper():\n def get_talk_topics(self, ta_soup): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_talk_topics", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002163.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_talk_transcrpit", "tests": "import unittest\n\nclass Test_get_talk_transcrpit(unittest.TestCase):\n def test_get_talk_transcript(self):\n talk_links = TEDScraperTest.ts.get_talk_links(TEDScraperTest.soup)\n transcript_text = []\n for talk_link in talk_links:\n t_url = TEDScraper.get_transcript_url(talk_link)\n t_soup = TEDScraper.make_soup(t_url)\n transcript_text.append(TEDScraperTest.ts.get_talk_transcrpit(t_soup))\n for tt in transcript_text:\n if len(tt) == 0:\n self.assertFalse(len(tt) == 0)\n break\n", "method_code": " def get_talk_transcrpit(self, tr_soup):\n \"\"\"\n Get the transcript of the target talk\n \n :param bs4.BeautifulSoup soup:\n :rtype: list\n \"\"\"\n talk_transcript_para = self._find_transcript_para(tr_soup)\n paragraph_list = []\n for ttp in talk_transcript_para:\n tt = self._find_transcript_text(ttp)\n transcript_text = self._format_string(tt)\n paragraph_list.append(transcript_text)\n return paragraph_list\n ", "context": "class TEDScraper():\n def get_talk_transcrpit(self, tr_soup): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_talk_transcript", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002164.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_all_language_transcript", "tests": "import unittest\n\nclass Test_get_all_language_transcript(unittest.TestCase):\n def test_get_all_language_transcript(self):\n test_talk_url = 'https://www.ted.com/talks/ken_robinson_says_schools_kill_creativity'\n all_lang_transcript = TEDScraperTest.ts.get_all_language_transcript(test_talk_url)\n self.assertIsNot(len(all_lang_transcript), 0)\n", "method_code": " def get_all_language_transcript(self, ta_url):\n \"\"\"\n Get transcript of all languages available for target talk\n \n :param str talk_url:\n :rtype: dict\n \"\"\"\n t_dict = {}\n try:\n available_lang = self.get_available_language(ta_url)\n except AttributeError as e:\n print('[DEBUG] in get_all_language_transcript(): Raise AttributeError exception:')\n print(' {}'.format(e))\n t_dict['none'] = 'no transcript text found.'\n return t_dict\n lang_num = len(available_lang)\n for i, al in enumerate(available_lang):\n tr_url = TEDScraper.get_transcript_url(ta_url, al)\n print(' [{:3}/{:3}] target language: {}'.format(i + 1, lang_num, al))\n tr_soup = TEDScraper.make_soup(tr_url)\n if tr_soup is not None:\n t_dict[al] = self.get_talk_transcrpit(tr_soup)\n return t_dict\n ", "context": "class TEDScraper():\n def get_all_language_transcript(self, ta_url): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_all_language_transcript", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002165.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "get_available_language", "tests": "import unittest\n\nclass Test_get_available_language(unittest.TestCase):\n def test_get_available_language(self):\n test_talk_url = 'https://www.ted.com/talks/ken_robinson_says_schools_kill_creativity'\n available_lang = TEDScraperTest.ts.get_available_language(test_talk_url)\n self.assertIsNot(len(available_lang), 0)\n", "method_code": " def get_available_language(self, ta_url):\n \"\"\"\n Get the language available for target talk\n \n :param str talk_url:\n :rtype: list\n \"\"\"\n tr_url = TEDScraper.get_transcript_url(ta_url)\n tr_soup = TEDScraper.make_soup(tr_url)\n talk_transcript_language = self._find_transcript_language(tr_soup)\n available_lang = []\n for ttl in talk_transcript_language:\n available_lang.append(ttl.attrs['value'])\n return available_lang\n ", "context": "class TEDScraper():\n def get_available_language(self, ta_url): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_get_available_language", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002166.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "dump_talk_info", "tests": "import unittest\n\nclass Test_dump_talk_info(unittest.TestCase):\n def test_dump_talk_info(self):\n run_path = os.path.abspath(os.path.dirname('__file__'))\n save_dir = os.path.join(run_path, 'dump_files')\n TEDScraperTest.ts.dump_talk_info('https://www.ted.com/talks', save_dir)\n dir_list = os.listdir(save_dir)\n for dl in dir_list:\n with open(os.path.join(save_dir, dl), 'r') as f:\n data = json.load(f)\n for v in data.values():\n self.assertIsNot(len(v), 0)\n", "method_code": " def dump_talk_info(self, ta_url, save_dir=None):\n \"\"\"\n Dump talk info of each talk from talk list as JSON file\n \n :param str url:\n \"\"\"\n if save_dir is None:\n save_dir = './dump_files'\n if not os.path.isdir('dump_files'):\n os.mkdir('dump_files')\n print('[ CREATE ] create default dump dir ...')\n else:\n save_dir = os.path.expanduser(save_dir)\n if not os.path.isdir(save_dir):\n print('[ CREATE ] create dump dir: {}'.format(save_dir))\n os.makedirs(save_dir)\n self.target_url = ta_url\n ta_soup = TEDScraper.make_soup(ta_url)\n print('[ GET ] get scrape date ...')\n update_date = self._get_scrape_date()\n print('[ GET ] get talk posted date ...')\n talk_date = self.get_talk_posted_date(ta_soup)\n print('[ GET ] get talk titles ...')\n talk_titles = self.get_talk_titles(ta_soup)\n print('[ GET ] get talk links ...')\n talk_links = self.get_talk_links(ta_soup)\n print('[ GET ] get talk language ...')\n talk_lang = self.lang\n talk_topics = []\n talk_transcript = []\n transcript_time = []\n talk_num = len(talk_links)\n self.all_page_list = talk_num\n print('[ GET ] get talk topics and transcripts ...')\n for i, tl in enumerate(talk_links):\n self.target_page_num = i + 1\n self.target_url = tl\n print(' [{}/{}] Target URL: {}'.format(i + 1, talk_num, tl))\n ta_soup = TEDScraper.make_soup(tl)\n print(' [ GET ] get talk topics')\n talk_topics.append(self.get_talk_topics(ta_soup))\n print(' [ GET ] get talk transcript')\n tr_url = TEDScraper.get_transcript_url(tl, self.lang)\n self.target_url = tr_url\n print(' Target transcript URL: {}'.format(tr_url))\n tr_soup = TEDScraper.make_soup(tr_url)\n talk_transcript.append(self.get_talk_transcrpit(tr_soup))\n print(' [ GET ] get transcript time')\n transcript_time.append(self.get_talk_transcript_time(tr_soup))\n print('[ DUMP ] dump talk info ...')\n for date, title, link, topics, transcript, t_time in zip(talk_date, talk_titles, talk_links, talk_topics, talk_transcript, transcript_time):\n talk_info = {'posted_date': date, 'update_date': update_date, 'talk_title': title, 'talk_link': link, 'talk_lang': talk_lang, 'talk_topics': topics, 'transcript': transcript, 'time': t_time}\n filename = os.path.join(save_dir, title + '.json')\n filename = self._format_filename(filename)\n print(' dump file: {}'.format(filename))\n with open(filename, 'w') as f:\n json.dump(talk_info, f, indent=2)\n ", "context": "class TEDScraper():\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_dump_talk_info", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002167.py"} {"focal_file": "ted_talks/scraper.py", "focal_class": null, "focal_method": "dump_talk_info_al", "tests": "import unittest\n\nclass Test_dump_talk_info_al(unittest.TestCase):\n def test_dump_talk_info_al(self):\n run_path = os.path.abspath(os.path.dirname('__file__'))\n save_dir = os.path.join(run_path, 'dump_files')\n TEDScraperTest.ts.dump_talk_info_al('https://www.ted.com/talks', save_dir)\n dir_list = os.listdir(save_dir)\n for dl in dir_list:\n with open(os.path.join(save_dir, dl), 'r') as f:\n data = json.load(f)\n for v in data.values():\n self.assertIsNot(len(v), 0)\n", "method_code": " def dump_talk_info_al(self, ta_url, save_dir=None):\n \"\"\"\n Dump the following talk info as JSON file\n * posted date\n * data collection date\n * talk title\n * talk link\n * talk topics\n * transcript of all available languages\n \n :param str talk_url:\n \"\"\"\n if save_dir is None:\n save_dir = './dump_files'\n if not os.path.isdir('dump_files'):\n os.mkdir('dump_files')\n print('[ CREATE ] create default dump dir ...')\n else:\n save_dir = os.path.expanduser(save_dir)\n if not os.path.isdir(save_dir):\n print('[ CREATE ] create dump dir: {}'.format(save_dir))\n os.makedirs(save_dir)\n self.target_url = ta_url\n ta_soup = TEDScraper.make_soup(ta_url)\n print('[ GET ] get scrape date ...')\n update_date = self._get_scrape_date()\n print('[ GET ] get talk posted date ...')\n talk_date = self.get_talk_posted_date(ta_soup)\n print('[ GET ] get talk titles ...')\n talk_titles = self.get_talk_titles(ta_soup)\n print('[ GET ] get talk links ...')\n talk_links = self.get_talk_links(ta_soup)\n talk_topics = []\n talk_transcript = []\n transcript_time = []\n talk_num = len(talk_links)\n self.all_page_list = talk_num\n print('[ GET ] get talk topics and transcripts ...')\n for i, tl in enumerate(talk_links):\n self.target_page_num = i + 1\n self.target_url = tl\n print(' [{}/{}] Target URL: {}'.format(i + 1, talk_num, tl))\n ta_soup = TEDScraper.make_soup(tl)\n print(' [ GET ] get talk topics')\n talk_topics.append(self.get_talk_topics(ta_soup))\n print(' [ GET ] get all language talk transcript')\n talk_transcript.append(self.get_all_language_transcript(tl))\n tr_url = TEDScraper.get_transcript_url(tl)\n self.target_url = tr_url\n print(' Target transcript URL: {}'.format(tr_url))\n tr_soup = TEDScraper.make_soup(tr_url)\n print(' [ GET ] get transcript time')\n transcript_time.append(self.get_talk_transcript_time(tr_soup))\n print('[ DUMP ] dump talk info ... ')\n for date, title, link, topics, transcript, t_time in zip(talk_date, talk_titles, talk_links, talk_topics, talk_transcript, transcript_time):\n talk_info = {'posted_date': date, 'update_date': update_date, 'talk_title': title, 'talk_link': link, 'talk_topics': topics, 'transcript': transcript, 'time': t_time}\n title = title.replace('/', '_')\n filename = os.path.join(save_dir, 'al-' + title + '.json')\n filename = self._format_filename(filename)\n print(' dump file: {}'.format(filename))\n with open(filename, 'w') as f:\n json.dump(talk_info, f, indent=2)\n ", "context": "class TEDScraper():\n def dump_talk_info_al(self, ta_url, save_dir=None): ...\n def __init__(self, lang='en'): ...\n def make_soup(url): ...\n def get_languages(): ...\n def get_transcript_url(s, lang='en'): ...\n def get_talk_titles(self, ta_soup): ...\n def get_all_talk_titles(self, all_talk_links): ...\n def get_talk_posted_date(self, ta_soup): ...\n def get_all_talk_posted_date(self, all_talk_links): ...\n def get_talk_links(self, ta_soup): ...\n def get_all_talk_links(self): ...\n def get_all_talk_page_list(self): ...\n def get_next_talk_list_a(self, soup): ...\n def get_talk_topics(self, ta_soup): ...\n def get_all_talk_topics(self, all_talk_links): ...\n def get_talk_transcript_time(self, tr_soup): ...\n def get_all_talk_transcript_time(self, all_talk_links): ...\n def get_talk_transcrpit(self, tr_soup): ...\n def get_all_talk_transcripts(self, all_talk_links): ...\n def get_all_language_transcript(self, ta_url): ...\n def get_available_language(self, ta_url): ...\n def dump_talk_info(self, ta_url, save_dir=None): ...\n def dump_all_talk_info_al(self, save_dir=None, page_list=None): ...\n def _find_talk_posted_date(self, soup): ...\n def _find_talk_a(self, soup): ...\n def _find_talk_title(self, soup): ...\n def _find_talk_topics(self, soup): ...\n def _find_transcript_para(self, soup): ...\n def _find_transcript_text(self, soup): ...\n def _find_transcript_time(self, soup): ...\n def _find_transcript_language(self, tr_soup): ...\n def _format_string(self, s): ...\n def _format_filename(self, s): ...\n def _get_scrape_date(self): ...\n def _convert_date2str(self, date): ...\n\n self.lang = lang\n self.target_url = TEDScraper.BASE_URL\n self.target_page_list_url = ''\n self.target_page_list = 0\n self.target_page_num = 0\n self.target_talk = ''\n self.all_page_list = 0\n self.all_talk_page_num = 0\n self.start_time = 0\n self.end_time = 0\n self.all_processing_time = 0\n\n BASE_URL = 'https://www.ted.com/talks'\n LANG_URL = 'https://www.ted.com/participate/translate/our-languages'\n", "repository": "shunk031/TedScraper", "test_name": "test_dump_talk_info_al", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002168.py"} {"focal_file": "tweepymashup/streaming.py", "focal_class": null, "focal_method": "userstream", "tests": "import unittest\n\nclass Test_userstream(unittest.TestCase):\n def test_userstream(self):\n self.listener.connect_cb = self.on_connect\n self.listener.status_stop_count = 1\n self.stream.userstream()\n self.assertEqual(self.listener.status_count, 1)\n\n def test_userstream_with_params(self):\n\n def on_connect():\n API(self.auth).update_status(mock_tweet())\n self.listener.connect_cb = on_connect\n self.listener.status_stop_count = 1\n self.stream.userstream(_with='user', replies='all', stall_warnings=True)\n self.assertEqual(self.listener.status_count, 1)\n", "method_code": " def userstream(self, stall_warnings=False, _with=None, replies=None, track=None, locations=None, is_async=False, encoding='utf8'):\n self.session.params = {'delimited': 'length'}\n if self.running:\n raise TweepError('Stream object already connected!')\n self.url = '/%s/user.json' % STREAM_VERSION\n self.host = 'userstream.twitter.com'\n if stall_warnings:\n self.session.params['stall_warnings'] = stall_warnings\n if _with:\n self.session.params['with'] = _with\n if replies:\n self.session.params['replies'] = replies\n if locations and len(locations) > 0:\n if len(locations) % 4 != 0:\n raise TweepError('Wrong number of locations points, it has to be a multiple of 4')\n self.session.params['locations'] = ','.join(['%.2f' % l for l in locations])\n if track:\n self.session.params['track'] = u','.join(track).encode(encoding)\n self._start(is_async)\n ", "context": "class Stream(object):\n def userstream(self, stall_warnings=False, _with=None, replies=None, track=None, locations=None, is_async=False, encoding='utf8'): ...\n def __init__(self, auth, listener, **options): ...\n def new_session(self): ...\n def _run(self): ...\n def _data(self, data): ...\n def _read_loop(self, resp): ...\n def _start(self, is_async): ...\n def on_closed(self, resp): ...\n def firehose(self, count=None, is_async=False): ...\n def retweet(self, is_async=False): ...\n def sample(self, is_async=False, languages=None, stall_warnings=False): ...\n def filter(self, follow=None, track=None, is_async=False, locations=None, stall_warnings=False, languages=None, encoding='utf8', filter_level=None): ...\n def sitestream(self, follow, stall_warnings=False, with_='user', replies=False, is_async=False): ...\n def disconnect(self): ...\n\n self.auth = auth\n self.listener = listener\n self.running = False\n self.daemon = options.get('daemon', False)\n self.timeout = options.get('timeout', 300.0)\n self.retry_count = options.get('retry_count')\n self.retry_time_start = options.get('retry_time', 5.0)\n self.retry_420_start = options.get('retry_420', 60.0)\n self.retry_time_cap = options.get('retry_time_cap', 320.0)\n self.snooze_time_step = options.get('snooze_time', 0.25)\n self.snooze_time_cap = options.get('snooze_time_cap', 16)\n self.chunk_size = options.get('chunk_size', 512)\n self.verify = options.get('verify', True)\n self.api = API()\n self.headers = options.get('headers') or {}\n self.body = None\n self.retry_time = self.retry_time_start\n self.snooze_time = self.snooze_time_step\n self.proxies = options.get('proxies')\n self.host = options.get('host', 'stream.twitter.com')\n", "repository": "oblockton/tweepy_fix", "test_name": "test_userstream", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002169.py"} {"focal_file": "tweepymashup/streaming.py", "focal_class": null, "focal_method": "sitestream", "tests": "import unittest\n\nclass Test_sitestream(unittest.TestCase):\n @skip('Sitestream only available to whitelisted accounts.')\n def test_sitestream(self):\n self.listener.connect_cb = self.on_connect\n self.listener.status_stop_count = 1\n self.stream.sitestream(follow=[self.auth.get_username()])\n self.assertEqual(self.listener.status_count, 1)\n", "method_code": " def sitestream(self, follow, stall_warnings=False, with_='user', replies=False, is_async=False):\n self.body = {}\n if self.running:\n raise TweepError('Stream object already connected!')\n self.url = '/%s/site.json' % STREAM_VERSION\n self.body['follow'] = u','.join(map(six.text_type, follow))\n self.body['delimited'] = 'length'\n if stall_warnings:\n self.body['stall_warnings'] = stall_warnings\n if with_:\n self.body['with'] = with_\n if replies:\n self.body['replies'] = replies\n self._start(is_async)\n ", "context": "class Stream(object):\n def sitestream(self, follow, stall_warnings=False, with_='user', replies=False, is_async=False): ...\n def __init__(self, auth, listener, **options): ...\n def new_session(self): ...\n def _run(self): ...\n def _data(self, data): ...\n def _read_loop(self, resp): ...\n def _start(self, is_async): ...\n def on_closed(self, resp): ...\n def userstream(self, stall_warnings=False, _with=None, replies=None, track=None, locations=None, is_async=False, encoding='utf8'): ...\n def firehose(self, count=None, is_async=False): ...\n def retweet(self, is_async=False): ...\n def sample(self, is_async=False, languages=None, stall_warnings=False): ...\n def filter(self, follow=None, track=None, is_async=False, locations=None, stall_warnings=False, languages=None, encoding='utf8', filter_level=None): ...\n def disconnect(self): ...\n\n self.auth = auth\n self.listener = listener\n self.running = False\n self.daemon = options.get('daemon', False)\n self.timeout = options.get('timeout', 300.0)\n self.retry_count = options.get('retry_count')\n self.retry_time_start = options.get('retry_time', 5.0)\n self.retry_420_start = options.get('retry_420', 60.0)\n self.retry_time_cap = options.get('retry_time_cap', 320.0)\n self.snooze_time_step = options.get('snooze_time', 0.25)\n self.snooze_time_cap = options.get('snooze_time_cap', 16)\n self.chunk_size = options.get('chunk_size', 512)\n self.verify = options.get('verify', True)\n self.api = API()\n self.headers = options.get('headers') or {}\n self.body = None\n self.retry_time = self.retry_time_start\n self.snooze_time = self.snooze_time_step\n self.proxies = options.get('proxies')\n self.host = options.get('host', 'stream.twitter.com')\n", "repository": "oblockton/tweepy_fix", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002170.py"} {"focal_file": "tweepymashup/streaming.py", "focal_class": null, "focal_method": "sample", "tests": "import unittest\n\nclass Test_sample(unittest.TestCase):\n def test_sample(self):\n self.listener.status_stop_count = 10\n self.stream.sample()\n self.assertEqual(self.listener.status_count, self.listener.status_stop_count)\n", "method_code": " def sample(self, is_async=False, languages=None, stall_warnings=False):\n self.session.params = {'delimited': 'length'}\n if self.running:\n raise TweepError('Stream object already connected!')\n self.url = '/%s/statuses/sample.json' % STREAM_VERSION\n if languages:\n self.session.params['language'] = ','.join(map(str, languages))\n if stall_warnings:\n self.session.params['stall_warnings'] = 'true'\n self._start(is_async)\n ", "context": "class Stream(object):\n def sample(self, is_async=False, languages=None, stall_warnings=False): ...\n def __init__(self, auth, listener, **options): ...\n def new_session(self): ...\n def _run(self): ...\n def _data(self, data): ...\n def _read_loop(self, resp): ...\n def _start(self, is_async): ...\n def on_closed(self, resp): ...\n def userstream(self, stall_warnings=False, _with=None, replies=None, track=None, locations=None, is_async=False, encoding='utf8'): ...\n def firehose(self, count=None, is_async=False): ...\n def retweet(self, is_async=False): ...\n def filter(self, follow=None, track=None, is_async=False, locations=None, stall_warnings=False, languages=None, encoding='utf8', filter_level=None): ...\n def sitestream(self, follow, stall_warnings=False, with_='user', replies=False, is_async=False): ...\n def disconnect(self): ...\n\n self.auth = auth\n self.listener = listener\n self.running = False\n self.daemon = options.get('daemon', False)\n self.timeout = options.get('timeout', 300.0)\n self.retry_count = options.get('retry_count')\n self.retry_time_start = options.get('retry_time', 5.0)\n self.retry_420_start = options.get('retry_420', 60.0)\n self.retry_time_cap = options.get('retry_time_cap', 320.0)\n self.snooze_time_step = options.get('snooze_time', 0.25)\n self.snooze_time_cap = options.get('snooze_time_cap', 16)\n self.chunk_size = options.get('chunk_size', 512)\n self.verify = options.get('verify', True)\n self.api = API()\n self.headers = options.get('headers') or {}\n self.body = None\n self.retry_time = self.retry_time_start\n self.snooze_time = self.snooze_time_step\n self.proxies = options.get('proxies')\n self.host = options.get('host', 'stream.twitter.com')\n", "repository": "oblockton/tweepy_fix", "test_name": "test_sample", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002171.py"} {"focal_file": "tweepymashup/streaming.py", "focal_class": null, "focal_method": "filter", "tests": "import unittest\n\nclass Test_filter(unittest.TestCase):\n def test_filter_track(self):\n self.listener.status_stop_count = 5\n phrases = ['twitter']\n self.stream.filter(track=phrases)\n self.assertEqual(self.listener.status_count, self.listener.status_stop_count)\n", "method_code": " def filter(self, follow=None, track=None, is_async=False, locations=None, stall_warnings=False, languages=None, encoding='utf8', filter_level=None):\n self.body = {}\n self.session.headers['Content-type'] = 'application/x-www-form-urlencoded'\n if self.running:\n raise TweepError('Stream object already connected!')\n self.url = '/%s/statuses/filter.json' % STREAM_VERSION\n if follow:\n self.body['follow'] = u','.join(follow).encode(encoding)\n if track:\n self.body['track'] = u','.join(track).encode(encoding)\n if locations and len(locations) > 0:\n if len(locations) % 4 != 0:\n raise TweepError('Wrong number of locations points, it has to be a multiple of 4')\n self.body['locations'] = u','.join(['%.4f' % l for l in locations])\n if stall_warnings:\n self.body['stall_warnings'] = stall_warnings\n if languages:\n self.body['language'] = u','.join(map(str, languages))\n if filter_level:\n self.body['filter_level'] = filter_level.encode(encoding)\n self.session.params = {'delimited': 'length'}\n self._start(is_async)\n ", "context": "class Stream(object):\n def filter(self, follow=None, track=None, is_async=False, locations=None, stall_warnings=False, languages=None, encoding='utf8', filter_level=None): ...\n def __init__(self, auth, listener, **options): ...\n def new_session(self): ...\n def _run(self): ...\n def _data(self, data): ...\n def _read_loop(self, resp): ...\n def _start(self, is_async): ...\n def on_closed(self, resp): ...\n def userstream(self, stall_warnings=False, _with=None, replies=None, track=None, locations=None, is_async=False, encoding='utf8'): ...\n def firehose(self, count=None, is_async=False): ...\n def retweet(self, is_async=False): ...\n def sample(self, is_async=False, languages=None, stall_warnings=False): ...\n def sitestream(self, follow, stall_warnings=False, with_='user', replies=False, is_async=False): ...\n def disconnect(self): ...\n\n self.auth = auth\n self.listener = listener\n self.running = False\n self.daemon = options.get('daemon', False)\n self.timeout = options.get('timeout', 300.0)\n self.retry_count = options.get('retry_count')\n self.retry_time_start = options.get('retry_time', 5.0)\n self.retry_420_start = options.get('retry_420', 60.0)\n self.retry_time_cap = options.get('retry_time_cap', 320.0)\n self.snooze_time_step = options.get('snooze_time', 0.25)\n self.snooze_time_cap = options.get('snooze_time_cap', 16)\n self.chunk_size = options.get('chunk_size', 512)\n self.verify = options.get('verify', True)\n self.api = API()\n self.headers = options.get('headers') or {}\n self.body = None\n self.retry_time = self.retry_time_start\n self.snooze_time = self.snooze_time_step\n self.proxies = options.get('proxies')\n self.host = options.get('host', 'stream.twitter.com')\n", "repository": "oblockton/tweepy_fix", "test_name": "test_filter_track", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002172.py"} {"focal_file": "tweepymashup/utils.py", "focal_class": null, "focal_method": "parse_datetime", "tests": "import unittest\n\nclass Test_parse_datetime(unittest.TestCase):\n def testparse_datetime(self):\n result = parse_datetime('Wed Aug 27 13:08:45 +0000 2008')\n self.assertEqual(datetime(2008, 8, 27, 13, 8, 45), result)\n", "method_code": "def parse_datetime(string):\n return datetime(*parsedate(string)[:6])", "context": "def parse_datetime(string): ...\ndef parse_datetime(string): ...\ndef parse_html_value(html): ...\ndef parse_a_href(atag): ...\ndef convert_to_utf8_str(arg): ...\ndef list_to_csv(item_list): ...\n", "repository": "oblockton/tweepy_fix", "test_name": "testparse_datetime", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002173.py"} {"focal_file": "tweepymashup/utils.py", "focal_class": null, "focal_method": "list_to_csv", "tests": "import unittest\n\nclass Test_list_to_csv(unittest.TestCase):\n def testlist_to_csv(self):\n self.assertEqual('1,2,3', list_to_csv([1, 2, 3]))\n self.assertEqual('bird,tweet,nest,egg', list_to_csv(['bird', 'tweet', 'nest', 'egg']))\n", "method_code": "def list_to_csv(item_list):\n if item_list:\n return ','.join([str(i) for i in item_list])", "context": "def list_to_csv(item_list): ...\ndef parse_datetime(string): ...\ndef parse_html_value(html): ...\ndef parse_a_href(atag): ...\ndef convert_to_utf8_str(arg): ...\ndef list_to_csv(item_list): ...\n", "repository": "oblockton/tweepy_fix", "test_name": "testlist_to_csv", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002174.py"} {"focal_file": "src/simplejson/__init__.py", "focal_class": null, "focal_method": "dumps", "tests": "import unittest\n\nclass Test_dumps(unittest.TestCase):\n def test_namedtuple_dumps(self):\n for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:\n d = v._asdict()\n self.assertEqual(d, json.loads(json.dumps(v)))\n self.assertEqual(d, json.loads(json.dumps(v, namedtuple_as_object=True)))\n self.assertEqual(d, json.loads(json.dumps(v, tuple_as_array=False)))\n self.assertEqual(d, json.loads(json.dumps(v, namedtuple_as_object=True, tuple_as_array=False)))\n\n def test_asdict_not_callable_dumps(self):\n for f in CONSTRUCTORS:\n self.assertRaises(TypeError, json.dumps, f(DeadDuck()), namedtuple_as_object=True)\n self.assertEqual(json.dumps(f({})), json.dumps(f(DeadDict()), namedtuple_as_object=True))\n\n def test_tuple_array_dumps(self):\n t = (1, 2, 3)\n expect = json.dumps(list(t))\n self.assertEqual(expect, json.dumps(t))\n self.assertEqual(expect, json.dumps(t, tuple_as_array=True))\n self.assertRaises(TypeError, json.dumps, t, tuple_as_array=False)\n self.assertEqual(expect, json.dumps(t, default=repr))\n self.assertEqual(expect, json.dumps(t, tuple_as_array=True, default=repr))\n self.assertEqual(json.dumps(repr(t)), json.dumps(t, tuple_as_array=False, default=repr))\n", "method_code": "def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw):\n \"\"\"Serialize ``obj`` to a JSON formatted ``str``.\n\n If ``skipkeys`` is false then ``dict`` keys that are not basic types\n (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\n will be skipped instead of raising a ``TypeError``.\n\n If ``ensure_ascii`` is false, then the return value will be a\n ``unicode`` instance subject to normal Python ``str`` to ``unicode``\n coercion rules instead of being escaped to an ASCII ``str``.\n\n If ``check_circular`` is false, then the circular reference check\n for container types will be skipped and a circular reference will\n result in an ``OverflowError`` (or worse).\n\n If ``allow_nan`` is false, then it will be a ``ValueError`` to\n serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in\n strict compliance of the JSON specification, instead of using the\n JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n\n If ``indent`` is a string, then JSON array elements and object members\n will be pretty-printed with a newline followed by that string repeated\n for each level of nesting. ``None`` (the default) selects the most compact\n representation without any newlines. For backwards compatibility with\n versions of simplejson earlier than 2.1.0, an integer is also accepted\n and is converted to a string with that many spaces.\n\n If specified, ``separators`` should be an\n ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``\n if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most\n compact JSON representation, you should specify ``(',', ':')`` to eliminate\n whitespace.\n\n ``encoding`` is the character encoding for str instances, default is UTF-8.\n\n ``default(obj)`` is a function that should return a serializable version\n of obj or raise TypeError. The default simply raises TypeError.\n\n If *use_decimal* is true (default: ``True``) then decimal.Decimal\n will be natively serialized to JSON with full precision.\n\n If *namedtuple_as_object* is true (default: ``True``),\n :class:`tuple` subclasses with ``_asdict()`` methods will be encoded\n as JSON objects.\n\n If *tuple_as_array* is true (default: ``True``),\n :class:`tuple` (and subclasses) will be encoded as JSON arrays.\n\n If *iterable_as_array* is true (default: ``False``),\n any object not in the above table that implements ``__iter__()``\n will be encoded as a JSON array.\n\n If *bigint_as_string* is true (not the default), ints 2**53 and higher\n or lower than -2**53 will be encoded as strings. This is to avoid the\n rounding that happens in Javascript otherwise.\n\n If *int_as_string_bitcount* is a positive number (n), then int of size\n greater than or equal to 2**n or lower than or equal to -2**n will be\n encoded as strings.\n\n If specified, *item_sort_key* is a callable used to sort the items in\n each dictionary. This is useful if you want to sort items other than\n in alphabetical order by key. This option takes precendence over\n *sort_keys*.\n\n If *sort_keys* is true (default: ``False``), the output of dictionaries\n will be sorted by item.\n\n If *for_json* is true (default: ``False``), objects with a ``for_json()``\n method will use the return value of that method for encoding as JSON\n instead of the object.\n\n If *ignore_nan* is true (default: ``False``), then out of range\n :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as\n ``null`` in compliance with the ECMA-262 specification. If true, this will\n override *allow_nan*.\n\n To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n ``.default()`` method to serialize additional types), specify it with\n the ``cls`` kwarg. NOTE: You should use *default* instead of subclassing\n whenever possible.\n\n \"\"\"\n if not skipkeys and ensure_ascii and check_circular and allow_nan and (cls is None) and (indent is None) and (separators is None) and (encoding == 'utf-8') and (default is None) and use_decimal and namedtuple_as_object and tuple_as_array and (not iterable_as_array) and (not bigint_as_string) and (not sort_keys) and (not item_sort_key) and (not for_json) and (not ignore_nan) and (int_as_string_bitcount is None) and (not kw):\n return _default_encoder.encode(obj)\n if cls is None:\n cls = JSONEncoder\n return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, iterable_as_array=iterable_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, int_as_string_bitcount=int_as_string_bitcount, **kw).encode(obj)", "context": "def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef _import_OrderedDict(): ...\ndef _import_c_make_encoder(): ...\ndef dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): ...\ndef loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): ...\ndef _toggle_speedups(enabled): ...\ndef simple_first(kv): ...\n", "repository": "bitblit/AlexaJacket", "test_name": "test_namedtuple_dumps", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002175.py"} {"focal_file": "src/simplejson/__init__.py", "focal_class": null, "focal_method": "dump", "tests": "import unittest\n\nclass Test_dump(unittest.TestCase):\n def test_namedtuple_dump(self):\n for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:\n d = v._asdict()\n sio = StringIO()\n json.dump(v, sio)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, namedtuple_as_object=True)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, tuple_as_array=False)\n self.assertEqual(d, json.loads(sio.getvalue()))\n sio = StringIO()\n json.dump(v, sio, namedtuple_as_object=True, tuple_as_array=False)\n self.assertEqual(d, json.loads(sio.getvalue()))\n\n def test_asdict_not_callable_dump(self):\n for f in CONSTRUCTORS:\n self.assertRaises(TypeError, json.dump, f(DeadDuck()), StringIO(), namedtuple_as_object=True)\n sio = StringIO()\n json.dump(f(DeadDict()), sio, namedtuple_as_object=True)\n self.assertEqual(json.dumps(f({})), sio.getvalue())\n\n def test_tuple_array_dump(self):\n t = (1, 2, 3)\n expect = json.dumps(list(t))\n sio = StringIO()\n json.dump(t, sio)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=True)\n self.assertEqual(expect, sio.getvalue())\n self.assertRaises(TypeError, json.dump, t, StringIO(), tuple_as_array=False)\n sio = StringIO()\n json.dump(t, sio, default=repr)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=True, default=repr)\n self.assertEqual(expect, sio.getvalue())\n sio = StringIO()\n json.dump(t, sio, tuple_as_array=False, default=repr)\n self.assertEqual(json.dumps(repr(t)), sio.getvalue())\n", "method_code": "def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw):\n \"\"\"Serialize ``obj`` as a JSON formatted stream to ``fp`` (a\n ``.write()``-supporting file-like object).\n\n If *skipkeys* is true then ``dict`` keys that are not basic types\n (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\n will be skipped instead of raising a ``TypeError``.\n\n If *ensure_ascii* is false, then the some chunks written to ``fp``\n may be ``unicode`` instances, subject to normal Python ``str`` to\n ``unicode`` coercion rules. Unless ``fp.write()`` explicitly\n understands ``unicode`` (as in ``codecs.getwriter()``) this is likely\n to cause an error.\n\n If *check_circular* is false, then the circular reference check\n for container types will be skipped and a circular reference will\n result in an ``OverflowError`` (or worse).\n\n If *allow_nan* is false, then it will be a ``ValueError`` to\n serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)\n in strict compliance of the original JSON specification, instead of using\n the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). See\n *ignore_nan* for ECMA-262 compliant behavior.\n\n If *indent* is a string, then JSON array elements and object members\n will be pretty-printed with a newline followed by that string repeated\n for each level of nesting. ``None`` (the default) selects the most compact\n representation without any newlines. For backwards compatibility with\n versions of simplejson earlier than 2.1.0, an integer is also accepted\n and is converted to a string with that many spaces.\n\n If specified, *separators* should be an\n ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``\n if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most\n compact JSON representation, you should specify ``(',', ':')`` to eliminate\n whitespace.\n\n *encoding* is the character encoding for str instances, default is UTF-8.\n\n *default(obj)* is a function that should return a serializable version\n of obj or raise ``TypeError``. The default simply raises ``TypeError``.\n\n If *use_decimal* is true (default: ``True``) then decimal.Decimal\n will be natively serialized to JSON with full precision.\n\n If *namedtuple_as_object* is true (default: ``True``),\n :class:`tuple` subclasses with ``_asdict()`` methods will be encoded\n as JSON objects.\n\n If *tuple_as_array* is true (default: ``True``),\n :class:`tuple` (and subclasses) will be encoded as JSON arrays.\n\n If *iterable_as_array* is true (default: ``False``),\n any object not in the above table that implements ``__iter__()``\n will be encoded as a JSON array.\n\n If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher\n or lower than -2**53 will be encoded as strings. This is to avoid the\n rounding that happens in Javascript otherwise. Note that this is still a\n lossy operation that will not round-trip correctly and should be used\n sparingly.\n\n If *int_as_string_bitcount* is a positive number (n), then int of size\n greater than or equal to 2**n or lower than or equal to -2**n will be\n encoded as strings.\n\n If specified, *item_sort_key* is a callable used to sort the items in\n each dictionary. This is useful if you want to sort items other than\n in alphabetical order by key. This option takes precedence over\n *sort_keys*.\n\n If *sort_keys* is true (default: ``False``), the output of dictionaries\n will be sorted by item.\n\n If *for_json* is true (default: ``False``), objects with a ``for_json()``\n method will use the return value of that method for encoding as JSON\n instead of the object.\n\n If *ignore_nan* is true (default: ``False``), then out of range\n :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as\n ``null`` in compliance with the ECMA-262 specification. If true, this will\n override *allow_nan*.\n\n To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n ``.default()`` method to serialize additional types), specify it with\n the ``cls`` kwarg. NOTE: You should use *default* or *for_json* instead\n of subclassing whenever possible.\n\n \"\"\"\n if not skipkeys and ensure_ascii and check_circular and allow_nan and (cls is None) and (indent is None) and (separators is None) and (encoding == 'utf-8') and (default is None) and use_decimal and namedtuple_as_object and tuple_as_array and (not iterable_as_array) and (not bigint_as_string) and (not sort_keys) and (not item_sort_key) and (not for_json) and (not ignore_nan) and (int_as_string_bitcount is None) and (not kw):\n iterable = _default_encoder.iterencode(obj)\n else:\n if cls is None:\n cls = JSONEncoder\n iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, iterable_as_array=iterable_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, int_as_string_bitcount=int_as_string_bitcount, **kw).iterencode(obj)\n for chunk in iterable:\n fp.write(chunk)", "context": "def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef _import_OrderedDict(): ...\ndef _import_c_make_encoder(): ...\ndef dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw): ...\ndef load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): ...\ndef loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): ...\ndef _toggle_speedups(enabled): ...\ndef simple_first(kv): ...\n", "repository": "bitblit/AlexaJacket", "test_name": "test_namedtuple_dump", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002176.py"} {"focal_file": "linty_fresh/linters/android.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), android.parse('', pass_warnings=False))\n", "method_code": "def parse(contents: str, pass_warnings: bool, **kwargs) -> Set[Problem]:\n result = set()\n try:\n root = ElementTree.fromstring(contents)\n except ElementTree.ParseError:\n return result\n for issue in root.findall('issue'):\n location = issue.getchildren()[0]\n if issue.get('severity') == 'Warning' and pass_warnings:\n pass\n else:\n result.add(Problem(location.get('file'), location.get('line', '0'), '{}: {}'.format(issue.get('summary'), issue.get('message'))))\n return result", "context": "def parse(contents: str, pass_warnings: bool, **kwargs) -> Set[Problem]: ...\ndef parse(contents: str, pass_warnings: bool, **kwargs) -> Set[Problem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002177.py"} {"focal_file": "linty_fresh/linters/buck_unittest.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), buck_unittest.parse(''))\n", "method_code": "def parse(contents: str, **kwargs) -> Set[TestProblem]:\n result = set()\n try:\n root = ElementTree.fromstring(contents)\n except ElementTree.ParseError:\n return result\n for test in root.findall('test'):\n if test.get('status') == 'FAIL':\n test_group = test.get('name')\n for tr in test.findall('testresult'):\n message = None\n stack_trace = None\n for m in tr.findall('message'):\n if m.text:\n message = m.text\n for st in tr.findall('stacktrace'):\n if st.text:\n stack_trace = st.text\n if stack_trace and message:\n test_name = tr.get('name')\n result.add(TestProblem(test_group, test_name, message, stack_trace))\n return result", "context": "def parse(contents: str, **kwargs) -> Set[TestProblem]: ...\ndef parse(contents: str, **kwargs) -> Set[TestProblem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002178.py"} {"focal_file": "linty_fresh/linters/checkstyle.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), checkstyle.parse(''))\n", "method_code": "def parse(contents: str, **kwargs) -> Set[Problem]:\n result = set()\n try:\n root = ElementTree.fromstring(contents)\n except ElementTree.ParseError:\n return result\n for file in root.findall('file'):\n file_name = file.get('name')\n for error in file.findall('error'):\n result.add(Problem(file_name, error.get('line'), '{}: {}'.format(error.get('source'), error.get('message'))))\n return result", "context": "def parse(contents: str, **kwargs) -> Set[Problem]: ...\ndef parse(contents: str, **kwargs) -> Set[Problem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002179.py"} {"focal_file": "linty_fresh/linters/mypy.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), mypy.parse(''))\n", "method_code": "def parse(contents: str, **kwargs) -> Set[Problem]:\n result = set()\n for line in contents.splitlines():\n match = MYPY_LINE_REGEX.match(line)\n if match:\n groups = match.groupdict()\n if groups['code'] != 'note':\n result.add(Problem(groups['path'], groups['line'], '{}: {}'.format(groups['code'], groups['message'])))\n return result", "context": "def parse(contents: str, **kwargs) -> Set[Problem]: ...\ndef parse(contents: str, **kwargs) -> Set[Problem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002180.py"} {"focal_file": "linty_fresh/linters/passthrough.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), passthrough.parse(''))\n", "method_code": "def parse(contents: str, **kwargs) -> Set[Problem]:\n if contents:\n return {Problem('', 0, contents.strip())}\n else:\n return set()", "context": "def parse(contents: str, **kwargs) -> Set[Problem]: ...\ndef parse(contents: str, **kwargs) -> Set[Problem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002181.py"} {"focal_file": "linty_fresh/linters/pmd.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), pmd.parse(''))\n", "method_code": "def parse(contents: str, **kwargs) -> Set[Problem]:\n result = set()\n try:\n root = ElementTree.fromstring(contents)\n except ElementTree.ParseError:\n return result\n for file in root.findall('file'):\n file_name = file.get('name')\n for violation in file.findall('violation'):\n result.add(Problem(file_name, violation.get('beginline'), '{}: {}'.format(violation.get('rule'), violation.text.strip())))\n return result", "context": "def parse(contents: str, **kwargs) -> Set[Problem]: ...\ndef parse(contents: str, **kwargs) -> Set[Problem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002182.py"} {"focal_file": "linty_fresh/linters/pylint.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), pylint.parse(''))\n", "method_code": "def parse(contents: str, **kwargs) -> Set[Problem]:\n result = set()\n for line in contents.splitlines():\n match = PYLINT_LINE_REGEX.match(line)\n if match:\n groups = match.groupdict()\n result.add(Problem(groups['path'], groups['line'], groups['message']))\n return result", "context": "def parse(contents: str, **kwargs) -> Set[Problem]: ...\ndef parse(contents: str, **kwargs) -> Set[Problem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002183.py"} {"focal_file": "linty_fresh/linters/swiftlint.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), swiftlint.parse(''))\n", "method_code": "def parse(contents: str, **kwargs) -> Set[Problem]:\n result = set()\n for line in contents.splitlines():\n match = SWIFTLINT_LINE_REGEX.match(line)\n if match:\n groups = match.groupdict()\n result.add(Problem(os.path.relpath(groups['path']), groups['line'], groups['message']))\n return result", "context": "def parse(contents: str, **kwargs) -> Set[Problem]: ...\ndef parse(contents: str, **kwargs) -> Set[Problem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002184.py"} {"focal_file": "linty_fresh/linters/xcodebuild.py", "focal_class": null, "focal_method": "parse", "tests": "import unittest\n\nclass Test_parse(unittest.TestCase):\n def test_empty_parse(self):\n self.assertEqual(set(), xcodebuild.parse(''))\n\n def test_should_not_parse(self):\n test_string = ['Details: log recorder was sent -stopRecordingWithInfo:completionBlock: after it had already been asked to stop recording.']\n result = xcodebuild.parse('\\n'.join(test_string))\n self.assertEqual(0, len(result))\n", "method_code": "def parse(contents: str, **kwargs) -> Set[Problem]:\n result = set()\n for line in contents.splitlines():\n match = XCODEBUILD_LINE_REGEX.match(line)\n if match:\n groups = match.groupdict()\n line = groups['line'] or 0\n message = groups['message']\n reference = groups['reference']\n if reference:\n message = f'{reference}: {message}'\n result.add(Problem(os.path.relpath(groups['path']), line, message))\n return result", "context": "def parse(contents: str, **kwargs) -> Set[Problem]: ...\ndef parse(contents: str, **kwargs) -> Set[Problem]: ...\n", "repository": "lyft/linty_fresh", "test_name": "test_empty_parse", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002185.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/auth.py", "focal_class": null, "focal_method": "modify_request", "tests": "import unittest\n\nclass Test_modify_request(unittest.TestCase):\n def test_modify_request(self):\n http_request = atom.http_core.HttpRequest()\n credentials = atom.auth.BasicAuth('Aladdin', 'open sesame')\n self.assert_(credentials.basic_cookie == 'QWxhZGRpbjpvcGVuIHNlc2FtZQ==')\n credentials.modify_request(http_request)\n self.assert_(http_request.headers['Authorization'] == 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')\n", "method_code": " def modify_request(self, http_request):\n http_request.headers['Authorization'] = 'Basic %s' % self.basic_cookie\n ", "context": "class BasicAuth(object):\n def modify_request(self, http_request): ...\n def __init__(self, user_id, password): ...\n\n self.basic_cookie = base64.encodestring('%s:%s' % (user_id, password)).strip()\n\n ModifyRequest = modify_request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_modify_request", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002186.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/client.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_get(self):\n client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient())\n response = client.get('http://example.com/simple')\n self.assert_(response.getheader('Echo-Host') == 'example.com:None')\n self.assert_(response.getheader('Echo-Uri') == '/simple')\n self.assert_(response.getheader('Echo-Method') == 'GET')\n response = client.Get(uri='http://example.com/simple2')\n self.assert_(response.getheader('Echo-Uri') == '/simple2')\n self.assert_(response.getheader('Echo-Method') == 'GET')\n", "method_code": " def get(self, uri=None, auth_token=None, http_request=None, **kwargs):\n \"\"\"Performs a request using the GET method, returns an HTTP response.\"\"\"\n return self.request(method='GET', uri=uri, auth_token=auth_token, http_request=http_request, **kwargs)\n ", "context": "class AtomPubClient(object):\n def get(self, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def __init__(self, http_client=None, host=None, auth_token=None, source=None, xoauth_requestor_id=None, **kwargs): ...\n def request(self, method=None, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def post(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): ...\n def put(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): ...\n def delete(self, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def modify_request(self, http_request): ...\n\n self.http_client = http_client or atom.http_core.ProxiedHttpClient()\n self.xoauth_requestor_id = xoauth_requestor_id\n self.source = source\n\n host = None\n auth_token = None\n ssl = False\n xoauth_requestor_id = None\n Request = request\n Get = get\n Post = post\n Put = put\n Delete = delete\n ModifyRequest = modify_request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_get", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002187.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/client.py", "focal_class": null, "focal_method": "post", "tests": "import unittest\n\nclass Test_post(unittest.TestCase):\n def test_post(self):\n client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient())\n\n class TestData(object):\n\n def modify_request(self, http_request):\n http_request.add_body_part('test body', 'text/testdata')\n response = client.Post(uri='http://example.com/', data=TestData())\n self.assert_(response.getheader('Echo-Host') == 'example.com:None')\n self.assert_(response.getheader('Echo-Uri') == '/')\n self.assert_(response.getheader('Echo-Method') == 'POST')\n self.assert_(response.getheader('Content-Length') == str(len('test body')))\n self.assert_(response.getheader('Content-Type') == 'text/testdata')\n self.assert_(response.read(2) == 'te')\n self.assert_(response.read() == 'st body')\n response = client.post(data=TestData(), uri='http://example.com/')\n self.assert_(response.read() == 'test body')\n self.assert_(response.getheader('Content-Type') == 'text/testdata')\n response = client.post(x=TestData(), uri='http://example.com/')\n self.assert_(response.read() == 'test body')\n", "method_code": " def post(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs):\n \"\"\"Sends data using the POST method, returns an HTTP response.\"\"\"\n return self.request(method='POST', uri=uri, auth_token=auth_token, http_request=http_request, data=data, **kwargs)\n ", "context": "class AtomPubClient(object):\n def post(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): ...\n def __init__(self, http_client=None, host=None, auth_token=None, source=None, xoauth_requestor_id=None, **kwargs): ...\n def request(self, method=None, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def get(self, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def put(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): ...\n def delete(self, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def modify_request(self, http_request): ...\n\n self.http_client = http_client or atom.http_core.ProxiedHttpClient()\n self.xoauth_requestor_id = xoauth_requestor_id\n self.source = source\n\n host = None\n auth_token = None\n ssl = False\n xoauth_requestor_id = None\n Request = request\n Get = get\n Post = post\n Put = put\n Delete = delete\n ModifyRequest = modify_request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_post", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002188.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/client.py", "focal_class": null, "focal_method": "put", "tests": "import unittest\n\nclass Test_put(unittest.TestCase):\n def test_put(self):\n body_text = 'test'\n client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient())\n\n class TestData(object):\n\n def modify_request(self, http_request):\n http_request.add_body_part(body_text, 'application/xml')\n response = client.put('http://example.org', TestData())\n self.assert_(response.getheader('Echo-Host') == 'example.org:None')\n self.assert_(response.getheader('Echo-Uri') == '/')\n self.assert_(response.getheader('Echo-Method') == 'PUT')\n self.assert_(response.getheader('Content-Length') == str(len(body_text)))\n self.assert_(response.getheader('Content-Type') == 'application/xml')\n response = client.put(uri='http://example.org', data=TestData())\n self.assert_(response.getheader('Content-Length') == str(len(body_text)))\n self.assert_(response.getheader('Content-Type') == 'application/xml')\n", "method_code": " def put(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs):\n \"\"\"Sends data using the PUT method, returns an HTTP response.\"\"\"\n return self.request(method='PUT', uri=uri, auth_token=auth_token, http_request=http_request, data=data, **kwargs)\n ", "context": "class AtomPubClient(object):\n def put(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): ...\n def __init__(self, http_client=None, host=None, auth_token=None, source=None, xoauth_requestor_id=None, **kwargs): ...\n def request(self, method=None, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def get(self, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def post(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): ...\n def delete(self, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def modify_request(self, http_request): ...\n\n self.http_client = http_client or atom.http_core.ProxiedHttpClient()\n self.xoauth_requestor_id = xoauth_requestor_id\n self.source = source\n\n host = None\n auth_token = None\n ssl = False\n xoauth_requestor_id = None\n Request = request\n Get = get\n Post = post\n Put = put\n Delete = delete\n ModifyRequest = modify_request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_put", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002189.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/client.py", "focal_class": null, "focal_method": "delete", "tests": "import unittest\n\nclass Test_delete(unittest.TestCase):\n def test_delete(self):\n client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient(), source='my new app')\n response = client.Delete('http://example.com/simple')\n self.assertEqual(response.getheader('Echo-Host'), 'example.com:None')\n self.assertEqual(response.getheader('Echo-Uri'), '/simple')\n self.assertEqual(response.getheader('Echo-Method'), 'DELETE')\n response = client.delete(uri='http://example.com/d')\n self.assertEqual(response.getheader('Echo-Uri'), '/d')\n self.assertEqual(response.getheader('Echo-Method'), 'DELETE')\n self.assert_(response.getheader('User-Agent').startswith('my new app gdata-py/'))\n", "method_code": " def delete(self, uri=None, auth_token=None, http_request=None, **kwargs):\n \"\"\"Performs a request using the DELETE method, returns an HTTP response.\"\"\"\n return self.request(method='DELETE', uri=uri, auth_token=auth_token, http_request=http_request, **kwargs)\n ", "context": "class AtomPubClient(object):\n def delete(self, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def __init__(self, http_client=None, host=None, auth_token=None, source=None, xoauth_requestor_id=None, **kwargs): ...\n def request(self, method=None, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def get(self, uri=None, auth_token=None, http_request=None, **kwargs): ...\n def post(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): ...\n def put(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): ...\n def modify_request(self, http_request): ...\n\n self.http_client = http_client or atom.http_core.ProxiedHttpClient()\n self.xoauth_requestor_id = xoauth_requestor_id\n self.source = source\n\n host = None\n auth_token = None\n ssl = False\n xoauth_requestor_id = None\n Request = request\n Get = get\n Post = post\n Put = put\n Delete = delete\n ModifyRequest = modify_request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_delete", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002190.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/core.py", "focal_class": null, "focal_method": "get_elements", "tests": "import unittest\n\nclass Test_get_elements(unittest.TestCase):\n def testGetElements(self):\n e = Example()\n e.child = Child()\n e.child.text = 'child text'\n e.foos.append(Foo())\n e.foos[0].text = 'foo1'\n e.foos.append(Foo())\n e.foos[1].text = 'foo2'\n e._other_elements.append(atom.core.XmlElement())\n e._other_elements[0]._qname = 'bar'\n e._other_elements[0].text = 'other1'\n e._other_elements.append(atom.core.XmlElement())\n e._other_elements[1]._qname = 'child'\n e._other_elements[1].text = 'other2'\n self.contains_expected_elements(e.get_elements(), ['foo1', 'foo2', 'child text', 'other1', 'other2'])\n self.contains_expected_elements(e.get_elements('child'), ['child text', 'other2'])\n self.contains_expected_elements(e.get_elements('child', 'http://example.com/1'), ['child text'])\n self.contains_expected_elements(e.get_elements('child', 'http://example.com/2'), [])\n self.contains_expected_elements(e.get_elements('child', 'http://example.com/2', 2), ['child text'])\n self.contains_expected_elements(e.get_elements('child', 'http://example.com/1', 2), [])\n self.contains_expected_elements(e.get_elements('child', 'http://example.com/2', 3), ['child text'])\n self.contains_expected_elements(e.get_elements('bar'), ['other1'])\n self.contains_expected_elements(e.get_elements('bar', version=2), ['other1'])\n self.contains_expected_elements(e.get_elements('bar', version=3), ['other1'])\n", "method_code": " def get_elements(self, tag=None, namespace=None, version=1):\n \"\"\"Find all sub elements which match the tag and namespace.\n \n To find all elements in this object, call get_elements with the tag and\n namespace both set to None (the default). This method searches through\n the object's members and the elements stored in _other_elements which\n did not match any of the XML parsing rules for this class.\n \n Args:\n tag: str\n namespace: str\n version: int Specifies the version of the XML rules to be used when\n searching for matching elements.\n \n Returns:\n A list of the matching XmlElements.\n \"\"\"\n matches = []\n ignored1, elements, ignored2 = self.__class__._get_rules(version)\n if elements:\n for qname, element_def in elements.iteritems():\n member = getattr(self, element_def[0])\n if member:\n if _qname_matches(tag, namespace, qname):\n if element_def[2]:\n matches.extend(member)\n else:\n matches.append(member)\n for element in self._other_elements:\n if _qname_matches(tag, namespace, element._qname):\n matches.append(element)\n return matches\n ", "context": "class XmlElement(object):\n def get_elements(self, tag=None, namespace=None, version=1): ...\n def __init__(self, text=None, *args, **kwargs): ...\n def _list_xml_members(cls): ...\n def _get_rules(cls, version): ...\n def get_attributes(self, tag=None, namespace=None, version=1): ...\n def _harvest_tree(self, tree, version=1): ...\n def _to_tree(self, version=1, encoding=None): ...\n def _attach_members(self, tree, version=1, encoding=None): ...\n def to_string(self, version=1, encoding=None, pretty_print=None): ...\n def __str__(self): ...\n def _become_child(self, tree, version=1): ...\n def __get_extension_elements(self): ...\n def __set_extension_elements(self, elements): ...\n def __get_extension_attributes(self): ...\n def __set_extension_attributes(self, attributes): ...\n def _get_tag(self, version=1): ...\n def _get_namespace(self, version=1): ...\n def _set_tag(self, tag): ...\n def _set_namespace(self, namespace): ...\n\n self._other_elements = []\n self._other_attributes = {}\n\n _qname = None\n _other_elements = None\n _other_attributes = None\n _rule_set = None\n _members = None\n text = None\n _list_xml_members = classmethod(_list_xml_members)\n _get_rules = classmethod(_get_rules)\n GetElements = get_elements\n FindExtensions = get_elements\n FindChildren = get_elements\n GetAttributes = get_attributes\n ToString = to_string\n extension_elements = property(__get_extension_elements, __set_extension_elements, 'Provides backwards compatibility for v1 atom.AtomBase classes.')\n extension_attributes = property(__get_extension_attributes, __set_extension_attributes, 'Provides backwards compatibility for v1 atom.AtomBase classes.')\n tag = property(_get_tag, _set_tag, 'Provides backwards compatibility for v1 atom.AtomBase classes.')\n namespace = property(_get_namespace, _set_namespace, 'Provides backwards compatibility for v1 atom.AtomBase classes.')\n children = extension_elements\n attributes = extension_attributes\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetElements", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002191.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/http_core.py", "focal_class": null, "focal_method": "parse_uri", "tests": "import unittest\n\nclass Test_parse_uri(unittest.TestCase):\n def test_parse_uri(self):\n uri = atom.http_core.parse_uri('http://www.google.com/test?q=foo&z=bar')\n self.assert_(uri.scheme == 'http')\n self.assert_(uri.host == 'www.google.com')\n self.assert_(uri.port is None)\n self.assert_(uri.path == '/test')\n self.assert_(uri.query == {'z': 'bar', 'q': 'foo'})\n\n def test_static_parse_uri(self):\n uri = atom.http_core.Uri.parse_uri('http://test.com/?token=foo&x=1')\n self.assertEqual(uri.scheme, 'http')\n self.assertEqual(uri.host, 'test.com')\n self.assert_(uri.port is None)\n self.assertEqual(uri.query, {'token': 'foo', 'x': '1'})\n", "method_code": " def parse_uri(uri_string):\n \"\"\"Creates a Uri object which corresponds to the URI string.\n \n This method can accept partial URIs, but it will leave missing\n members of the Uri unset.\n \"\"\"\n parts = urlparse.urlparse(uri_string)\n uri = Uri()\n if parts[0]:\n uri.scheme = parts[0]\n if parts[1]:\n host_parts = parts[1].split(':')\n if host_parts[0]:\n uri.host = host_parts[0]\n if len(host_parts) > 1:\n uri.port = int(host_parts[1])\n if parts[2]:\n uri.path = parts[2]\n if parts[4]:\n param_pairs = parts[4].split('&')\n for pair in param_pairs:\n pair_parts = pair.split('=')\n if len(pair_parts) > 1:\n uri.query[urllib.unquote_plus(pair_parts[0])] = urllib.unquote_plus(pair_parts[1])\n elif len(pair_parts) == 1:\n uri.query[urllib.unquote_plus(pair_parts[0])] = None\n return uri\n ", "context": "class Uri(object):\n def parse_uri(uri_string): ...\n def __init__(self, scheme=None, host=None, port=None, path=None, query=None): ...\n def _get_query_string(self): ...\n def _get_relative_path(self): ...\n def _to_string(self): ...\n def __str__(self): ...\n def modify_request(self, http_request=None): ...\n\n self.query = query or {}\n\n scheme = None\n host = None\n port = None\n path = None\n ModifyRequest = modify_request\n parse_uri = staticmethod(parse_uri)\n ParseUri = parse_uri\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_parse_uri", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002192.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/http_core.py", "focal_class": null, "focal_method": "modify_request", "tests": "import unittest\n\nclass Test_modify_request(unittest.TestCase):\n def test_modify_request_no_request(self):\n uri = atom.http_core.parse_uri('http://www.google.com/test?q=foo&z=bar')\n request = uri.modify_request()\n self.assert_(request.uri.scheme == 'http')\n self.assert_(request.uri.host == 'www.google.com')\n self.assert_(request.uri.port is None)\n self.assert_(request.uri.path.startswith('/test'))\n self.assertEqual(request.uri.query, {'z': 'bar', 'q': 'foo'})\n self.assert_(request.method is None)\n self.assert_(request.headers == {})\n self.assert_(request._body_parts == [])\n", "method_code": " def modify_request(self, http_request=None):\n \"\"\"Sets HTTP request components based on the URI.\"\"\"\n if http_request is None:\n http_request = HttpRequest()\n if http_request.uri is None:\n http_request.uri = Uri()\n if self.scheme:\n http_request.uri.scheme = self.scheme\n if self.port:\n http_request.uri.port = self.port\n if self.host:\n http_request.uri.host = self.host\n if self.path:\n http_request.uri.path = self.path\n if self.query:\n http_request.uri.query = self.query.copy()\n return http_request\n ", "context": "class Uri(object):\n def modify_request(self, http_request=None): ...\n def __init__(self, scheme=None, host=None, port=None, path=None, query=None): ...\n def _get_query_string(self): ...\n def _get_relative_path(self): ...\n def _to_string(self): ...\n def __str__(self): ...\n def parse_uri(uri_string): ...\n\n self.query = query or {}\n\n scheme = None\n host = None\n port = None\n path = None\n ModifyRequest = modify_request\n parse_uri = staticmethod(parse_uri)\n ParseUri = parse_uri\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_modify_request_no_request", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002193.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/http_core.py", "focal_class": null, "focal_method": "_to_string", "tests": "import unittest\n\nclass Test_to_string(unittest.TestCase):\n def test_to_string(self):\n uri = atom.http_core.Uri(host='www.google.com', query={'q': 'sippycode'})\n uri_string = uri._to_string()\n self.assert_(uri_string == 'http://www.google.com/?q=sippycode')\n", "method_code": " def _to_string(self):\n if self.scheme is None and self.port == 443:\n scheme = 'https'\n elif self.scheme is None:\n scheme = 'http'\n else:\n scheme = self.scheme\n if self.path is None:\n path = '/'\n else:\n path = self.path\n if self.port is None:\n return '%s://%s%s' % (scheme, self.host, self._get_relative_path())\n else:\n return '%s://%s:%s%s' % (scheme, self.host, str(self.port), self._get_relative_path())\n ", "context": "class Uri(object):\n def _to_string(self): ...\n def __init__(self, scheme=None, host=None, port=None, path=None, query=None): ...\n def _get_query_string(self): ...\n def _get_relative_path(self): ...\n def __str__(self): ...\n def modify_request(self, http_request=None): ...\n def parse_uri(uri_string): ...\n\n self.query = query or {}\n\n scheme = None\n host = None\n port = None\n path = None\n ModifyRequest = modify_request\n parse_uri = staticmethod(parse_uri)\n ParseUri = parse_uri\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_to_string", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002194.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/http_core.py", "focal_class": "atom.http_core.HttpRequest", "focal_method": "add_body_part", "tests": "import unittest\n\nclass Test_atom_http_core_HttpRequest_add_body_part(unittest.TestCase):\n def test_request_with_one_body_part(self):\n request = atom.http_core.HttpRequest()\n self.assert_(len(request._body_parts) == 0)\n self.assert_('Content-Length' not in request.headers)\n self.assert_(not 'Content-Type' in request.headers)\n self.assert_(not 'Content-Length' in request.headers)\n request.add_body_part('this is a test', 'text/plain')\n self.assert_(len(request._body_parts) == 1)\n self.assert_(request.headers['Content-Type'] == 'text/plain')\n self.assert_(request._body_parts[0] == 'this is a test')\n self.assert_(request.headers['Content-Length'] == str(len('this is a test')))\n", "method_code": " def add_body_part(self, data, mime_type, size=None):\n \"\"\"Adds data to the HTTP request body.\n \n If more than one part is added, this is assumed to be a mime-multipart\n request. This method is designed to create MIME 1.0 requests as specified\n in RFC 1341.\n \n Args:\n data: str or a file-like object containing a part of the request body.\n mime_type: str The MIME type describing the data\n size: int Required if the data is a file like object. If the data is a\n string, the size is calculated so this parameter is ignored.\n \"\"\"\n if isinstance(data, str):\n size = len(data)\n if size is None:\n raise UnknownSize('Each part of the body must have a known size.')\n if 'Content-Length' in self.headers:\n content_length = int(self.headers['Content-Length'])\n else:\n content_length = 0\n if len(self._body_parts) == 0:\n self.headers['Content-Type'] = mime_type\n content_length = size\n self._body_parts.append(data)\n elif len(self._body_parts) == 1:\n self._body_parts.insert(0, 'Media multipart posting')\n boundary_string = '\\r\\n--%s\\r\\n' % (MIME_BOUNDARY,)\n content_length += len(boundary_string) + size\n self._body_parts.insert(1, boundary_string)\n content_length += len('Media multipart posting')\n original_type_string = 'Content-Type: %s\\r\\n\\r\\n' % (self.headers['Content-Type'],)\n self._body_parts.insert(2, original_type_string)\n content_length += len(original_type_string)\n boundary_string = '\\r\\n--%s\\r\\n' % (MIME_BOUNDARY,)\n self._body_parts.append(boundary_string)\n content_length += len(boundary_string)\n self.headers['Content-Type'] = 'multipart/related; boundary=\"%s\"' % (MIME_BOUNDARY,)\n self.headers['MIME-version'] = '1.0'\n type_string = 'Content-Type: %s\\r\\n\\r\\n' % mime_type\n self._body_parts.append(type_string)\n content_length += len(type_string)\n self._body_parts.append(data)\n ending_boundary_string = '\\r\\n--%s--' % (MIME_BOUNDARY,)\n self._body_parts.append(ending_boundary_string)\n content_length += len(ending_boundary_string)\n else:\n boundary_string = '\\r\\n--%s\\r\\n' % (MIME_BOUNDARY,)\n self._body_parts.insert(-1, boundary_string)\n content_length += len(boundary_string) + size\n type_string = 'Content-Type: %s\\r\\n\\r\\n' % mime_type\n self._body_parts.insert(-1, type_string)\n content_length += len(type_string)\n self._body_parts.insert(-1, data)\n self.headers['Content-Length'] = str(content_length)\n ", "context": "class HttpRequest(object):\n def add_body_part(self, data, mime_type, size=None): ...\n def __init__(self, uri=None, method=None, headers=None): ...\n def add_form_inputs(self, form_data, mime_type='application/x-www-form-urlencoded'): ...\n def _copy(self): ...\n def _dump(self): ...\n\n self.headers = headers or {}\n self._body_parts = []\n self.uri = uri or Uri()\n\n method = None\n uri = None\n AddBodyPart = add_body_part\n AddFormInputs = add_form_inputs\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_request_with_one_body_part", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002195.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/http_core.py", "focal_class": "atom.http_core.HttpRequest", "focal_method": "_copy", "tests": "import unittest\n\nclass Test_atom_http_core_HttpRequest_copy(unittest.TestCase):\n def test_copy(self):\n request = atom.http_core.HttpRequest(uri=atom.http_core.Uri(scheme='https', host='www.google.com'), method='POST', headers={'test': '1', 'ok': 'yes'})\n request.add_body_part('body1', 'text/plain')\n request.add_body_part('body2', 'text/html')\n copied = request._copy()\n self.assert_(request.uri.scheme == copied.uri.scheme)\n self.assert_(request.uri.host == copied.uri.host)\n self.assert_(request.method == copied.method)\n self.assert_(request.uri.path == copied.uri.path)\n self.assert_(request.headers == copied.headers)\n self.assert_(request._body_parts == copied._body_parts)\n copied.headers['test'] = '2'\n copied._body_parts[1] = 'body3'\n self.assert_(request.headers != copied.headers)\n self.assert_(request._body_parts != copied._body_parts)\n", "method_code": " def _copy(self):\n \"\"\"Creates a deep copy of this request.\"\"\"\n copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port, self.uri.path, self.uri.query.copy())\n new_request = HttpRequest(uri=copied_uri, method=self.method, headers=self.headers.copy())\n new_request._body_parts = self._body_parts[:]\n return new_request\n ", "context": "class HttpRequest(object):\n def _copy(self): ...\n def __init__(self, uri=None, method=None, headers=None): ...\n def add_body_part(self, data, mime_type, size=None): ...\n def add_form_inputs(self, form_data, mime_type='application/x-www-form-urlencoded'): ...\n def _dump(self): ...\n\n self.headers = headers or {}\n self._body_parts = []\n self.uri = uri or Uri()\n\n method = None\n uri = None\n AddBodyPart = add_body_part\n AddFormInputs = add_form_inputs\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_copy", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002196.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/mock_http_core.py", "focal_class": null, "focal_method": "read", "tests": "import unittest\n\nclass Test_read(unittest.TestCase):\n def test_echo_response(self):\n client = atom.mock_http_core.EchoHttpClient()\n request = atom.http_core.HttpRequest(method='POST', uri=atom.http_core.Uri(host='www.jeffscudder.com', path='/'))\n request.add_body_part('hello world!', 'text/plain')\n response = client.request(request)\n self.assert_(response.getheader('Echo-Host') == 'www.jeffscudder.com:None')\n self.assert_(response.getheader('Echo-Uri') == '/')\n self.assert_(response.getheader('Echo-Scheme') is None)\n self.assert_(response.getheader('Echo-Method') == 'POST')\n self.assert_(response.getheader('Content-Length') == str(len('hello world!')))\n self.assert_(response.getheader('Content-Type') == 'text/plain')\n self.assert_(response.read() == 'hello world!')\n request = atom.http_core.HttpRequest(method='POST', uri=atom.http_core.Uri(host='www.jeffscudder.com', path=None))\n response = client.request(request)\n self.assert_(response.getheader('Echo-Host') == 'www.jeffscudder.com:None')\n self.assert_(response.getheader('Echo-Method') == 'POST')\n self.assert_(response.getheader('Echo-Uri') == '/')\n request = atom.http_core.HttpRequest(method='POST', uri=atom.http_core.Uri(scheme='https', host='www.jeffscudder.com', port=8080, path='/multipart', query={'test': 'true', 'happy': 'yes'}), headers={'Authorization': 'Test xyzzy', 'Testing': 'True'})\n request.add_body_part('start', 'text/plain')\n request.add_body_part(StringIO.StringIO('hi'), 'text/html', len('hi'))\n request.add_body_part('alert(\"Greetings!\")', 'text/javascript')\n response = client.request(request)\n self.assert_(response.getheader('Echo-Host') == 'www.jeffscudder.com:8080')\n self.assert_(response.getheader('Echo-Uri') == '/multipart?test=true&happy=yes')\n self.assert_(response.getheader('Echo-Scheme') == 'https')\n self.assert_(response.getheader('Echo-Method') == 'POST')\n self.assert_(response.getheader('Content-Type') == 'multipart/related; boundary=\"%s\"' % (atom.http_core.MIME_BOUNDARY,))\n expected_body = 'Media multipart posting\\r\\n--%s\\r\\nContent-Type: text/plain\\r\\n\\r\\nstart\\r\\n--%s\\r\\nContent-Type: text/html\\r\\n\\r\\nhi\\r\\n--%s\\r\\nContent-Type: text/javascript\\r\\n\\r\\nalert(\"Greetings!\")\\r\\n--%s--' % (atom.http_core.MIME_BOUNDARY, atom.http_core.MIME_BOUNDARY, atom.http_core.MIME_BOUNDARY, atom.http_core.MIME_BOUNDARY)\n self.assert_(response.read() == expected_body)\n self.assert_(response.getheader('Content-Length') == str(len(expected_body)))\n", "method_code": " def read(self):\n return self._body\n ", "context": "class MockHttpResponse(atom.http_core.HttpResponse):\n def read(self): ...\n def __init__(self, status=None, reason=None, headers=None, body=None): ...\n\n self._headers = headers or {}\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_echo_response", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002197.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/mock_http_core.py", "focal_class": null, "focal_method": "_load_recordings", "tests": "import unittest\n\nclass Test_load_recordings(unittest.TestCase):\n def test_save_and_load_recordings(self):\n request = atom.http_core.HttpRequest(method='GET')\n atom.http_core.parse_uri('http://www.google.com/').modify_request(request)\n self.client.add_response(request, 200, 'OK', body='Testing')\n response = self.client.request(request)\n self.client._save_recordings('test_save_and_load_recordings')\n self.client._recordings = []\n try:\n response = self.client.request(request)\n self.fail('There should be no recording for this request.')\n except atom.mock_http_core.NoRecordingFound:\n pass\n self.client._load_recordings('test_save_and_load_recordings')\n response = self.client.request(request)\n self.assert_(response.status == 200)\n self.assert_(response.reason == 'OK')\n self.assert_(response.read() == 'Testing')\n", "method_code": " def _load_recordings(self, filename):\n recording_file = open(os.path.join(tempfile.gettempdir(), filename), 'rb')\n self._recordings = pickle.load(recording_file)\n recording_file.close()\n ", "context": "class MockHttpClient(object):\n def _load_recordings(self, filename): ...\n def __init__(self, recordings=None, real_client=None): ...\n def add_response(self, http_request, status, reason, headers=None, body=None): ...\n def request(self, http_request): ...\n def _save_recordings(self, filename): ...\n def _delete_recordings(self, filename): ...\n def _load_or_use_client(self, filename, http_client): ...\n def use_cached_session(self, name=None, real_http_client=None): ...\n def close_session(self): ...\n def delete_session(self, name=None): ...\n def get_cache_file_name(self): ...\n def _dump(self): ...\n\n self._recordings = recordings or []\n\n debug = None\n real_client = None\n last_request_was_live = False\n cache_name_prefix = 'gdata_live_test'\n cache_case_name = ''\n cache_test_name = ''\n AddResponse = add_response\n Request = request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_save_and_load_recordings", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002198.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/mock_http_core.py", "focal_class": null, "focal_method": "_save_recordings", "tests": "import unittest\n\nclass Test_save_recordings(unittest.TestCase):\n def test_use_recordings(self):\n request = atom.http_core.HttpRequest(method='GET')\n atom.http_core.parse_uri('http://www.google.com/').modify_request(request)\n self.client._load_or_use_client('test_use_recordings', atom.http_core.HttpClient())\n response = self.client.request(request)\n if self.client.real_client:\n self.client._save_recordings('test_use_recordings')\n self.assert_(response.status in (200, 302))\n self.assert_(response.reason in ('OK', 'Found'))\n self.assert_(response.getheader('server') == 'gws')\n body = response.read()\n self.assert_(body.startswith('') or body.startswith(''))\n", "method_code": " def _save_recordings(self, filename):\n recording_file = open(os.path.join(tempfile.gettempdir(), filename), 'wb')\n pickle.dump(self._recordings, recording_file)\n recording_file.close()\n ", "context": "class MockHttpClient(object):\n def _save_recordings(self, filename): ...\n def __init__(self, recordings=None, real_client=None): ...\n def add_response(self, http_request, status, reason, headers=None, body=None): ...\n def request(self, http_request): ...\n def _load_recordings(self, filename): ...\n def _delete_recordings(self, filename): ...\n def _load_or_use_client(self, filename, http_client): ...\n def use_cached_session(self, name=None, real_http_client=None): ...\n def close_session(self): ...\n def delete_session(self, name=None): ...\n def get_cache_file_name(self): ...\n def _dump(self): ...\n\n self._recordings = recordings or []\n\n debug = None\n real_client = None\n last_request_was_live = False\n cache_name_prefix = 'gdata_live_test'\n cache_case_name = ''\n cache_test_name = ''\n AddResponse = add_response\n Request = request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_use_recordings", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002199.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/mock_http_core.py", "focal_class": null, "focal_method": "_match_request", "tests": "import unittest\n\nclass Test_match_request(unittest.TestCase):\n def test_match_request(self):\n x = atom.http_core.HttpRequest('http://example.com/', 'GET')\n y = atom.http_core.HttpRequest('http://example.com/', 'GET')\n self.assert_(atom.mock_http_core._match_request(x, y))\n y = atom.http_core.HttpRequest('http://example.com/', 'POST')\n self.assert_(not atom.mock_http_core._match_request(x, y))\n y = atom.http_core.HttpRequest('http://example.com/1', 'GET')\n self.assert_(not atom.mock_http_core._match_request(x, y))\n y = atom.http_core.HttpRequest('http://example.com/?gsessionid=1', 'GET')\n self.assert_(not atom.mock_http_core._match_request(x, y))\n y = atom.http_core.HttpRequest('http://example.com/?start_index=1', 'GET')\n self.assert_(atom.mock_http_core._match_request(x, y))\n x = atom.http_core.HttpRequest('http://example.com/?gsessionid=1', 'GET')\n y = atom.http_core.HttpRequest('http://example.com/?gsessionid=1', 'GET')\n self.assert_(atom.mock_http_core._match_request(x, y))\n y = atom.http_core.HttpRequest('http://example.com/?gsessionid=2', 'GET')\n self.assert_(not atom.mock_http_core._match_request(x, y))\n y = atom.http_core.HttpRequest('http://example.com/', 'GET')\n self.assert_(not atom.mock_http_core._match_request(x, y))\n", "method_code": "def _match_request(http_request, stored_request):\n \"\"\"Determines whether a request is similar enough to a stored request\n to cause the stored response to be returned.\"\"\"\n if http_request.uri.host is not None and http_request.uri.host != stored_request.uri.host:\n return False\n elif http_request.uri.path != stored_request.uri.path:\n return False\n elif http_request.method != stored_request.method:\n return False\n elif 'gsessionid' in http_request.uri.query or 'gsessionid' in stored_request.uri.query:\n if 'gsessionid' not in stored_request.uri.query:\n return False\n elif 'gsessionid' not in http_request.uri.query:\n return False\n elif http_request.uri.query['gsessionid'] != stored_request.uri.query['gsessionid']:\n return False\n return True", "context": "def _match_request(http_request, stored_request): ...\ndef _match_request(http_request, stored_request): ...\ndef _scrub_request(http_request): ...\ndef _scrub_response(http_response): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_match_request", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002200.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/mock_http_core.py", "focal_class": null, "focal_method": "use_cached_session", "tests": "import unittest\n\nclass Test_use_cached_session(unittest.TestCase):\n def test_use_named_sessions(self):\n self.client._delete_recordings('mock_http_test.test_use_named_sessions')\n self.client.use_cached_session('mock_http_test.test_use_named_sessions', atom.mock_http_core.EchoHttpClient())\n request = atom.http_core.HttpRequest('http://example.com', 'GET')\n response = self.client.request(request)\n self.assertEqual(response.getheader('Echo-Method'), 'GET')\n self.assertEqual(response.getheader('Echo-Host'), 'example.com:None')\n self.assertEqual(response.getheader('Cache-Marker'), None)\n self.assert_('Cache-Marker' not in self.client._recordings[0][1]._headers)\n self.client._recordings[0][1]._headers['Cache-Marker'] = '1'\n self.assert_('Cache-Marker' in self.client._recordings[0][1]._headers)\n self.client.close_session()\n client = atom.mock_http_core.MockHttpClient()\n client.use_cached_session('mock_http_test.test_use_named_sessions', atom.mock_http_core.EchoHttpClient())\n response = client.request(request)\n self.assertEqual(response.getheader('Echo-Method'), 'GET')\n self.assertEqual(response.getheader('Echo-Host'), 'example.com:None')\n self.assertEqual(response.getheader('Cache-Marker'), '1')\n", "method_code": " def use_cached_session(self, name=None, real_http_client=None):\n \"\"\"Attempts to load recordings from a previous live request.\n \n If a temp file with the recordings exists, then it is used to fulfill\n requests. If the file does not exist, then a real client is used to\n actually make the desired HTTP requests. Requests and responses are\n recorded and will be written to the desired temprary cache file when\n close_session is called.\n \n Args:\n name: str (optional) The file name of session file to be used. The file\n is loaded from the temporary directory of this machine. If no name\n is passed in, a default name will be constructed using the\n cache_name_prefix, cache_case_name, and cache_test_name of this\n object.\n real_http_client: atom.http_core.HttpClient the real client to be used\n if the cached recordings are not found. If the default\n value is used, this will be an\n atom.http_core.HttpClient.\n \"\"\"\n if real_http_client is None:\n real_http_client = atom.http_core.HttpClient()\n if name is None:\n self._recordings_cache_name = self.get_cache_file_name()\n else:\n self._recordings_cache_name = name\n self._load_or_use_client(self._recordings_cache_name, real_http_client)\n ", "context": "class MockHttpClient(object):\n def use_cached_session(self, name=None, real_http_client=None): ...\n def __init__(self, recordings=None, real_client=None): ...\n def add_response(self, http_request, status, reason, headers=None, body=None): ...\n def request(self, http_request): ...\n def _save_recordings(self, filename): ...\n def _load_recordings(self, filename): ...\n def _delete_recordings(self, filename): ...\n def _load_or_use_client(self, filename, http_client): ...\n def close_session(self): ...\n def delete_session(self, name=None): ...\n def get_cache_file_name(self): ...\n def _dump(self): ...\n\n self._recordings = recordings or []\n\n debug = None\n real_client = None\n last_request_was_live = False\n cache_name_prefix = 'gdata_live_test'\n cache_case_name = ''\n cache_test_name = ''\n AddResponse = add_response\n Request = request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_use_named_sessions", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002201.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/mock_service.py", "focal_class": null, "focal_method": "IsMatch", "tests": "import unittest\n\nclass Test_IsMatch(unittest.TestCase):\n def testIsMatch(self):\n matching_request = atom.mock_service.MockRequest('GET', 'http://www.google.com', extra_headers={'Header1': 'a', 'Header2': 'b', 'Header3': 'c'})\n bad_url = atom.mock_service.MockRequest('GET', 'http://example.com', extra_headers={'Header1': 'a', 'Header2': 'b', 'Header3': 'c'})\n bad_header = atom.mock_service.MockRequest('GET', 'http://www.google.com', extra_headers={'Header1': 'a', 'Header2': '1', 'Header3': 'c'})\n bad_verb = atom.mock_service.MockRequest('POST', 'http://www.google.com', data='post data', extra_headers={'Header1': 'a', 'Header2': 'b'})\n self.assertEquals(self.request_thumbprint.IsMatch(matching_request), True)\n self.assertEquals(self.request_thumbprint.IsMatch(bad_url), False)\n self.assertEquals(self.request_thumbprint.IsMatch(bad_header), True)\n self.assertEquals(self.request_thumbprint.IsMatch(bad_verb), False)\n", "method_code": " def IsMatch(self, other_request):\n \"\"\"Check to see if the other_request is equivalent to this request.\n \n Used to determine if a recording matches an incoming request so that a\n recorded response should be sent to the client.\n \n The matching is not exact, only the operation and URL are examined \n currently.\n \n Args:\n other_request: MockRequest The request which we want to check this\n (self) MockRequest against to see if they are equivalent.\n \"\"\"\n return self.operation == other_request.operation and self.uri == other_request.uri\n ", "context": "class MockRequest(object):\n def IsMatch(self, other_request): ...\n def __init__(self, operation, uri, host=None, ssl=False, port=None, data=None, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): ...\n def ConcealSecrets(self, conceal_func): ...\n\n self.operation = operation\n self.uri = _ConstructFullUrlBase(uri, host=host, ssl=ssl)\n self.data = data\n self.extra_headers = extra_headers\n self.url_params = url_params or {}\n self.escape_params = escape_params\n self.content_type = content_type\n", "repository": "bigsnarfdude/webscraping", "test_name": "testIsMatch", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002202.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/service.py", "focal_class": null, "focal_method": "UseBasicAuth", "tests": "import unittest\n\nclass Test_UseBasicAuth(unittest.TestCase):\n def testSetBasicAuth(self):\n client = atom.service.AtomService()\n client.UseBasicAuth('foo', 'bar')\n token = client.token_store.find_token('http://')\n self.assert_(isinstance(token, atom.service.BasicAuthToken))\n self.assertEquals(token.auth_header, 'Basic Zm9vOmJhcg==')\n client.UseBasicAuth('', '')\n token = client.token_store.find_token('http://')\n self.assert_(isinstance(token, atom.service.BasicAuthToken))\n self.assertEquals(token.auth_header, 'Basic Og==')\n", "method_code": "def UseBasicAuth(service, username, password, for_proxy=False):\n \"\"\"Sets an Authenticaiton: Basic HTTP header containing plaintext.\n\n Deprecated, use AtomService.use_basic_auth insread.\n \n The username and password are base64 encoded and added to an HTTP header\n which will be included in each request. Note that your username and \n password are sent in plaintext. The auth header is added to the \n additional_headers dictionary in the service object.\n\n Args:\n service: atom.AtomService or a subclass which has an \n additional_headers dict as a member.\n username: str\n password: str\n \"\"\"\n deprecation('calling deprecated function UseBasicAuth')\n base_64_string = base64.encodestring('%s:%s' % (username, password))\n base_64_string = base_64_string.strip()\n if for_proxy:\n header_name = 'Proxy-Authorization'\n else:\n header_name = 'Authorization'\n service.additional_headers[header_name] = 'Basic %s' % (base_64_string,)", "context": "def UseBasicAuth(service, username, password, for_proxy=False): ...\ndef PrepareConnection(service, full_uri): ...\ndef UseBasicAuth(service, username, password, for_proxy=False): ...\ndef ProcessUrl(service, url, for_proxy=False): ...\ndef DictionaryToParamList(url_parameters, escape_params=True): ...\ndef BuildUri(uri, url_params=None, escape_params=True): ...\ndef HttpRequest(service, operation, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): ...\ndef __SendDataPart(data, connection): ...\ndef CalculateDataLength(data): ...\ndef deprecation(message): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testSetBasicAuth", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002203.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/url.py", "focal_class": null, "focal_method": "to_string", "tests": "import unittest\n\nclass Test_to_string(unittest.TestCase):\n def testUrlToString(self):\n url = atom.url.Url(port=80)\n url.host = 'example.com'\n self.assert_(str(url), '//example.com:80')\n url = atom.url.Url(protocol='http', host='example.com', path='/feed')\n url.params['has spaces'] = 'sneaky=values?&!'\n self.assert_(url.to_string() == 'http://example.com/feed?has+spaces=sneaky%3Dvalues%3F%26%21')\n", "method_code": " def to_string(self):\n url_parts = ['', '', '', '', '', '']\n if self.protocol:\n url_parts[0] = self.protocol\n if self.host:\n if self.port:\n url_parts[1] = ':'.join((self.host, str(self.port)))\n else:\n url_parts[1] = self.host\n if self.path:\n url_parts[2] = self.path\n if self.params:\n url_parts[4] = self.get_param_string()\n return urlparse.urlunparse(url_parts)\n ", "context": "class Url(object):\n def to_string(self): ...\n def __init__(self, protocol=None, host=None, port=None, path=None, params=None): ...\n def get_param_string(self): ...\n def get_request_uri(self): ...\n def __cmp__(self, other): ...\n def __str__(self): ...\n\n self.protocol = protocol\n self.host = host\n self.port = port\n self.path = path\n self.params = params or {}\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUrlToString", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002204.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/atom/url.py", "focal_class": null, "focal_method": "get_request_uri", "tests": "import unittest\n\nclass Test_get_request_uri(unittest.TestCase):\n def testGetRequestUri(self):\n url = atom.url.Url(protocol='http', host='example.com', path='/feed')\n url.params['has spaces'] = 'sneaky=values?&!'\n self.assert_(url.get_request_uri() == '/feed?has+spaces=sneaky%3Dvalues%3F%26%21')\n self.assert_(url.get_param_string() == 'has+spaces=sneaky%3Dvalues%3F%26%21')\n", "method_code": " def get_request_uri(self):\n \"\"\"Returns the path with the parameters escaped and appended.\"\"\"\n param_string = self.get_param_string()\n if param_string:\n return '?'.join([self.path, param_string])\n else:\n return self.path\n ", "context": "class Url(object):\n def get_request_uri(self): ...\n def __init__(self, protocol=None, host=None, port=None, path=None, params=None): ...\n def to_string(self): ...\n def get_param_string(self): ...\n def __cmp__(self, other): ...\n def __str__(self): ...\n\n self.protocol = protocol\n self.host = host\n self.port = port\n self.path = path\n self.params = params or {}\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetRequestUri", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002205.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "GenerateClientLoginAuthToken", "tests": "import unittest\n\nclass Test_GenerateClientLoginAuthToken(unittest.TestCase):\n def testGenerateClientLoginAuthToken(self):\n http_body = 'SID=DQAAAGgA7Zg8CTN\\r\\nLSID=DQAAAGsAlk8BBbG\\r\\nAuth=DQAAAGgAdk3fA5N'\n self.assert_(gdata.auth.GenerateClientLoginAuthToken(http_body) == 'GoogleLogin auth=DQAAAGgAdk3fA5N')\n", "method_code": "def GenerateClientLoginAuthToken(http_body):\n \"\"\"Returns the token value to use in Authorization headers.\n\n Reads the token from the server's response to a Client Login request and\n creates header value to use in requests.\n\n Args:\n http_body: str The body of the server's HTTP response to a Client Login\n request\n \n Returns:\n The value half of an Authorization header.\n \"\"\"\n token = get_client_login_token(http_body)\n if token:\n return 'GoogleLogin auth=%s' % token\n return None", "context": "def GenerateClientLoginAuthToken(http_body): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef GenerateClientLoginAuthToken(http_body): ...\ndef get_client_login_token(http_body): ...\ndef extract_client_login_token(http_body, scopes): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef GenerateOAuthRequestTokenUrl(oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): ...\ndef GenerateOAuthAuthorizationUrl(request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): ...\ndef GenerateOAuthAccessTokenUrl(authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0', oauth_verifier=None): ...\ndef GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default'): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef AuthSubTokenFromUrl(url): ...\ndef TokenFromUrl(url): ...\ndef extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): ...\ndef AuthSubTokenFromHttpBody(http_body): ...\ndef token_from_http_body(http_body): ...\ndef OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): ...\ndef OAuthTokenFromHttpBody(http_body): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGenerateClientLoginAuthToken", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002206.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "TokenFromUrl", "tests": "import unittest\n\nclass Test_TokenFromUrl(unittest.TestCase):\n def testGetTokenFromUrl(self):\n url = 'http://www.yourwebapp.com/showcalendar.html?token=CKF50YzIH'\n self.assert_(gdata.auth.AuthSubTokenFromUrl(url) == 'AuthSub token=CKF50YzIH')\n self.assert_(gdata.auth.TokenFromUrl(url) == 'CKF50YzIH')\n url = 'http://www.yourwebapp.com/showcalendar.html?token==tokenCKF50YzIH='\n self.assert_(gdata.auth.AuthSubTokenFromUrl(url) == 'AuthSub token==tokenCKF50YzIH=')\n self.assert_(gdata.auth.TokenFromUrl(url) == '=tokenCKF50YzIH=')\n", "method_code": "def TokenFromUrl(url):\n \"\"\"Extracts the AuthSub token from the URL.\n\n Returns the raw token value.\n\n Args:\n url: str The URL or the query portion of the URL string (after the ?) of\n the current page which contains the AuthSub token as a URL parameter.\n \"\"\"\n if url.find('?') > -1:\n query_params = url.split('?')[1]\n else:\n query_params = url\n for pair in query_params.split('&'):\n if pair.startswith('token='):\n return pair[6:]\n return None", "context": "def TokenFromUrl(url): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef GenerateClientLoginAuthToken(http_body): ...\ndef get_client_login_token(http_body): ...\ndef extract_client_login_token(http_body, scopes): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef GenerateOAuthRequestTokenUrl(oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): ...\ndef GenerateOAuthAuthorizationUrl(request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): ...\ndef GenerateOAuthAccessTokenUrl(authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0', oauth_verifier=None): ...\ndef GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default'): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef AuthSubTokenFromUrl(url): ...\ndef TokenFromUrl(url): ...\ndef extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): ...\ndef AuthSubTokenFromHttpBody(http_body): ...\ndef token_from_http_body(http_body): ...\ndef OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): ...\ndef OAuthTokenFromHttpBody(http_body): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetTokenFromUrl", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002207.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "AuthSubTokenFromHttpBody", "tests": "import unittest\n\nclass Test_AuthSubTokenFromHttpBody(unittest.TestCase):\n def testGetTokenFromHttpResponse(self):\n response_body = 'Token=DQAA...7DCTN\\r\\nExpiration=20061004T123456Z'\n self.assert_(gdata.auth.AuthSubTokenFromHttpBody(response_body) == 'AuthSub token=DQAA...7DCTN')\n", "method_code": "def AuthSubTokenFromHttpBody(http_body):\n \"\"\"Extracts the AuthSub token from an HTTP body string.\n\n Used to find the new session token after making a request to upgrade a\n single use AuthSub token.\n\n Args:\n http_body: str The repsonse from the server which contains the AuthSub\n key. For example, this function would find the new session token\n from the server's response to an upgrade token request.\n\n Returns:\n The header value to use for Authorization which contains the AuthSub\n token.\n \"\"\"\n token_value = token_from_http_body(http_body)\n if token_value:\n return '%s%s' % (AUTHSUB_AUTH_LABEL, token_value)\n return None", "context": "def AuthSubTokenFromHttpBody(http_body): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef GenerateClientLoginAuthToken(http_body): ...\ndef get_client_login_token(http_body): ...\ndef extract_client_login_token(http_body, scopes): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef GenerateOAuthRequestTokenUrl(oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): ...\ndef GenerateOAuthAuthorizationUrl(request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): ...\ndef GenerateOAuthAccessTokenUrl(authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0', oauth_verifier=None): ...\ndef GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default'): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef AuthSubTokenFromUrl(url): ...\ndef TokenFromUrl(url): ...\ndef extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): ...\ndef AuthSubTokenFromHttpBody(http_body): ...\ndef token_from_http_body(http_body): ...\ndef OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): ...\ndef OAuthTokenFromHttpBody(http_body): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetTokenFromHttpResponse", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002208.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "OAuthTokenFromUrl", "tests": "import unittest\n\nclass Test_OAuthTokenFromUrl(unittest.TestCase):\n def testOAuthTokenFromUrl(self):\n scope_1 = 'http://docs.google.com/feeds/'\n scope_2 = 'http://www.blogger.com/feeds/'\n url = 'http://dummy.com/?oauth_token_scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F+http%3A%2F%2Fdocs.google.com%2Ffeeds%2F&oauth_token=CMns6t7MCxDz__8B'\n token = gdata.auth.OAuthTokenFromUrl(url)\n self.assertEquals('CMns6t7MCxDz__8B', token.key)\n self.assertEquals(2, len(token.scopes))\n self.assert_(scope_1 in token.scopes)\n self.assert_(scope_2 in token.scopes)\n url = 'http://dummy.com/?oauth_token_scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F+http%3A%2F%2Fdocs.google.com%2Ffeeds%2F&oauth_token=CMns6t7MCxDz__8B'\n token = gdata.auth.OAuthTokenFromUrl(url, scopes_param_prefix='token_scope')\n self.assertEquals('CMns6t7MCxDz__8B', token.key)\n self.assert_(not token.scopes)\n url = 'http://dummy.com/?no_oauth_token_scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F+http%3A%2F%2Fdocs.google.com%2Ffeeds%2F&no_oauth_token=CMns6t7MCxDz__8B'\n token = gdata.auth.OAuthTokenFromUrl(url)\n self.assert_(token is None)\n", "method_code": "def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'):\n \"\"\"Creates an OAuthToken and sets token key and scopes (if present) from URL.\n \n After the Google Accounts OAuth pages redirect the user's broswer back to \n the web application (using the 'callback' URL from the request) the web app\n can extract the token from the current page's URL. The token is same as the\n request token, but it is either authorized (if user grants access) or\n unauthorized (if user denies access). The token is provided as a \n URL parameter named 'oauth_token' and if it was chosen to use\n GenerateOAuthAuthorizationUrl with include_scopes_in_param=True, the token's\n valid scopes are included in a URL parameter whose name is specified in\n scopes_param_prefix.\n\n Args:\n url: atom.url.Url or str representing the current URL. The token value\n and valid scopes should be included as URL parameters.\n scopes_param_prefix: str (optional) The URL parameter key which maps to\n the list of valid scopes for the token.\n\n Returns:\n An OAuthToken with the token key from the URL and set to be valid for\n the scopes passed in on the URL. If no scopes were included in the URL,\n the OAuthToken defaults to being valid for no scopes. If there was no\n 'oauth_token' parameter in the URL, this function returns None.\n \"\"\"\n if isinstance(url, (str, unicode)):\n url = atom.url.parse_url(url)\n if 'oauth_token' not in url.params:\n return None\n scopes = []\n if scopes_param_prefix in url.params:\n scopes = url.params[scopes_param_prefix].split(' ')\n token_key = url.params['oauth_token']\n token = OAuthToken(key=token_key, scopes=scopes)\n return token", "context": "def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef GenerateClientLoginAuthToken(http_body): ...\ndef get_client_login_token(http_body): ...\ndef extract_client_login_token(http_body, scopes): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef GenerateOAuthRequestTokenUrl(oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): ...\ndef GenerateOAuthAuthorizationUrl(request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): ...\ndef GenerateOAuthAccessTokenUrl(authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0', oauth_verifier=None): ...\ndef GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default'): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef AuthSubTokenFromUrl(url): ...\ndef TokenFromUrl(url): ...\ndef extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): ...\ndef AuthSubTokenFromHttpBody(http_body): ...\ndef token_from_http_body(http_body): ...\ndef OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): ...\ndef OAuthTokenFromHttpBody(http_body): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testOAuthTokenFromUrl", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002209.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "OAuthTokenFromHttpBody", "tests": "import unittest\n\nclass Test_OAuthTokenFromHttpBody(unittest.TestCase):\n def testOAuthTokenFromHttpBody(self):\n token_key = 'ABCD'\n token_secret = 'XYZ'\n http_body = 'oauth_token=%s&oauth_token_secret=%s' % (token_key, token_secret)\n token = gdata.auth.OAuthTokenFromHttpBody(http_body)\n self.assertEquals(token_key, token.key)\n self.assertEquals(token_secret, token.secret)\n", "method_code": "def OAuthTokenFromHttpBody(http_body):\n \"\"\"Parses the HTTP response body and returns an OAuth token.\n \n The returned OAuth token will just have key and secret parameters set.\n It won't have any knowledge about the scopes or oauth_input_params. It is\n your responsibility to make it aware of the remaining parameters.\n \n Returns:\n OAuthToken OAuth token.\n \"\"\"\n token = oauth.OAuthToken.from_string(http_body)\n oauth_token = OAuthToken(key=token.key, secret=token.secret)\n return oauth_token", "context": "def OAuthTokenFromHttpBody(http_body): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef GenerateClientLoginAuthToken(http_body): ...\ndef get_client_login_token(http_body): ...\ndef extract_client_login_token(http_body, scopes): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef GenerateOAuthRequestTokenUrl(oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): ...\ndef GenerateOAuthAuthorizationUrl(request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): ...\ndef GenerateOAuthAccessTokenUrl(authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0', oauth_verifier=None): ...\ndef GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default'): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef AuthSubTokenFromUrl(url): ...\ndef TokenFromUrl(url): ...\ndef extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): ...\ndef AuthSubTokenFromHttpBody(http_body): ...\ndef token_from_http_body(http_body): ...\ndef OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): ...\ndef OAuthTokenFromHttpBody(http_body): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testOAuthTokenFromHttpBody", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002210.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "GetSignatureMethod", "tests": "import unittest\n\nclass Test_GetSignatureMethod(unittest.TestCase):\n def testGetSignatureMethod(self):\n self.assertEquals('HMAC-SHA1', self.oauth_input_parameters_hmac.GetSignatureMethod().get_name())\n rsa_signature_method = self.oauth_input_parameters_rsa.GetSignatureMethod()\n self.assertEquals('RSA-SHA1', rsa_signature_method.get_name())\n self.assertEquals(RSA_KEY, rsa_signature_method._fetch_private_cert(None))\n", "method_code": " def GetSignatureMethod(self):\n \"\"\"Gets the OAuth signature method.\n \n Returns:\n object of supertype \n \"\"\"\n return self._signature_method\n ", "context": "class OAuthInputParams(object):\n def GetSignatureMethod(self): ...\n def __init__(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, requestor_id=None): ...\n def __get_signature_method(self): ...\n def __set_signature_method(self, signature_method): ...\n def GetConsumer(self): ...\n\n self.rsa_key = rsa_key\n self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)\n self.requestor_id = requestor_id\n\n _signature_method = property(__get_signature_method, __set_signature_method, doc='Returns object capable of signing the request using RSA of HMAC.\\n \\n Replaces the _signature_method member to avoid pickle errors.')\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetSignatureMethod", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002211.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "GetConsumer", "tests": "import unittest\n\nclass Test_GetConsumer(unittest.TestCase):\n def testGetConsumer(self):\n self.assertEquals(CONSUMER_KEY, self.oauth_input_parameters_hmac.GetConsumer().key)\n self.assertEquals(CONSUMER_KEY, self.oauth_input_parameters_rsa.GetConsumer().key)\n self.assertEquals(CONSUMER_SECRET, self.oauth_input_parameters_hmac.GetConsumer().secret)\n self.assert_(self.oauth_input_parameters_rsa.GetConsumer().secret is None)\n", "method_code": " def GetConsumer(self):\n \"\"\"Gets the OAuth consumer.\n \n Returns:\n object of type \n \"\"\"\n return self._consumer\n ", "context": "class OAuthInputParams(object):\n def GetConsumer(self): ...\n def __init__(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, requestor_id=None): ...\n def __get_signature_method(self): ...\n def __set_signature_method(self, signature_method): ...\n def GetSignatureMethod(self): ...\n\n self.rsa_key = rsa_key\n self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)\n self.requestor_id = requestor_id\n\n _signature_method = property(__get_signature_method, __set_signature_method, doc='Returns object capable of signing the request using RSA of HMAC.\\n \\n Replaces the _signature_method member to avoid pickle errors.')\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetConsumer", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002212.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "set_token_string", "tests": "import unittest\n\nclass Test_set_token_string(unittest.TestCase):\n def testOAuthToAndFromString(self):\n token_key = 'ABCD'\n token_secret = 'XYZ'\n token_string = 'oauth_token=%s&oauth_token_secret=%s' % (token_key, token_secret)\n token = gdata.auth.OAuthToken()\n token.set_token_string(token_string)\n self.assert_(-1 < token.get_token_string().find(token_string.split('&')[0]))\n self.assert_(-1 < token.get_token_string().find(token_string.split('&')[1]))\n self.assertEquals(token_key, token.key)\n self.assertEquals(token_secret, token.secret)\n token_string = 'oauth_token=%s&oauth_token_secret=%s&oauth_token=%s&ExtraParams=GarbageString' % (token_key, token_secret, 'LMNO')\n token = gdata.auth.OAuthToken()\n token.set_token_string(token_string)\n self.assert_(-1 < token.get_token_string().find(token_string.split('&')[0]))\n self.assert_(-1 < token.get_token_string().find(token_string.split('&')[1]))\n self.assertEquals(token_key, token.key)\n self.assertEquals(token_secret, token.secret)\n token_string = 'oauth_token=%s' % (token_key,)\n token = gdata.auth.OAuthToken()\n token.set_token_string(token_string)\n self.assertEquals(token_string, token.get_token_string())\n self.assertEquals(token_key, token.key)\n self.assert_(not token.secret)\n token_string = 'oauth_token_secret=%s' % (token_secret,)\n token = gdata.auth.OAuthToken()\n token.set_token_string(token_string)\n self.assertEquals(token_string, token.get_token_string())\n self.assertEquals(token_secret, token.secret)\n self.assert_(not token.key)\n token_string = ''\n token = gdata.auth.OAuthToken()\n token.set_token_string(token_string)\n self.assert_(token.get_token_string() is None)\n self.assert_(not token.key)\n self.assert_(not token.secret)\n", "method_code": " def set_token_string(self, token_string):\n self.auth_header = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, token_string)\n ", "context": "class ClientLoginToken(atom.http_interface.GenericToken):\n def set_token_string(self, token_string): ...\n def __init__(self, auth_header=None, scopes=None): ...\n def __str__(self): ...\n def perform_request(self, http_client, operation, url, data=None, headers=None): ...\n def get_token_string(self): ...\n def valid_for_scope(self, url): ...\n\n self.auth_header = auth_header\n self.scopes = scopes or []\n", "repository": "bigsnarfdude/webscraping", "test_name": "testOAuthToAndFromString", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002213.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/auth.py", "focal_class": null, "focal_method": "GetAuthHeader", "tests": "import unittest\n\nclass Test_GetAuthHeader(unittest.TestCase):\n def testSecureAuthSubGetAuthHeader(self):\n url = 'http://dummy.com/?q=notebook&s=true'\n token = gdata.auth.SecureAuthSubToken(RSA_KEY, token_string='foo')\n auth_header = token.GetAuthHeader('GET', url)\n self.assert_('Authorization' in auth_header)\n header_value = auth_header['Authorization']\n self.assert_(header_value.startswith('AuthSub token=\"foo\"'))\n self.assert_(-1 < header_value.find('sigalg=\"rsa-sha1\"'))\n self.assert_(-1 < header_value.find('data=\"'))\n self.assert_(-1 < header_value.find('sig=\"'))\n m = re.search('data=\"(.*?)\"', header_value)\n self.assert_(m is not None)\n data = m.group(1)\n self.assert_(data.startswith('GET'))\n self.assert_(-1 < data.find(url))\n\n def testOAuthGetAuthHeader(self):\n oauth_input_params = gdata.auth.OAuthInputParams(gdata.auth.OAuthSignatureMethod.RSA_SHA1, CONSUMER_KEY, rsa_key=RSA_KEY)\n token = gdata.auth.OAuthToken(key='ABCDDSFFDSG', oauth_input_params=oauth_input_params)\n auth_header = token.GetAuthHeader('GET', 'http://dummy.com/?q=notebook&s=true', realm='http://dummy.com')\n self.assert_('Authorization' in auth_header)\n header_value = auth_header['Authorization']\n self.assert_(-1 < header_value.find('OAuth realm=\"http://dummy.com\"'))\n self.assert_(-1 < header_value.find('oauth_version=\"1.0\"'))\n self.assert_(-1 < header_value.find('oauth_token=\"ABCDDSFFDSG\"'))\n self.assert_(-1 < header_value.find('oauth_nonce=\"'))\n self.assert_(-1 < header_value.find('oauth_timestamp=\"'))\n self.assert_(-1 < header_value.find('oauth_signature=\"'))\n self.assert_(-1 < header_value.find('oauth_consumer_key=\"%s\"' % CONSUMER_KEY))\n self.assert_(-1 < header_value.find('oauth_signature_method=\"RSA-SHA1\"'))\n oauth_input_params = gdata.auth.OAuthInputParams(gdata.auth.OAuthSignatureMethod.HMAC_SHA1, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)\n token = gdata.auth.OAuthToken(oauth_input_params=oauth_input_params)\n auth_header = token.GetAuthHeader('GET', 'http://dummy.com/?xoauth_requestor_id=user@gmail.com&q=book')\n self.assert_('Authorization' in auth_header)\n header_value = auth_header['Authorization']\n self.assert_(-1 < header_value.find('OAuth realm=\"\"'))\n self.assert_(-1 < header_value.find('oauth_version=\"1.0\"'))\n self.assertEquals(-1, header_value.find('oauth_token='))\n self.assert_(-1 < header_value.find('oauth_nonce=\"'))\n self.assert_(-1 < header_value.find('oauth_timestamp=\"'))\n self.assert_(-1 < header_value.find('oauth_signature=\"'))\n self.assert_(-1 < header_value.find('oauth_consumer_key=\"%s\"' % CONSUMER_KEY))\n self.assert_(-1 < header_value.find('oauth_signature_method=\"HMAC-SHA1\"'))\n", "method_code": " def GetAuthHeader(self, http_method, http_url, realm=''):\n \"\"\"Get the authentication header.\n \n Args:\n http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.\n http_url: string or atom.url.Url HTTP URL to which request is made.\n realm: string (default='') realm parameter to be included in the\n authorization header.\n \n Returns:\n dict Header to be sent with every subsequent request after\n authentication.\n \"\"\"\n if isinstance(http_url, types.StringTypes):\n http_url = atom.url.parse_url(http_url)\n header = None\n token = None\n if self.key or self.secret:\n token = oauth.OAuthToken(self.key, self.secret)\n oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.oauth_input_params.GetConsumer(), token=token, http_url=str(http_url), http_method=http_method, parameters=http_url.params)\n oauth_request.sign_request(self.oauth_input_params.GetSignatureMethod(), self.oauth_input_params.GetConsumer(), token)\n header = oauth_request.to_header(realm=realm)\n header['Authorization'] = header['Authorization'].replace('+', '%2B')\n return header\n ", "context": "class OAuthToken(atom.http_interface.GenericToken):\n def GetAuthHeader(self, http_method, http_url, realm=''): ...\n def __init__(self, key=None, secret=None, scopes=None, oauth_input_params=None): ...\n def __str__(self): ...\n def get_token_string(self): ...\n def set_token_string(self, token_string): ...\n def perform_request(self, http_client, operation, url, data=None, headers=None): ...\n def valid_for_scope(self, url): ...\n\n self.key = key\n self.secret = secret\n self.scopes = scopes or []\n self.oauth_input_params = oauth_input_params\n", "repository": "bigsnarfdude/webscraping", "test_name": "testSecureAuthSubGetAuthHeader", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002214.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/core.py", "focal_class": null, "focal_method": "_convert_to_jsonc", "tests": "import unittest\n\nclass Test_convert_to_jsonc(unittest.TestCase):\n def test_to_and_from_jsonc(self):\n x = {'a': 1}\n jsonc_obj = gdata.core._convert_to_jsonc(x)\n self.assertEqual(jsonc_obj.a, 1)\n self.assertEqual(x, gdata.core._convert_to_object(jsonc_obj))\n\n def test_convert_to_jsonc(self):\n x = gdata.core._convert_to_jsonc(1)\n self.assert_(isinstance(x, (int, long)))\n self.assertEqual(x, 1)\n x = gdata.core._convert_to_jsonc([1, 'a'])\n self.assert_(isinstance(x, list))\n self.assertEqual(len(x), 2)\n self.assert_(isinstance(x[0], (int, long)))\n self.assertEqual(x[0], 1)\n self.assert_(isinstance(x[1], (str, unicode)))\n self.assertEqual(x[1], 'a')\n x = gdata.core._convert_to_jsonc([{'b': 1}, 'a'])\n self.assert_(isinstance(x, list))\n self.assertEqual(len(x), 2)\n self.assert_(isinstance(x[0], gdata.core.Jsonc))\n self.assertEqual(x[0].b, 1)\n", "method_code": "def _convert_to_jsonc(x):\n \"\"\"Builds a Jsonc objects which wraps the argument's members.\"\"\"\n if isinstance(x, dict):\n jsonc_obj = Jsonc()\n for key, value in x.iteritems():\n jsonc_obj._dict[key] = _convert_to_jsonc(value)\n return jsonc_obj\n elif isinstance(x, list):\n members = []\n for item in x:\n members.append(_convert_to_jsonc(item))\n return members\n else:\n return x", "context": "def _convert_to_jsonc(x): ...\ndef _convert_to_jsonc(x): ...\ndef parse_json(json_string): ...\ndef parse_json_file(json_file): ...\ndef jsonc_to_string(jsonc_obj): ...\ndef prettify_jsonc(jsonc_obj, indentation=2): ...\ndef _convert_to_object(jsonc_obj): ...\ndef _to_jsonc_name(member_name): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_to_and_from_jsonc", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002215.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/core.py", "focal_class": null, "focal_method": "parse_json", "tests": "import unittest\n\nclass Test_parse_json(unittest.TestCase):\n def test_read_json(self):\n x = gdata.core.parse_json(PLAYLIST_EXAMPLE)\n self.assert_(isinstance(x._dict, dict))\n self.assertEqual(x._dict['apiVersion'], '2.0')\n self.assertEqual(x.api_version, '2.0')\n x = gdata.core.parse_json(VIDEO_EXAMPLE)\n self.assert_(isinstance(x._dict, dict))\n self.assertEqual(x._dict['apiVersion'], '2.0')\n self.assertEqual(x.api_version, '2.0')\n x = gdata.core.parse_json(VIDEO_EXAMPLE)\n self.check_video_json(x)\n", "method_code": "def parse_json(json_string):\n \"\"\"Converts a JSON-C string into a Jsonc object.\n \n Args:\n json_string: str or unicode The JSON to be parsed.\n \n Returns:\n A new Jsonc object.\n \"\"\"\n return _convert_to_jsonc(simplejson.loads(json_string))", "context": "def parse_json(json_string): ...\ndef _convert_to_jsonc(x): ...\ndef parse_json(json_string): ...\ndef parse_json_file(json_file): ...\ndef jsonc_to_string(jsonc_obj): ...\ndef prettify_jsonc(jsonc_obj, indentation=2): ...\ndef _convert_to_object(jsonc_obj): ...\ndef _to_jsonc_name(member_name): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_read_json", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002216.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/core.py", "focal_class": null, "focal_method": "jsonc_to_string", "tests": "import unittest\n\nclass Test_jsonc_to_string(unittest.TestCase):\n def test_to_string(self):\n self.check_video_json(gdata.core.parse_json(gdata.core.jsonc_to_string(gdata.core._convert_to_object(build_test_object()))))\n", "method_code": "def jsonc_to_string(jsonc_obj):\n \"\"\"Converts a Jsonc object into a string of JSON-C.\"\"\"\n return simplejson.dumps(_convert_to_object(jsonc_obj))", "context": "def jsonc_to_string(jsonc_obj): ...\ndef _convert_to_jsonc(x): ...\ndef parse_json(json_string): ...\ndef parse_json_file(json_file): ...\ndef jsonc_to_string(jsonc_obj): ...\ndef prettify_jsonc(jsonc_obj, indentation=2): ...\ndef _convert_to_object(jsonc_obj): ...\ndef _to_jsonc_name(member_name): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_to_string", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002217.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "generate_auth_sub_url", "tests": "import unittest\n\nclass Test_generate_auth_sub_url(unittest.TestCase):\n def test_generate_request_url(self):\n url = gdata.gauth.generate_auth_sub_url('http://example.com', ['http://example.net/scope1'])\n self.assert_(isinstance(url, atom.http_core.Uri))\n self.assertEqual(url.query['secure'], '0')\n self.assertEqual(url.query['session'], '1')\n self.assertEqual(url.query['scope'], 'http://example.net/scope1')\n self.assertEqual(atom.http_core.Uri.parse_uri(url.query['next']).query['auth_sub_scopes'], 'http://example.net/scope1')\n self.assertEqual(atom.http_core.Uri.parse_uri(url.query['next']).path, '/')\n self.assertEqual(atom.http_core.Uri.parse_uri(url.query['next']).host, 'example.com')\n", "method_code": "def generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'):\n \"\"\"Constructs a URI for requesting a multiscope AuthSub token.\n\n The generated token will contain a URL parameter to pass along the\n requested scopes to the next URL. When the Google Accounts page\n redirects the broswser to the 'next' URL, it appends the single use\n AuthSub token value to the URL as a URL parameter with the key 'token'.\n However, the information about which scopes were requested is not\n included by Google Accounts. This method adds the scopes to the next\n URL before making the request so that the redirect will be sent to\n a page, and both the token value and the list of scopes for which the token\n was requested.\n\n Args:\n next: atom.http_core.Uri or string The URL user will be sent to after\n authorizing this web application to access their data.\n scopes: list containint strings or atom.http_core.Uri objects. The URLs\n of the services to be accessed. Could also be a single string\n or single atom.http_core.Uri for requesting just one scope.\n secure: boolean (optional) Determines whether or not the issued token\n is a secure token.\n session: boolean (optional) Determines whether or not the issued token\n can be upgraded to a session token.\n request_url: atom.http_core.Uri or str The beginning of the request URL.\n This is normally\n 'http://www.google.com/accounts/AuthSubRequest' or\n '/accounts/AuthSubRequest'\n domain: The domain which the account is part of. This is used for Google\n Apps accounts, the default value is 'default' which means that\n the requested account is a Google Account (@gmail.com for\n example)\n scopes_param_prefix: str (optional) The requested scopes are added as a\n URL parameter to the next URL so that the page at\n the 'next' URL can extract the token value and the\n valid scopes from the URL. The key for the URL\n parameter defaults to 'auth_sub_scopes'\n\n Returns:\n An atom.http_core.Uri which the user's browser should be directed to in\n order to authorize this application to access their information.\n \"\"\"\n if isinstance(next, (str, unicode)):\n next = atom.http_core.Uri.parse_uri(next)\n if isinstance(scopes, (str, unicode, atom.http_core.Uri)):\n scopes = (scopes,)\n scopes_string = ' '.join([str(scope) for scope in scopes])\n next.query[scopes_param_prefix] = scopes_string\n if isinstance(request_url, (str, unicode)):\n request_url = atom.http_core.Uri.parse_uri(request_url)\n request_url.query['next'] = str(next)\n request_url.query['scope'] = scopes_string\n if session:\n request_url.query['session'] = '1'\n else:\n request_url.query['session'] = '0'\n if secure:\n request_url.query['secure'] = '1'\n else:\n request_url.query['secure'] = '0'\n request_url.query['hd'] = domain\n return request_url", "context": "def generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_generate_request_url", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002218.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "modify_request", "tests": "import unittest\n\nclass Test_modify_request(unittest.TestCase):\n def test_modify_request(self):\n token = gdata.gauth.OAuth2Token('clientId', 'clientSecret', 'https://www.google.com/calendar/feeds', 'userAgent', access_token='accessToken')\n request = atom.http_core.HttpRequest()\n token.modify_request(request)\n self.assertEqual(request.headers['Authorization'], 'OAuth accessToken')\n", "method_code": " def modify_request(self, http_request):\n http_request.headers['Authorization'] = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, self.token_string)\n ", "context": "class ClientLoginToken(object):\n def modify_request(self, http_request): ...\n def __init__(self, token_string): ...\n\n self.token_string = token_string\n\n ModifyRequest = modify_request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_modify_request", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002219.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "_upgrade_token", "tests": "import unittest\n\nclass Test_upgrade_token(unittest.TestCase):\n def test_create_and_upgrade_tokens(self):\n token = gdata.gauth.AuthSubToken.from_url('http://example.com/?token=123abc')\n self.assert_(isinstance(token, gdata.gauth.AuthSubToken))\n self.assertEqual(token.token_string, '123abc')\n self.assertEqual(token.scopes, [])\n token._upgrade_token('Token=456def')\n self.assertEqual(token.token_string, '456def')\n self.assertEqual(token.scopes, [])\n", "method_code": " def _upgrade_token(self, http_body):\n \"\"\"Replaces the token value with a session token from the auth server.\n \n Uses the response of a token upgrade request to modify this token. Uses\n auth_sub_string_from_body.\n \"\"\"\n self.token_string = auth_sub_string_from_body(http_body)\n ", "context": "class AuthSubToken(object):\n def _upgrade_token(self, http_body): ...\n def __init__(self, token_string, scopes=None): ...\n def modify_request(self, http_request): ...\n def from_url(str_or_uri): ...\n\n self.token_string = token_string\n self.scopes = scopes or []\n\n ModifyRequest = modify_request\n from_url = staticmethod(from_url)\n FromUrl = from_url\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_create_and_upgrade_tokens", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002220.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "build_auth_sub_data", "tests": "import unittest\n\nclass Test_build_auth_sub_data(unittest.TestCase):\n def test_build_data(self):\n request = atom.http_core.HttpRequest(method='PUT')\n request.uri = atom.http_core.Uri.parse_uri('http://example.com/foo?a=1')\n data = gdata.gauth.build_auth_sub_data(request, 1234567890, 'mynonce')\n self.assertEqual(data, 'PUT http://example.com/foo?a=1 1234567890 mynonce')\n", "method_code": "def build_auth_sub_data(http_request, timestamp, nonce):\n \"\"\"Creates the data string which must be RSA-signed in secure requests.\n\n For more details see the documenation on secure AuthSub requests:\n http://code.google.com/apis/accounts/docs/AuthSub.html#signingrequests\n\n Args:\n http_request: The request being made to the server. The Request's URL\n must be complete before this signature is calculated as any changes\n to the URL will invalidate the signature.\n nonce: str Random 64-bit, unsigned number encoded as an ASCII string in\n decimal format. The nonce/timestamp pair should always be unique to\n prevent replay attacks.\n timestamp: Integer representing the time the request is sent. The\n timestamp should be expressed in number of seconds after January 1,\n 1970 00:00:00 GMT.\n \"\"\"\n return '%s %s %s %s' % (http_request.method, str(http_request.uri), str(timestamp), nonce)", "context": "def build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_build_data", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002221.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "generate_signature", "tests": "import unittest\n\nclass Test_generate_signature(unittest.TestCase):\n def test_generate_signature(self):\n request = atom.http_core.HttpRequest(method='GET', uri=atom.http_core.Uri(host='example.com', path='/foo', query={'a': '1'}))\n data = gdata.gauth.build_auth_sub_data(request, 1134567890, 'p234908')\n self.assertEqual(data, 'GET http://example.com/foo?a=1 1134567890 p234908')\n self.assertEqual(gdata.gauth.generate_signature(data, PRIVATE_TEST_KEY), 'GeBfeIDnT41dvLquPgDB4U5D4hfxqaHk/5LX1kccNBnL4BjsHWU1djbEp7xp3BL9abQtLrK7oa/aHEHtGRUZGg87O+ND8iDPR76WFXAruuN8O8GCMqCDdPduNPY++LYO4MdJBZNY974Nn0m6Hc0/T4M1ElqvPhl61fkXMm+ElSM=')\n", "method_code": "def generate_signature(data, rsa_key):\n \"\"\"Signs the data string for a secure AuthSub request.\"\"\"\n import base64\n try:\n from tlslite.utils import keyfactory\n except ImportError:\n try:\n from gdata.tlslite.utils import keyfactory\n except ImportError:\n from tlslite.tlslite.utils import keyfactory\n private_key = keyfactory.parsePrivateKey(rsa_key)\n signed = private_key.hashAndSign(data)\n if hasattr(base64, 'b64encode'):\n return base64.b64encode(signed)\n else:\n return base64.encodestring(signed).replace('\\n', '')", "context": "def generate_signature(data, rsa_key): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_generate_signature", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002222.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "build_oauth_base_string", "tests": "import unittest\n\nclass Test_build_oauth_base_string(unittest.TestCase):\n def test_build_base_string(self):\n request = atom.http_core.HttpRequest('http://example.com/', 'GET')\n base_string = gdata.gauth.build_oauth_base_string(request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0')\n self.assertEqual(base_string, 'GET&http%3A%2F%2Fexample.com%2F&oauth_callback%3Doob%26oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oauth_version%3D1.0')\n request = atom.http_core.HttpRequest('http://www.google.com/calendar/feeds/default/allcalendars/full?orderby=starttime', 'GET')\n base_string = gdata.gauth.build_oauth_base_string(request, 'example.com', '4572616e48616d6d65724c61686176', gdata.gauth.RSA_SHA1, 137131200, '1.0', token='1%2Fab3cd9j4ks73hf7g', next='http://googlecodesamples.com/oauth_playground/index.php')\n self.assertEqual(base_string, 'GET&http%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2Fdefault%2Fallcalendars%2Ffull&oauth_callback%3Dhttp%253A%252F%252Fgooglecodesamples.com%252Foauth_playground%252Findex.php%26oauth_consumer_key%3Dexample.com%26oauth_nonce%3D4572616e48616d6d65724c61686176%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D137131200%26oauth_token%3D1%25252Fab3cd9j4ks73hf7g%26oauth_version%3D1.0%26orderby%3Dstarttime')\n request = atom.http_core.HttpRequest('http://eXample.COM', 'get')\n base_string = gdata.gauth.build_oauth_base_string(request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0')\n self.assertEqual(base_string, 'GET&http%3A%2F%2Fexample.com%2F&oauth_callback%3Doob%26oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oauth_version%3D1.0')\n request = atom.http_core.HttpRequest('https://eXample.COM:443', 'get')\n base_string = gdata.gauth.build_oauth_base_string(request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0', 'http://googlecodesamples.com/oauth_playground/index.php')\n self.assertEqual(base_string, 'GET&https%3A%2F%2Fexample.com%2F&oauth_callback%3Dhttp%253A%252F%252Fgooglecodesamples.com%252Foauth_playground%252Findex.php%26oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oauth_version%3D1.0')\n request = atom.http_core.HttpRequest('http://eXample.COM:443', 'get')\n base_string = gdata.gauth.build_oauth_base_string(request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0')\n self.assertEqual(base_string, 'GET&http%3A%2F%2Fexample.com%3A443%2F&oauth_callback%3Doob%26oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oauth_version%3D1.0')\n request = atom.http_core.HttpRequest(atom.http_core.Uri(host='eXample.COM'), 'GET')\n base_string = gdata.gauth.build_oauth_base_string(request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0', next='oob')\n self.assertEqual(base_string, 'GET&http%3A%2F%2Fexample.com%2F&oauth_callback%3Doob%26oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oauth_version%3D1.0')\n request = atom.http_core.HttpRequest('https://www.google.com/accounts/OAuthGetRequestToken', 'GET')\n request.uri.query['scope'] = 'https://docs.google.com/feeds/ http://docs.google.com/feeds/'\n base_string = gdata.gauth.build_oauth_base_string(request, 'anonymous', '48522759', gdata.gauth.HMAC_SHA1, 1246489532, '1.0', 'http://googlecodesamples.com/oauth_playground/index.php')\n self.assertEqual(base_string, 'GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_callback%3Dhttp%253A%252F%252Fgooglecodesamples.com%252Foauth_playground%252Findex.php%26oauth_consumer_key%3Danonymous%26oauth_nonce%3D48522759%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246489532%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fdocs.google.com%252Ffeeds%252F%2520http%253A%252F%252Fdocs.google.com%252Ffeeds%252F')\n", "method_code": "def build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None):\n \"\"\"Generates the base string to be signed in the OAuth request.\n\n Args:\n http_request: The request being made to the server. The Request's URL\n must be complete before this signature is calculated as any changes\n to the URL will invalidate the signature.\n consumer_key: Domain identifying the third-party web application. This is\n the domain used when registering the application with Google. It\n identifies who is making the request on behalf of the user.\n nonce: Random 64-bit, unsigned number encoded as an ASCII string in decimal\n format. The nonce/timestamp pair should always be unique to prevent\n replay attacks.\n signaure_type: either RSA_SHA1 or HMAC_SHA1\n timestamp: Integer representing the time the request is sent. The\n timestamp should be expressed in number of seconds after January 1,\n 1970 00:00:00 GMT.\n version: The OAuth version used by the requesting web application. This\n value must be '1.0' or '1.0a'. If not provided, Google assumes version\n 1.0 is in use.\n next: The URL the user should be redirected to after granting access\n to a Google service(s). It can include url-encoded query parameters.\n The default value is 'oob'. (This is the oauth_callback.)\n token: The string for the OAuth request token or OAuth access token.\n verifier: str Sent as the oauth_verifier and required when upgrading a\n request token to an access token.\n \"\"\"\n params = http_request.uri.query.copy()\n params['oauth_consumer_key'] = consumer_key\n params['oauth_nonce'] = nonce\n params['oauth_signature_method'] = signaure_type\n params['oauth_timestamp'] = str(timestamp)\n if next is not None:\n params['oauth_callback'] = str(next)\n if token is not None:\n params['oauth_token'] = token\n if version is not None:\n params['oauth_version'] = version\n if verifier is not None:\n params['oauth_verifier'] = verifier\n sorted_keys = None\n try:\n sorted_keys = sorted(params.keys())\n except NameError:\n sorted_keys = params.keys()\n sorted_keys.sort()\n pairs = []\n for key in sorted_keys:\n pairs.append('%s=%s' % (urllib.quote(key, safe='~'), urllib.quote(params[key], safe='~')))\n all_parameters = urllib.quote('&'.join(pairs), safe='~')\n normailzed_host = http_request.uri.host.lower()\n normalized_scheme = (http_request.uri.scheme or 'http').lower()\n non_default_port = None\n if http_request.uri.port is not None and (normalized_scheme == 'https' and http_request.uri.port != 443 or (normalized_scheme == 'http' and http_request.uri.port != 80)):\n non_default_port = http_request.uri.port\n path = http_request.uri.path or '/'\n request_path = None\n if not path.startswith('/'):\n path = '/%s' % path\n if non_default_port is not None:\n request_path = urllib.quote('%s://%s:%s%s' % (normalized_scheme, normailzed_host, non_default_port, path), safe='~')\n else:\n request_path = urllib.quote('%s://%s%s' % (normalized_scheme, normailzed_host, path), safe='~')\n base_string = '&'.join((http_request.method.upper(), request_path, all_parameters))\n return base_string", "context": "def build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_build_base_string", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002223.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "generate_hmac_signature", "tests": "import unittest\n\nclass Test_generate_hmac_signature(unittest.TestCase):\n def test_generate_hmac_signature(self):\n request = atom.http_core.HttpRequest('https://www.google.com/accounts/OAuthGetRequestToken?scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F', 'GET')\n signature = gdata.gauth.generate_hmac_signature(request, 'anonymous', 'anonymous', '1246491360', 'c0155b3f28697c029e7a62efff44bd46', '1.0', next='http://googlecodesamples.com/oauth_playground/index.php')\n self.assertEqual(signature, '5a2GPdtAY3LWYv8IdiT3wp1Coeg=')\n request = atom.http_core.HttpRequest('https://www.google.com/accounts/OAuthGetRequestToken', 'GET')\n request.uri.query['scope'] = 'http://www.blogger.com/feeds/'\n signature = gdata.gauth.generate_hmac_signature(request, 'anonymous', 'anonymous', '1246491360', 'c0155b3f28697c029e7a62efff44bd46', '1.0', 'http://googlecodesamples.com/oauth_playground/index.php')\n self.assertEqual(signature, '5a2GPdtAY3LWYv8IdiT3wp1Coeg=')\n request = atom.http_core.HttpRequest('https://www.google.com/accounts/OAuthGetRequestToken', 'GET')\n request.uri.query['scope'] = 'https://www.google.com/analytics/feeds/ http://www.google.com/base/feeds/ http://www.google.com/calendar/feeds/'\n signature = gdata.gauth.generate_hmac_signature(request, 'anonymous', 'anonymous', 1246491797, '33209c4d7a09be4eb1d6ff18e00f8548', '1.0', next='http://googlecodesamples.com/oauth_playground/index.php')\n self.assertEqual(signature, 'kFAgTTFDIWz4/xAabIlrcZZMTq8=')\n", "method_code": "def generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None):\n import hmac\n import base64\n base_string = build_oauth_base_string(http_request, consumer_key, nonce, HMAC_SHA1, timestamp, version, next, token, verifier=verifier)\n hash_key = None\n hashed = None\n if token_secret is not None:\n hash_key = '%s&%s' % (urllib.quote(consumer_secret, safe='~'), urllib.quote(token_secret, safe='~'))\n else:\n hash_key = '%s&' % urllib.quote(consumer_secret, safe='~')\n try:\n import hashlib\n hashed = hmac.new(hash_key, base_string, hashlib.sha1)\n except ImportError:\n import sha\n hashed = hmac.new(hash_key, base_string, sha)\n if hasattr(base64, 'b64encode'):\n return base64.b64encode(hashed.digest())\n else:\n return base64.encodestring(hashed.digest()).replace('\\n', '')", "context": "def generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_generate_hmac_signature", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002224.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "generate_rsa_signature", "tests": "import unittest\n\nclass Test_generate_rsa_signature(unittest.TestCase):\n def test_generate_rsa_signature(self):\n request = atom.http_core.HttpRequest('https://www.google.com/accounts/OAuthGetRequestToken?scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F', 'GET')\n signature = gdata.gauth.generate_rsa_signature(request, 'anonymous', PRIVATE_TEST_KEY, '1246491360', 'c0155b3f28697c029e7a62efff44bd46', '1.0', next='http://googlecodesamples.com/oauth_playground/index.php')\n self.assertEqual(signature, 'bfMantdttKaTrwoxU87JiXmMeXhAiXPiq79a5XmLlOYwwlX06Pu7CafMp7hW1fPeZtL4o9Sz3NvPI8GECCaZk7n5vi1EJ5/wfIQbddrC8j45joBG6gFSf4tRJct82dSyn6bd71knwPZH1sKK46Y0ePJvEIDI3JDd7pRZuMM2sN8=')\n", "method_code": "def generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None):\n import base64\n try:\n from tlslite.utils import keyfactory\n except ImportError:\n try:\n from gdata.tlslite.utils import keyfactory\n except ImportError:\n from tlslite.tlslite.utils import keyfactory\n base_string = build_oauth_base_string(http_request, consumer_key, nonce, RSA_SHA1, timestamp, version, next, token, verifier=verifier)\n private_key = keyfactory.parsePrivateKey(rsa_key)\n signed = private_key.hashAndSign(base_string)\n if hasattr(base64, 'b64encode'):\n return base64.b64encode(signed)\n else:\n return base64.encodestring(signed).replace('\\n', '')", "context": "def generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_generate_rsa_signature", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002225.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "generate_authorize_url", "tests": "import unittest\n\nclass Test_generate_authorize_url(unittest.TestCase):\n def test_generate_authorize_url(self):\n token = gdata.gauth.OAuth2Token('clientId', 'clientSecret', 'https://www.google.com/calendar/feeds', 'userAgent')\n url = token.generate_authorize_url()\n self.assertEqual(url, 'https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds&redirect_uri=oob&response_type=code&client_id=clientId&access_type=offline')\n url = token.generate_authorize_url('https://www.example.com/redirect', 'token')\n self.assertEqual(url, 'https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds&redirect_uri=https%3A%2F%2Fwww.example.com%2Fredirect&response_type=token&client_id=clientId&access_type=offline')\n url = token.generate_authorize_url(access_type='online')\n self.assertEqual(url, 'https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds&redirect_uri=oob&response_type=code&client_id=clientId&access_type=online')\n", "method_code": " def generate_authorize_url(self, redirect_uri='oob', response_type='code', **kwargs):\n \"\"\"Returns a URI to redirect to the provider.\n \n Args:\n redirect_uri: string, Either the string 'oob' for a non-web-based\n application, or a URI that handles the callback from\n the authorization server.\n response_type: string, Either the string 'code' for server-side or\n native application, or the string 'token' for client-\n side application.\n \n If redirect_uri is 'oob' then pass in the\n generated verification code to get_access_token,\n otherwise pass in the query parameters received\n at the callback uri to get_access_token.\n If the response_type is 'token', no need to call\n get_access_token as the API will return it within\n the query parameters received at the callback:\n oauth2_token.access_token = YOUR_ACCESS_TOKEN\n \"\"\"\n self.redirect_uri = redirect_uri\n query = {'response_type': response_type, 'client_id': self.client_id, 'redirect_uri': redirect_uri, 'scope': self.scope}\n query.update(kwargs)\n parts = list(urlparse.urlparse(self.auth_uri))\n query.update(dict(parse_qsl(parts[4])))\n parts[4] = urllib.urlencode(query)\n return urlparse.urlunparse(parts)\n ", "context": "class OAuth2Token(object):\n def generate_authorize_url(self, redirect_uri='oob', response_type='code', **kwargs): ...\n def __init__(self, client_id, client_secret, scope, user_agent, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', access_token=None, refresh_token=None): ...\n def invalid(self): ...\n def _refresh(self, request): ...\n def _extract_tokens(self, body): ...\n def get_access_token(self, code): ...\n def authorize(self, client): ...\n def modify_request(self, http_request): ...\n\n self.client_id = client_id\n self.client_secret = client_secret\n self.scope = scope\n self.user_agent = user_agent\n self.auth_uri = auth_uri\n self.token_uri = token_uri\n self.access_token = access_token\n self.refresh_token = refresh_token\n self._invalid = False\n\n ModifyRequest = modify_request\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_generate_authorize_url", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002226.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "generate_auth_header", "tests": "import unittest\n\nclass Test_generate_auth_header(unittest.TestCase):\n def test_generate_auth_header(self):\n header = gdata.gauth.generate_auth_header('consumerkey', 1234567890, 'mynonce', 'unknown_sig_type', 'sig')\n self.assert_(header.startswith('OAuth'))\n self.assert_(header.find('oauth_nonce=\"mynonce\"') > -1)\n self.assert_(header.find('oauth_timestamp=\"1234567890\"') > -1)\n self.assert_(header.find('oauth_consumer_key=\"consumerkey\"') > -1)\n self.assert_(header.find('oauth_signature_method=\"unknown_sig_type\"') > -1)\n self.assert_(header.find('oauth_version=\"1.0\"') > -1)\n self.assert_(header.find('oauth_signature=\"sig\"') > -1)\n header = gdata.gauth.generate_auth_header('consumer/key', 1234567890, 'ab%&33', '', 'ab/+-_=')\n self.assert_(header.find('oauth_nonce=\"ab%25%2633\"') > -1)\n self.assert_(header.find('oauth_consumer_key=\"consumer%2Fkey\"') > -1)\n self.assert_(header.find('oauth_signature_method=\"\"') > -1)\n self.assert_(header.find('oauth_signature=\"ab%2F%2B-_%3D\"') > -1)\n", "method_code": "def generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None):\n \"\"\"Builds the Authorization header to be sent in the request.\n\n Args:\n consumer_key: Identifies the application making the request (str).\n timestamp:\n nonce:\n signature_type: One of either HMAC_SHA1 or RSA_SHA1\n signature: The HMAC or RSA signature for the request as a base64\n encoded string.\n version: The version of the OAuth protocol that this request is using.\n Default is '1.0'\n next: The URL of the page that the user's browser should be sent to\n after they authorize the token. (Optional)\n token: str The OAuth token value to be used in the oauth_token parameter\n of the header.\n verifier: str The OAuth verifier which must be included when you are\n upgrading a request token to an access token.\n \"\"\"\n params = {'oauth_consumer_key': consumer_key, 'oauth_version': version, 'oauth_nonce': nonce, 'oauth_timestamp': str(timestamp), 'oauth_signature_method': signature_type, 'oauth_signature': signature}\n if next is not None:\n params['oauth_callback'] = str(next)\n if token is not None:\n params['oauth_token'] = token\n if verifier is not None:\n params['oauth_verifier'] = verifier\n pairs = ['%s=\"%s\"' % (k, urllib.quote(v, safe='~')) for k, v in params.iteritems()]\n return 'OAuth %s' % ', '.join(pairs)", "context": "def generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_generate_auth_header", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002227.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "generate_request_for_request_token", "tests": "import unittest\n\nclass Test_generate_request_for_request_token(unittest.TestCase):\n def test_request_hmac_request_token(self):\n request = gdata.gauth.generate_request_for_request_token('anonymous', gdata.gauth.HMAC_SHA1, ['http://www.blogger.com/feeds/', 'http://www.google.com/calendar/feeds/'], consumer_secret='anonymous')\n request_uri = str(request.uri)\n self.assert_('http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F' in request_uri)\n self.assert_('http%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F' in request_uri)\n auth_header = request.headers['Authorization']\n self.assert_('oauth_consumer_key=\"anonymous\"' in auth_header)\n self.assert_('oauth_signature_method=\"HMAC-SHA1\"' in auth_header)\n self.assert_('oauth_version=\"1.0\"' in auth_header)\n self.assert_('oauth_signature=\"' in auth_header)\n self.assert_('oauth_nonce=\"' in auth_header)\n self.assert_('oauth_timestamp=\"' in auth_header)\n\n def test_request_rsa_request_token(self):\n request = gdata.gauth.generate_request_for_request_token('anonymous', gdata.gauth.RSA_SHA1, ['http://www.blogger.com/feeds/', 'http://www.google.com/calendar/feeds/'], rsa_key=PRIVATE_TEST_KEY)\n request_uri = str(request.uri)\n self.assert_('http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F' in request_uri)\n self.assert_('http%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F' in request_uri)\n auth_header = request.headers['Authorization']\n self.assert_('oauth_consumer_key=\"anonymous\"' in auth_header)\n self.assert_('oauth_signature_method=\"RSA-SHA1\"' in auth_header)\n self.assert_('oauth_version=\"1.0\"' in auth_header)\n self.assert_('oauth_signature=\"' in auth_header)\n self.assert_('oauth_nonce=\"' in auth_header)\n self.assert_('oauth_timestamp=\"' in auth_header)\n", "method_code": "def generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'):\n \"\"\"Creates request to be sent to auth server to get an OAuth request token.\n\n Args:\n consumer_key:\n signature_type: either RSA_SHA1 or HMAC_SHA1. The rsa_key must be\n provided if the signature type is RSA but if the signature method\n is HMAC, the consumer_secret must be used.\n scopes: List of URL prefixes for the data which we want to access. For\n example, to request access to the user's Blogger and Google Calendar\n data, we would request\n ['http://www.blogger.com/feeds/',\n 'https://www.google.com/calendar/feeds/',\n 'http://www.google.com/calendar/feeds/']\n rsa_key: Only used if the signature method is RSA_SHA1.\n consumer_secret: Only used if the signature method is HMAC_SHA1.\n auth_server_url: The URL to which the token request should be directed.\n Defaults to 'https://www.google.com/accounts/OAuthGetRequestToken'.\n next: The URL of the page that the user's browser should be sent to\n after they authorize the token. (Optional)\n version: The OAuth version used by the requesting web application.\n Defaults to '1.0a'\n\n Returns:\n An atom.http_core.HttpRequest object with the URL, Authorization header\n and body filled in.\n \"\"\"\n request = atom.http_core.HttpRequest(auth_server_url, 'POST')\n if scopes:\n request.uri.query['scope'] = ' '.join(scopes)\n timestamp = str(int(time.time()))\n nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)])\n signature = None\n if signature_type == HMAC_SHA1:\n signature = generate_hmac_signature(request, consumer_key, consumer_secret, timestamp, nonce, version, next=next)\n elif signature_type == RSA_SHA1:\n signature = generate_rsa_signature(request, consumer_key, rsa_key, timestamp, nonce, version, next=next)\n else:\n return None\n request.headers['Authorization'] = generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version, next)\n request.headers['Content-Length'] = '0'\n return request", "context": "def generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_request_hmac_request_token", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002228.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "oauth_token_info_from_body", "tests": "import unittest\n\nclass Test_oauth_token_info_from_body(unittest.TestCase):\n def test_extract_token_from_body(self):\n body = 'oauth_token=4%2F5bNFM_efIu3yN-E9RrF1KfZzOAZG&oauth_token_secret=%2B4O49V9WUOkjXgpOobAtgYzy&oauth_callback_confirmed=true'\n token, secret = gdata.gauth.oauth_token_info_from_body(body)\n self.assertEqual(token, '4/5bNFM_efIu3yN-E9RrF1KfZzOAZG')\n self.assertEqual(secret, '+4O49V9WUOkjXgpOobAtgYzy')\n", "method_code": "def oauth_token_info_from_body(http_body):\n \"\"\"Exracts an OAuth request token from the server's response.\n\n Returns:\n A tuple of strings containing the OAuth token and token secret. If\n neither of these are present in the body, returns (None, None)\n \"\"\"\n token = None\n token_secret = None\n for pair in http_body.split('&'):\n if pair.startswith('oauth_token='):\n token = urllib.unquote(pair[len('oauth_token='):])\n if pair.startswith('oauth_token_secret='):\n token_secret = urllib.unquote(pair[len('oauth_token_secret='):])\n return (token, token_secret)", "context": "def oauth_token_info_from_body(http_body): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_extract_token_from_body", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002229.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "hmac_token_from_body", "tests": "import unittest\n\nclass Test_hmac_token_from_body(unittest.TestCase):\n def test_hmac_request_token_from_body(self):\n body = 'oauth_token=4%2F5bNFM_efIu3yN-E9RrF1KfZzOAZG&oauth_token_secret=%2B4O49V9WUOkjXgpOobAtgYzy&oauth_callback_confirmed=true'\n request_token = gdata.gauth.hmac_token_from_body(body, 'myKey', 'mySecret', True)\n self.assertEqual(request_token.consumer_key, 'myKey')\n self.assertEqual(request_token.consumer_secret, 'mySecret')\n self.assertEqual(request_token.token, '4/5bNFM_efIu3yN-E9RrF1KfZzOAZG')\n self.assertEqual(request_token.token_secret, '+4O49V9WUOkjXgpOobAtgYzy')\n self.assertEqual(request_token.auth_state, gdata.gauth.REQUEST_TOKEN)\n", "method_code": "def hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state):\n token_value, token_secret = oauth_token_info_from_body(http_body)\n token = OAuthHmacToken(consumer_key, consumer_secret, token_value, token_secret, auth_state)\n return token", "context": "def hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_hmac_request_token_from_body", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002230.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "rsa_token_from_body", "tests": "import unittest\n\nclass Test_rsa_token_from_body(unittest.TestCase):\n def test_rsa_request_token_from_body(self):\n body = 'oauth_token=4%2F5bNFM_efIu3yN-E9RrF1KfZzOAZG&oauth_token_secret=%2B4O49V9WUOkjXgpOobAtgYzy&oauth_callback_confirmed=true'\n request_token = gdata.gauth.rsa_token_from_body(body, 'myKey', 'rsaKey', True)\n self.assertEqual(request_token.consumer_key, 'myKey')\n self.assertEqual(request_token.rsa_private_key, 'rsaKey')\n self.assertEqual(request_token.token, '4/5bNFM_efIu3yN-E9RrF1KfZzOAZG')\n self.assertEqual(request_token.token_secret, '+4O49V9WUOkjXgpOobAtgYzy')\n self.assertEqual(request_token.auth_state, gdata.gauth.REQUEST_TOKEN)\n", "method_code": "def rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state):\n token_value, token_secret = oauth_token_info_from_body(http_body)\n token = OAuthRsaToken(consumer_key, rsa_private_key, token_value, token_secret, auth_state)\n return token", "context": "def rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_rsa_request_token_from_body", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002231.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "generate_oauth_authorization_url", "tests": "import unittest\n\nclass Test_generate_oauth_authorization_url(unittest.TestCase):\n def test_generate_authorization_url(self):\n url = gdata.gauth.generate_oauth_authorization_url('/+=aosdpikk')\n self.assert_(str(url).startswith('https://www.google.com/accounts/OAuthAuthorizeToken'))\n self.assert_('oauth_token=%2F%2B%3Daosdpikk' in str(url))\n", "method_code": "def generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL):\n \"\"\"Creates a URL for the page where the request token can be authorized.\n\n Args:\n token: str The request token from the OAuth server.\n next: str (optional) URL the user should be redirected to after granting\n access to a Google service(s). It can include url-encoded query\n parameters.\n hd: str (optional) Identifies a particular hosted domain account to be\n accessed (for example, 'mycollege.edu'). Uses 'default' to specify a\n regular Google account ('username@gmail.com').\n hl: str (optional) An ISO 639 country code identifying what language the\n approval page should be translated in (for example, 'hl=en' for\n English). The default is the user's selected language.\n btmpl: str (optional) Forces a mobile version of the approval page. The\n only accepted value is 'mobile'.\n auth_server: str (optional) The start of the token authorization web\n page. Defaults to\n 'https://www.google.com/accounts/OAuthAuthorizeToken'\n\n Returns:\n An atom.http_core.Uri pointing to the token authorization page where the\n user may allow or deny this app to access their Google data.\n \"\"\"\n uri = atom.http_core.Uri.parse_uri(auth_server)\n uri.query['oauth_token'] = token\n uri.query['hd'] = hd\n if next is not None:\n uri.query['oauth_callback'] = str(next)\n if hl is not None:\n uri.query['hl'] = hl\n if btmpl is not None:\n uri.query['btmpl'] = btmpl\n return uri", "context": "def generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_generate_authorization_url", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002232.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/gauth.py", "focal_class": null, "focal_method": "find_scopes_for_services", "tests": "import unittest\n\nclass Test_find_scopes_for_services(unittest.TestCase):\n def test_multiple_services(self):\n self.assertEqual(set(gdata.gauth.find_scopes_for_services(('jotspot', 'wise'))), set(['http://sites.google.com/feeds/', 'https://sites.google.com/feeds/', 'https://spreadsheets.google.com/feeds/']))\n", "method_code": "def find_scopes_for_services(service_names=None):\n \"\"\"Creates a combined list of scope URLs for the desired services.\n\n This method searches the AUTH_SCOPES dictionary.\n\n Args:\n service_names: list of strings (optional) Each name must be a key in the\n AUTH_SCOPES dictionary. If no list is provided (None) then\n the resulting list will contain all scope URLs in the\n AUTH_SCOPES dict.\n\n Returns:\n A list of URL strings which are the scopes needed to access these services\n when requesting a token using AuthSub or OAuth.\n \"\"\"\n result_scopes = []\n if service_names is None:\n for service_name, scopes in AUTH_SCOPES.iteritems():\n result_scopes.extend(scopes)\n else:\n for service_name in service_names:\n result_scopes.extend(AUTH_SCOPES[service_name])\n return result_scopes", "context": "def find_scopes_for_services(service_names=None): ...\ndef generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): ...\ndef get_client_login_token_string(http_body): ...\ndef get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): ...\ndef _to_uri(str_or_uri): ...\ndef generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri('https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): ...\ndef auth_sub_string_from_body(http_body): ...\ndef build_auth_sub_data(http_request, timestamp, nonce): ...\ndef generate_signature(data, rsa_key): ...\ndef build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): ...\ndef generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): ...\ndef generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): ...\ndef generate_request_for_request_token(consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): ...\ndef generate_request_for_access_token(request_token, auth_server_url=ACCESS_TOKEN_URL): ...\ndef oauth_token_info_from_body(http_body): ...\ndef hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): ...\ndef rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): ...\ndef generate_oauth_authorization_url(token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): ...\ndef oauth_token_info_from_url(url): ...\ndef authorize_request_token(request_token, url): ...\ndef upgrade_to_access_token(request_token, server_response_body): ...\ndef _join_token_parts(*args): ...\ndef _split_token_parts(blob): ...\ndef token_to_blob(token): ...\ndef token_from_blob(blob): ...\ndef dump_tokens(tokens): ...\ndef load_tokens(blob): ...\ndef find_scopes_for_services(service_names=None): ...\ndef ae_save(token, token_key): ...\ndef ae_load(token_key): ...\ndef ae_delete(token_key): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_multiple_services", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002233.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "CreateLabel", "tests": "import unittest\n\nclass Test_CreateLabel(unittest.TestCase):\n def testCreateLabel(self):\n result = self.es.CreateLabel(username, label='New label!!!')\n self.assertEquals(result['label'], 'New label!!!')\n", "method_code": " def CreateLabel(self, username, label):\n \"\"\"Create a label.\n \n Args:\n username: User to create label for.\n label: Label to create.\n \n Returns:\n A dict containing the result of the create operation.\n \"\"\"\n uri = self._serviceUrl('label', username)\n properties = {'label': label}\n return self._PostProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def CreateLabel(self, username, label): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testCreateLabel", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002234.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "CreateFilter", "tests": "import unittest\n\nclass Test_CreateFilter(unittest.TestCase):\n def testCreateFilter(self):\n result = self.es.CreateFilter(username, from_='from_foo', to='to_foo', subject='subject_foo', has_the_word='has_the_words_foo', does_not_have_the_word='doesnt_have_foo', has_attachment=True, label='label_foo', should_mark_as_read=True, should_archive=True)\n self.assertEquals(result['from'], 'from_foo')\n self.assertEquals(result['to'], 'to_foo')\n self.assertEquals(result['subject'], 'subject_foo')\n", "method_code": " def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None):\n \"\"\"Create a filter.\n \n Args:\n username: User to create filter for.\n from_: Filter from string.\n to: Filter to string.\n subject: Filter subject.\n has_the_word: Words to filter in.\n does_not_have_the_word: Words to filter out.\n has_attachment: Boolean for message having attachment.\n label: Label to apply.\n should_mark_as_read: Boolean for marking message as read.\n should_archive: Boolean for archiving message.\n \n Returns:\n A dict containing the result of the create operation.\n \"\"\"\n uri = self._serviceUrl('filter', username)\n properties = {}\n properties['from'] = from_\n properties['to'] = to\n properties['subject'] = subject\n properties['hasTheWord'] = has_the_word\n properties['doesNotHaveTheWord'] = does_not_have_the_word\n properties['hasAttachment'] = gdata.apps.service._bool2str(has_attachment)\n properties['label'] = label\n properties['shouldMarkAsRead'] = gdata.apps.service._bool2str(should_mark_as_read)\n properties['shouldArchive'] = gdata.apps.service._bool2str(should_archive)\n return self._PostProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testCreateFilter", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002235.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "CreateSendAsAlias", "tests": "import unittest\n\nclass Test_CreateSendAsAlias(unittest.TestCase):\n def testCreateSendAsAlias(self):\n result = self.es.CreateSendAsAlias(username, name='Send-as Alias', address='user2@sizzles.org', reply_to='user3@sizzles.org', make_default=True)\n self.assertEquals(result['name'], 'Send-as Alias')\n", "method_code": " def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None):\n \"\"\"Create alias to send mail as.\n \n Args:\n username: User to create alias for.\n name: Name of alias.\n address: Email address to send from.\n reply_to: Email address to reply to.\n make_default: Boolean for whether this is the new default sending alias.\n \n Returns:\n A dict containing the result of the create operation.\n \"\"\"\n uri = self._serviceUrl('sendas', username)\n properties = {}\n properties['name'] = name\n properties['address'] = address\n properties['replyTo'] = reply_to\n properties['makeDefault'] = gdata.apps.service._bool2str(make_default)\n return self._PostProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testCreateSendAsAlias", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002236.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "UpdateWebClipSettings", "tests": "import unittest\n\nclass Test_UpdateWebClipSettings(unittest.TestCase):\n def testUpdateWebClipSettings(self):\n result = self.es.UpdateWebClipSettings(username, enable=True)\n self.assertEquals(result['enable'], 'true')\n", "method_code": " def UpdateWebClipSettings(self, username, enable):\n \"\"\"Update WebClip Settings\n \n Args:\n username: User to update forwarding for.\n enable: Boolean whether to enable Web Clip.\n Returns:\n A dict containing the result of the update operation.\n \"\"\"\n uri = self._serviceUrl('webclip', username)\n properties = {}\n properties['enable'] = gdata.apps.service._bool2str(enable)\n return self._PutProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def UpdateWebClipSettings(self, username, enable): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUpdateWebClipSettings", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002237.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "UpdateForwarding", "tests": "import unittest\n\nclass Test_UpdateForwarding(unittest.TestCase):\n def testUpdateForwarding(self):\n result = self.es.UpdateForwarding(username, enable=True, forward_to='user4@sizzles.org', action=gdata.apps.emailsettings.service.KEEP)\n self.assertEquals(result['enable'], 'true')\n", "method_code": " def UpdateForwarding(self, username, enable, forward_to=None, action=None):\n \"\"\"Update forwarding settings.\n \n Args:\n username: User to update forwarding for.\n enable: Boolean whether to enable this forwarding rule.\n forward_to: Email address to forward to.\n action: Action to take after forwarding.\n \n Returns:\n A dict containing the result of the update operation.\n \"\"\"\n uri = self._serviceUrl('forwarding', username)\n properties = {}\n properties['enable'] = gdata.apps.service._bool2str(enable)\n if enable is True:\n properties['forwardTo'] = forward_to\n properties['action'] = action\n return self._PutProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUpdateForwarding", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002238.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "UpdatePop", "tests": "import unittest\n\nclass Test_UpdatePop(unittest.TestCase):\n def testUpdatePop(self):\n result = self.es.UpdatePop(username, enable=True, enable_for=gdata.apps.emailsettings.service.ALL_MAIL, action=gdata.apps.emailsettings.service.ARCHIVE)\n self.assertEquals(result['enable'], 'true')\n", "method_code": " def UpdatePop(self, username, enable, enable_for=None, action=None):\n \"\"\"Update POP3 settings.\n \n Args:\n username: User to update POP3 settings for.\n enable: Boolean whether to enable POP3.\n enable_for: Which messages to make available via POP3.\n action: Action to take after user retrieves email via POP3.\n \n Returns:\n A dict containing the result of the update operation.\n \"\"\"\n uri = self._serviceUrl('pop', username)\n properties = {}\n properties['enable'] = gdata.apps.service._bool2str(enable)\n if enable is True:\n properties['enableFor'] = enable_for\n properties['action'] = action\n return self._PutProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUpdatePop", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002239.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "UpdateImap", "tests": "import unittest\n\nclass Test_UpdateImap(unittest.TestCase):\n def testUpdateImap(self):\n result = self.es.UpdateImap(username, enable=True)\n self.assertEquals(result['enable'], 'true')\n", "method_code": " def UpdateImap(self, username, enable):\n \"\"\"Update IMAP settings.\n \n Args:\n username: User to update IMAP settings for.\n enable: Boolean whether to enable IMAP.\n \n Returns:\n A dict containing the result of the update operation.\n \"\"\"\n uri = self._serviceUrl('imap', username)\n properties = {'enable': gdata.apps.service._bool2str(enable)}\n return self._PutProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def UpdateImap(self, username, enable): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUpdateImap", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002240.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "UpdateVacation", "tests": "import unittest\n\nclass Test_UpdateVacation(unittest.TestCase):\n def testUpdateVacation(self):\n result = self.es.UpdateVacation(username, enable=True, subject='Hawaii', message='Wish you were here!', contacts_only=True)\n self.assertEquals(result['subject'], 'Hawaii')\n", "method_code": " def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None):\n \"\"\"Update vacation settings.\n \n Args:\n username: User to update vacation settings for.\n enable: Boolean whether to enable vacation responses.\n subject: Vacation message subject.\n message: Vacation message body.\n contacts_only: Boolean whether to send message only to contacts.\n \n Returns:\n A dict containing the result of the update operation.\n \"\"\"\n uri = self._serviceUrl('vacation', username)\n properties = {}\n properties['enable'] = gdata.apps.service._bool2str(enable)\n if enable is True:\n properties['subject'] = subject\n properties['message'] = message\n properties['contactsOnly'] = gdata.apps.service._bool2str(contacts_only)\n return self._PutProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUpdateVacation", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002241.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "UpdateSignature", "tests": "import unittest\n\nclass Test_UpdateSignature(unittest.TestCase):\n def testUpdateSignature(self):\n result = self.es.UpdateSignature(username, signature='Signature')\n self.assertEquals(result['signature'], 'Signature')\n", "method_code": " def UpdateSignature(self, username, signature):\n \"\"\"Update signature.\n \n Args:\n username: User to update signature for.\n signature: Signature string.\n \n Returns:\n A dict containing the result of the update operation.\n \"\"\"\n uri = self._serviceUrl('signature', username)\n properties = {'signature': signature}\n return self._PutProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def UpdateSignature(self, username, signature): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateLanguage(self, username, language): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUpdateSignature", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002242.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "UpdateLanguage", "tests": "import unittest\n\nclass Test_UpdateLanguage(unittest.TestCase):\n def testUpdateLanguage(self):\n result = self.es.UpdateLanguage(username, language='fr')\n self.assertEquals(result['language'], 'fr')\n", "method_code": " def UpdateLanguage(self, username, language):\n \"\"\"Update user interface language.\n \n Args:\n username: User to update language for.\n language: Language code.\n \n Returns:\n A dict containing the result of the update operation.\n \"\"\"\n uri = self._serviceUrl('language', username)\n properties = {'language': language}\n return self._PutProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def UpdateLanguage(self, username, language): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUpdateLanguage", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002243.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/apps/emailsettings/service.py", "focal_class": null, "focal_method": "UpdateGeneral", "tests": "import unittest\n\nclass Test_UpdateGeneral(unittest.TestCase):\n def testUpdateGeneral(self):\n result = self.es.UpdateGeneral(username, page_size=100, shortcuts=True, arrows=True, snippets=True, unicode=True)\n self.assertEquals(result['pageSize'], '100')\n", "method_code": " def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None):\n \"\"\"Update general settings.\n \n Args:\n username: User to update general settings for.\n page_size: Number of messages to show.\n shortcuts: Boolean whether shortcuts are enabled.\n arrows: Boolean whether arrows are enabled.\n snippets: Boolean whether snippets are enabled.\n unicode: Wheter unicode is enabled.\n \n Returns:\n A dict containing the result of the update operation.\n \"\"\"\n uri = self._serviceUrl('general', username)\n properties = {}\n if page_size != None:\n properties['pageSize'] = str(page_size)\n if shortcuts != None:\n properties['shortcuts'] = gdata.apps.service._bool2str(shortcuts)\n if arrows != None:\n properties['arrows'] = gdata.apps.service._bool2str(arrows)\n if snippets != None:\n properties['snippets'] = gdata.apps.service._bool2str(snippets)\n if unicode != None:\n properties['unicode'] = gdata.apps.service._bool2str(unicode)\n return self._PutProperties(uri, properties)\n ", "context": "class EmailSettingsService(gdata.apps.service.PropertyService):\n def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): ...\n def _serviceUrl(self, setting_id, username, domain=None): ...\n def CreateLabel(self, username, label): ...\n def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): ...\n def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): ...\n def UpdateWebClipSettings(self, username, enable): ...\n def UpdateForwarding(self, username, enable, forward_to=None, action=None): ...\n def UpdatePop(self, username, enable, enable_for=None, action=None): ...\n def UpdateImap(self, username, enable): ...\n def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): ...\n def UpdateSignature(self, username, signature): ...\n def UpdateLanguage(self, username, language): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testUpdateGeneral", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002244.py"} {"focal_file": "gdata-2.0.17/src/gdata/blogger/client.py", "focal_class": null, "focal_method": "delete", "tests": "import unittest\n\nclass Test_delete(unittest.TestCase):\n def test_create_update_delete(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_cache(self.client, 'test_create_update_delete')\n created = self.client.add_post(conf.options.get_value('blogid'), 'test post from BloggerClientTest', 'Hey look, another test!', labels=['test', 'python'])\n self.assertEqual(created.title.text, 'test post from BloggerClientTest')\n self.assertEqual(created.content.text, 'Hey look, another test!')\n self.assertEqual(len(created.category), 2)\n self.assert_(created.control is None)\n created.title.text = 'Edited'\n updated = self.client.update(created)\n self.assertEqual(updated.title.text, 'Edited')\n self.assert_(isinstance(updated, gdata.blogger.data.BlogPost))\n self.assertEqual(updated.content.text, created.content.text)\n self.client.delete(updated)\n", "method_code": " def delete(self, entry_or_uri, auth_token=None, **kwargs):\n if isinstance(entry_or_uri, (str, unicode, atom.http_core.Uri)):\n return gdata.client.GDClient.delete(self, entry_or_uri, auth_token=auth_token, **kwargs)\n old_etag = entry_or_uri.etag\n entry_or_uri.etag = None\n response = gdata.client.GDClient.delete(self, entry_or_uri, auth_token=auth_token, **kwargs)\n entry_or_uri.etag = old_etag\n return response\n ", "context": "class BloggerClient(gdata.client.GDClient):\n def delete(self, entry_or_uri, auth_token=None, **kwargs): ...\n def get_blogs(self, user_id='default', auth_token=None, desired_class=gdata.blogger.data.BlogFeed, **kwargs): ...\n def get_posts(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.BlogPostFeed, query=None, **kwargs): ...\n def get_pages(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.BlogPageFeed, query=None, **kwargs): ...\n def get_post_comments(self, blog_id, post_id, auth_token=None, desired_class=gdata.blogger.data.CommentFeed, query=None, **kwargs): ...\n def get_blog_comments(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.CommentFeed, query=None, **kwargs): ...\n def get_blog_archive(self, blog_id, auth_token=None, **kwargs): ...\n def add_post(self, blog_id, title, body, labels=None, draft=False, auth_token=None, title_type='text', body_type='html', **kwargs): ...\n def add_page(self, blog_id, title, body, draft=False, auth_token=None, title_type='text', body_type='html', **kwargs): ...\n def add_comment(self, blog_id, post_id, body, auth_token=None, title_type='text', body_type='html', **kwargs): ...\n def update(self, entry, auth_token=None, **kwargs): ...\n\n api_version = '2'\n auth_service = 'blogger'\n auth_scopes = gdata.gauth.AUTH_SCOPES['blogger']\n GetBlogs = get_blogs\n GetPosts = get_posts\n GetPages = get_pages\n GetPostComments = get_post_comments\n GetBlogComments = get_blog_comments\n GetBlogArchive = get_blog_archive\n AddPost = add_post\n AddPage = add_page\n AddComment = add_comment\n Update = update\n Delete = delete\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_create_update_delete", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002245.py"} {"focal_file": "gdata-2.0.17/src/gdata/blogger/service.py", "focal_class": null, "focal_method": "AddComment", "tests": "import unittest\n\nclass Test_AddComment(unittest.TestCase):\n def testAddComment(self):\n new_entry = gdata.blogger.BlogPostEntry(title=atom.Title(text='Comments Test Post'))\n new_entry.content = atom.Content('text', None, 'Hello Comments')\n target_post = self.client.AddPost(new_entry, blog_id=test_blog_id)\n blog_id = target_post.GetBlogId()\n post_id = target_post.GetPostId()\n new_comment = gdata.blogger.CommentEntry()\n new_comment.content = atom.Content(text='Test comment')\n posted = self.client.AddComment(new_comment, blog_id=blog_id, post_id=post_id)\n self.assertEquals(posted.content.text, new_comment.content.text)\n self.client.DeletePost(entry=target_post)\n", "method_code": " def AddComment(self, comment_entry, blog_id=None, post_id=None, uri=None):\n \"\"\"Adds a new comment to the specified blog post.\"\"\"\n if blog_id and post_id:\n uri = '/feeds/%s/%s/comments/default' % (blog_id, post_id)\n return self.Post(comment_entry, uri, converter=gdata.blogger.CommentEntryFromString)\n ", "context": "class BloggerService(gdata.service.GDataService):\n def AddComment(self, comment_entry, blog_id=None, post_id=None, uri=None): ...\n def __init__(self, email=None, password=None, source=None, server='www.blogger.com', **kwargs): ...\n def GetBlogFeed(self, uri=None): ...\n def GetBlogCommentFeed(self, blog_id=None, uri=None): ...\n def GetBlogPostFeed(self, blog_id=None, uri=None): ...\n def GetPostCommentFeed(self, blog_id=None, post_id=None, uri=None): ...\n def AddPost(self, entry, blog_id=None, uri=None): ...\n def UpdatePost(self, entry, uri=None): ...\n def DeletePost(self, entry=None, uri=None): ...\n def DeleteComment(self, entry=None, uri=None): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testAddComment", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002246.py"} {"focal_file": "gdata-2.0.17/src/gdata/contacts/service.py", "focal_class": null, "focal_method": "GetContactsFeed", "tests": "import unittest\n\nclass Test_GetContactsFeed(unittest.TestCase):\n def testGetContactsFeed(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_service_cache(self.gd_client, 'testGetContactsFeed')\n feed = self.gd_client.GetContactsFeed()\n self.assert_(isinstance(feed, gdata.contacts.ContactsFeed))\n", "method_code": " def GetContactsFeed(self, uri=None):\n uri = uri or self.GetFeedUri()\n return self.Get(uri, converter=gdata.contacts.ContactsFeedFromString)\n ", "context": "class ContactsService(gdata.service.GDataService):\n def GetContactsFeed(self, uri=None): ...\n def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None, contact_list='default', **kwargs): ...\n def GetFeedUri(self, kind='contacts', contact_list=None, projection='full', scheme=None): ...\n def GetContact(self, uri): ...\n def CreateContact(self, new_contact, insert_uri=None, url_params=None, escape_params=True): ...\n def UpdateContact(self, edit_uri, updated_contact, url_params=None, escape_params=True): ...\n def DeleteContact(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): ...\n def GetGroupsFeed(self, uri=None): ...\n def CreateGroup(self, new_group, insert_uri=None, url_params=None, escape_params=True): ...\n def UpdateGroup(self, edit_uri, updated_group, url_params=None, escape_params=True): ...\n def DeleteGroup(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): ...\n def ChangePhoto(self, media, contact_entry_or_url, content_type=None, content_length=None): ...\n def GetPhoto(self, contact_entry_or_url): ...\n def DeletePhoto(self, contact_entry_or_url): ...\n def GetProfilesFeed(self, uri=None): ...\n def GetProfile(self, uri): ...\n def UpdateProfile(self, edit_uri, updated_profile, url_params=None, escape_params=True): ...\n def ExecuteBatch(self, batch_feed, url, converter=gdata.contacts.ContactsFeedFromString): ...\n def ExecuteBatchProfiles(self, batch_feed, url, converter=gdata.contacts.ProfilesFeedFromString): ...\n def _CleanUri(self, uri): ...\n\n self.contact_list = contact_list\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetContactsFeed", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002247.py"} {"focal_file": "gdata-2.0.17/src/gdata/contacts/service.py", "focal_class": null, "focal_method": "GetFeedUri", "tests": "import unittest\n\nclass Test_GetFeedUri(unittest.TestCase):\n def testGetFeedUriDefault(self):\n self.gd_client.contact_list = 'domain.com'\n self.assertEquals('/m8/feeds/contacts/domain.com/full', self.gd_client.GetFeedUri())\n\n def testGetFeedUriCustom(self):\n uri = self.gd_client.GetFeedUri(kind='groups', contact_list='example.com', projection='base/batch', scheme='https')\n self.assertEquals('https://www.google.com/m8/feeds/groups/example.com/base/batch', uri)\n", "method_code": " def GetFeedUri(self, kind='contacts', contact_list=None, projection='full', scheme=None):\n \"\"\"Builds a feed URI.\n \n Args:\n kind: The type of feed to return, typically 'groups' or 'contacts'.\n Default value: 'contacts'.\n contact_list: The contact list to return a feed for.\n Default value: self.contact_list.\n projection: The projection to apply to the feed contents, for example\n 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.\n scheme: The URL scheme such as 'http' or 'https', None to return a\n relative URI without hostname.\n \n Returns:\n A feed URI using the given kind, contact list, and projection.\n Example: '/m8/feeds/contacts/default/full'.\n \"\"\"\n contact_list = contact_list or self.contact_list\n if kind == 'profiles':\n contact_list = 'domain/%s' % contact_list\n prefix = scheme and '%s://%s' % (scheme, self.server) or ''\n return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection)\n ", "context": "class ContactsService(gdata.service.GDataService):\n def GetFeedUri(self, kind='contacts', contact_list=None, projection='full', scheme=None): ...\n def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None, contact_list='default', **kwargs): ...\n def GetContactsFeed(self, uri=None): ...\n def GetContact(self, uri): ...\n def CreateContact(self, new_contact, insert_uri=None, url_params=None, escape_params=True): ...\n def UpdateContact(self, edit_uri, updated_contact, url_params=None, escape_params=True): ...\n def DeleteContact(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): ...\n def GetGroupsFeed(self, uri=None): ...\n def CreateGroup(self, new_group, insert_uri=None, url_params=None, escape_params=True): ...\n def UpdateGroup(self, edit_uri, updated_group, url_params=None, escape_params=True): ...\n def DeleteGroup(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): ...\n def ChangePhoto(self, media, contact_entry_or_url, content_type=None, content_length=None): ...\n def GetPhoto(self, contact_entry_or_url): ...\n def DeletePhoto(self, contact_entry_or_url): ...\n def GetProfilesFeed(self, uri=None): ...\n def GetProfile(self, uri): ...\n def UpdateProfile(self, edit_uri, updated_profile, url_params=None, escape_params=True): ...\n def ExecuteBatch(self, batch_feed, url, converter=gdata.contacts.ContactsFeedFromString): ...\n def ExecuteBatchProfiles(self, batch_feed, url, converter=gdata.contacts.ProfilesFeedFromString): ...\n def _CleanUri(self, uri): ...\n\n self.contact_list = contact_list\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetFeedUriDefault", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002248.py"} {"focal_file": "gdata-2.0.17/src/gdata/contacts/service.py", "focal_class": null, "focal_method": "DeleteGroup", "tests": "import unittest\n\nclass Test_DeleteGroup(unittest.TestCase):\n def testCreateUpdateDeleteGroup(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_service_cache(self.gd_client, 'testCreateUpdateDeleteGroup')\n test_group = gdata.contacts.GroupEntry(title=atom.Title(text='test group py'))\n new_group = self.gd_client.CreateGroup(test_group)\n self.assert_(isinstance(new_group, gdata.contacts.GroupEntry))\n self.assertEquals(new_group.title.text, 'test group py')\n new_group.title.text = 'new group name py'\n updated_group = self.gd_client.UpdateGroup(new_group.GetEditLink().href, new_group)\n self.assertEquals(updated_group.title.text, new_group.title.text)\n self.gd_client.DeleteGroup(updated_group.GetEditLink().href)\n", "method_code": " def DeleteGroup(self, edit_uri, extra_headers=None, url_params=None, escape_params=True):\n return self.Delete(self._CleanUri(edit_uri), url_params=url_params, escape_params=escape_params)\n ", "context": "class ContactsService(gdata.service.GDataService):\n def DeleteGroup(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): ...\n def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None, contact_list='default', **kwargs): ...\n def GetFeedUri(self, kind='contacts', contact_list=None, projection='full', scheme=None): ...\n def GetContactsFeed(self, uri=None): ...\n def GetContact(self, uri): ...\n def CreateContact(self, new_contact, insert_uri=None, url_params=None, escape_params=True): ...\n def UpdateContact(self, edit_uri, updated_contact, url_params=None, escape_params=True): ...\n def DeleteContact(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): ...\n def GetGroupsFeed(self, uri=None): ...\n def CreateGroup(self, new_group, insert_uri=None, url_params=None, escape_params=True): ...\n def UpdateGroup(self, edit_uri, updated_group, url_params=None, escape_params=True): ...\n def ChangePhoto(self, media, contact_entry_or_url, content_type=None, content_length=None): ...\n def GetPhoto(self, contact_entry_or_url): ...\n def DeletePhoto(self, contact_entry_or_url): ...\n def GetProfilesFeed(self, uri=None): ...\n def GetProfile(self, uri): ...\n def UpdateProfile(self, edit_uri, updated_profile, url_params=None, escape_params=True): ...\n def ExecuteBatch(self, batch_feed, url, converter=gdata.contacts.ContactsFeedFromString): ...\n def ExecuteBatchProfiles(self, batch_feed, url, converter=gdata.contacts.ProfilesFeedFromString): ...\n def _CleanUri(self, uri): ...\n\n self.contact_list = contact_list\n", "repository": "bigsnarfdude/webscraping", "test_name": "testCreateUpdateDeleteGroup", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002249.py"} {"focal_file": "gdata-2.0.17/samples/apps/marketplace_sample/gdata/__init__.py", "focal_class": null, "focal_method": "GetSelfLink", "tests": "import unittest\n\nclass Test_GetSelfLink(unittest.TestCase):\n def testGetRevisionBySelfLink(self):\n if self.resource_type != 'collection':\n revisions = self.client.GetRevisions(self.resource)\n entry = revisions.entry[0]\n new_entry = self.client.GetRevisionBySelfLink(entry.GetSelfLink().href)\n self.assertEqual(entry.GetSelfLink().href, new_entry.GetSelfLink().href)\n self.assertEqual(entry.title.text, new_entry.title.text)\n", "method_code": " def GetSelfLink(self):\n \"\"\"Find the first link with rel set to 'self'\n \n Returns:\n An atom.Link or none if none of the links had rel equal to 'self'\n \"\"\"\n for a_link in self.link:\n if a_link.rel == 'self':\n return a_link\n return None\n ", "context": "class LinkFinder(atom.LinkFinder):\n def GetSelfLink(self): ...\n def GetEditLink(self): ...\n def GetEditMediaLink(self): ...\n def GetHtmlLink(self): ...\n def GetPostLink(self): ...\n def GetAclLink(self): ...\n def GetFeedLink(self): ...\n def GetNextLink(self): ...\n def GetPrevLink(self): ...\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetRevisionBySelfLink", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002250.py"} {"focal_file": "gdata-2.0.17/src/gdata/health/service.py", "focal_class": null, "focal_method": "GetProfileListFeed", "tests": "import unittest\n\nclass Test_GetProfileListFeed(unittest.TestCase):\n def testGetProfileListFeed(self):\n self.assert_(isinstance(self.profile_list_feed, gdata.health.ProfileListFeed))\n self.assertEqual(self.profile_list_feed.id.text, 'https://www.google.com/h9/feeds/profile/list')\n first_entry = self.profile_list_feed.entry[0]\n self.assert_(isinstance(first_entry, gdata.health.ProfileListEntry))\n self.assert_(first_entry.GetProfileId() is not None)\n self.assert_(first_entry.GetProfileName() is not None)\n query = gdata.health.service.HealthProfileListQuery()\n profile_list = self.h9.GetProfileListFeed(query)\n self.assertEqual(first_entry.GetProfileId(), profile_list.entry[0].GetProfileId())\n self.assertEqual(profile_list.id.text, 'https://www.google.com/h9/feeds/profile/list')\n", "method_code": " def GetProfileListFeed(self, query=None):\n \"\"\"Fetches the users Google Health profile feed.\n \n Args:\n query: HealthProfileListQuery or string (optional) A query to use\n on the profile list feed. If None, a HealthProfileListQuery is\n constructed to /health/feeds/profile/list or /h9/feeds/profile/list.\n \n Returns:\n A gdata.health.ProfileListFeed object containing the user's list\n of profiles.\n \"\"\"\n if not query:\n uri = HealthProfileListQuery(service=self.__get_service()).ToUri()\n elif isinstance(query, HealthProfileListQuery):\n uri = query.ToUri()\n else:\n uri = query\n return self.GetFeed(uri, converter=gdata.health.ProfileListFeedFromString)\n ", "context": "class HealthService(gdata.service.GDataService):\n def GetProfileListFeed(self, query=None): ...\n def __init__(self, email=None, password=None, source=None, use_h9_sandbox=False, server='www.google.com', additional_headers=None, **kwargs): ...\n def __get_service(self): ...\n def GetProfileFeed(self, query=None, profile_id=None): ...\n def SendNotice(self, subject, body=None, content_type='html', ccr=None, profile_id=None): ...\n\n self.ssl = True\n self.use_h9_sandbox = use_h9_sandbox\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetProfileListFeed", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002251.py"} {"focal_file": "gdata-2.0.17/src/gdata/health/service.py", "focal_class": null, "focal_method": "GetProfileFeed", "tests": "import unittest\n\nclass Test_GetProfileFeed(unittest.TestCase):\n def testGetProfileFeed(self):\n feed = self.h9.GetProfileFeed(profile_id=self.profile_id)\n self.assert_(isinstance(feed, gdata.health.ProfileFeed))\n self.assert_(feed.entry[0].ccr is not None)\n\n def testGetProfileFeedByQuery(self):\n query = gdata.health.service.HealthProfileQuery(service='h9', projection='ui', profile_id=self.profile_id)\n feed = self.h9.GetProfileFeed(query=query)\n self.assert_(isinstance(feed, gdata.health.ProfileFeed))\n self.assert_(feed.entry[0].ccr is not None)\n\n def testGetProfileDigestFeed(self):\n query = gdata.health.service.HealthProfileQuery(projection='ui', profile_id=self.profile_id, params={'digest': 'true'})\n feed = self.health.GetProfileFeed(query=query)\n self.assertEqual(len(feed.entry), 1)\n", "method_code": " def GetProfileFeed(self, query=None, profile_id=None):\n \"\"\"Fetches the users Google Health profile feed.\n \n Args:\n query: HealthProfileQuery or string (optional) A query to use on the\n profile feed. If None, a HealthProfileQuery is constructed.\n profile_id: string (optional) The profile id to query the profile feed\n with when using ClientLogin. Note: this parameter is ignored if\n query is set.\n \n Returns:\n A gdata.health.ProfileFeed object containing the user's Health profile.\n \"\"\"\n if query is None:\n projection = profile_id and 'ui' or 'default'\n uri = HealthProfileQuery(service=self.__get_service(), projection=projection, profile_id=profile_id).ToUri()\n elif isinstance(query, HealthProfileQuery):\n uri = query.ToUri()\n else:\n uri = query\n return self.GetFeed(uri, converter=gdata.health.ProfileFeedFromString)\n ", "context": "class HealthService(gdata.service.GDataService):\n def GetProfileFeed(self, query=None, profile_id=None): ...\n def __init__(self, email=None, password=None, source=None, use_h9_sandbox=False, server='www.google.com', additional_headers=None, **kwargs): ...\n def __get_service(self): ...\n def GetProfileListFeed(self, query=None): ...\n def SendNotice(self, subject, body=None, content_type='html', ccr=None, profile_id=None): ...\n\n self.ssl = True\n self.use_h9_sandbox = use_h9_sandbox\n", "repository": "bigsnarfdude/webscraping", "test_name": "testGetProfileFeed", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002252.py"} {"focal_file": "gdata-2.0.17/src/gdata/health/service.py", "focal_class": null, "focal_method": "SendNotice", "tests": "import unittest\n\nclass Test_SendNotice(unittest.TestCase):\n def testSendNotice(self):\n subject_line = 'subject line'\n body = 'Notice body.'\n ccr_xml = test_data.HEALTH_CCR_NOTICE_PAYLOAD\n created_entry = self.h9.SendNotice(subject_line, body, ccr=ccr_xml, profile_id=self.profile_id)\n self.assertEqual(created_entry.title.text, subject_line)\n self.assertEqual(created_entry.content.text, body)\n self.assertEqual(created_entry.content.type, 'html')\n problem = created_entry.ccr.GetProblems()[0]\n problem_desc = problem.FindChildren('Description')[0]\n name = problem_desc.FindChildren('Text')[0]\n self.assertEqual(name.text, 'Aortic valve disorders')\n", "method_code": " def SendNotice(self, subject, body=None, content_type='html', ccr=None, profile_id=None):\n \"\"\"Sends (posts) a notice to the user's Google Health profile.\n \n Args:\n subject: A string representing the message's subject line.\n body: string (optional) The message body.\n content_type: string (optional) The content type of the notice message\n body. This parameter is only honored when a message body is\n specified.\n ccr: string (optional) The CCR XML document to reconcile into the\n user's profile.\n profile_id: string (optional) The profile id to work with when using\n ClientLogin. Note: this parameter is ignored if query is set.\n \n Returns:\n A gdata.health.ProfileEntry object of the posted entry.\n \"\"\"\n if body:\n content = atom.Content(content_type=content_type, text=body)\n else:\n content = body\n entry = gdata.GDataEntry(title=atom.Title(text=subject), content=content, extension_elements=[atom.ExtensionElementFromString(ccr)])\n projection = profile_id and 'ui' or 'default'\n query = HealthRegisterQuery(service=self.__get_service(), projection=projection, profile_id=profile_id)\n return self.Post(entry, query.ToUri(), converter=gdata.health.ProfileEntryFromString)\n ", "context": "class HealthService(gdata.service.GDataService):\n def SendNotice(self, subject, body=None, content_type='html', ccr=None, profile_id=None): ...\n def __init__(self, email=None, password=None, source=None, use_h9_sandbox=False, server='www.google.com', additional_headers=None, **kwargs): ...\n def __get_service(self): ...\n def GetProfileFeed(self, query=None, profile_id=None): ...\n def GetProfileListFeed(self, query=None): ...\n\n self.ssl = True\n self.use_h9_sandbox = use_h9_sandbox\n", "repository": "bigsnarfdude/webscraping", "test_name": "testSendNotice", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002253.py"} {"focal_file": "gdata-2.0.17/src/gdata/projecthosting/client.py", "focal_class": null, "focal_method": "update_issue", "tests": "import unittest\n\nclass Test_update_issue(unittest.TestCase):\n def test_create_update_close(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_cache(self.client, 'test_create_update_delete')\n created = self.create_issue()\n issue_id = created.id.text.split('/')[-1]\n update_response = self.client.update_issue(self.project_name, issue_id, self.owner, comment='My comment here.', summary='New Summary', status='Accepted', owner=self.assignee, labels=['-label0', 'label1'], ccs=[self.owner])\n updates = update_response.updates\n self.assertEqual(update_response.content.text, 'My comment here.')\n self.assertEqual(updates.summary.text, 'New Summary')\n self.assertEqual(updates.status.text, 'Accepted')\n self.assertEquals(len(updates.label), 2)\n self.assertEquals(updates.label[0].text, '-label0')\n self.assertEquals(updates.label[1].text, 'label1')\n self.assertEquals(len(updates.ccUpdate), 1)\n self.assert_(updates.ownerUpdate.text)\n", "method_code": " def update_issue(self, project_name, issue_id, author, comment=None, summary=None, status=None, owner=None, labels=None, ccs=None, **kwargs):\n \"\"\"Update or comment on one issue for the project.\n \n Args:\n project_name str The name of the issue's project.\n issue_id str The issue number needing updated.\n author str The authenticated user's username.\n comment str A comment to append to the issue\n summary str Rewrite the summary of the issue.\n status str A new status for the issue.\n owner str The username of the new owner.\n labels [str] Labels to set on the issue (prepend issue with - to remove a\n label).\n ccs [str] Ccs to set on th enew issue (prepend cc with - to remove a cc).\n \n Returns:\n data.CommentEntry\n \"\"\"\n updates = gdata.projecthosting.data.Updates()\n if summary:\n updates.summary = gdata.projecthosting.data.Summary(text=summary)\n if status:\n updates.status = gdata.projecthosting.data.Status(text=status)\n if owner:\n updates.ownerUpdate = gdata.projecthosting.data.OwnerUpdate(text=owner)\n if labels:\n updates.label = [gdata.projecthosting.data.Label(text=label) for label in labels]\n if ccs:\n updates.ccUpdate = [gdata.projecthosting.data.CcUpdate(text=cc) for cc in ccs]\n update_entry = gdata.projecthosting.data.CommentEntry(content=atom.data.Content(text=comment), author=[atom.data.Author(name=atom.data.Name(text=author))], updates=updates)\n return self.post(update_entry, gdata.projecthosting.data.COMMENTS_FULL_FEED % (project_name, issue_id), **kwargs)\n ", "context": "class ProjectHostingClient(gdata.client.GDClient):\n def update_issue(self, project_name, issue_id, author, comment=None, summary=None, status=None, owner=None, labels=None, ccs=None, **kwargs): ...\n def get_issues(self, project_name, desired_class=gdata.projecthosting.data.IssuesFeed, **kwargs): ...\n def add_issue(self, project_name, title, content, author, status=None, owner=None, labels=None, ccs=None, **kwargs): ...\n def get_comments(self, project_name, issue_id, desired_class=gdata.projecthosting.data.CommentsFeed, **kwargs): ...\n def update(self, entry, auth_token=None, force=False, **kwargs): ...\n def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs): ...\n\n api_version = '1.0'\n auth_service = 'code'\n auth_scopes = gdata.gauth.AUTH_SCOPES['code']\n host = 'code.google.com'\n ssl = True\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_create_update_close", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002254.py"} {"focal_file": "gdata-2.0.17/src/gdata/projecthosting/client.py", "focal_class": "gdata.projecthosting.client.Query", "focal_method": "get_issues", "tests": "import unittest\n\nclass Test_gdata_projecthosting_client_Query_get_issues(unittest.TestCase):\n def test_get_issues(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_cache(self.client, 'test_create_update_delete')\n created = self.create_issue()\n issue_id = created.id.text.split('/')[-1]\n query = gdata.projecthosting.client.Query(label='label0')\n feed = self.client.get_issues(self.project_name, query=query)\n self.assert_(len(feed.entry) > 0)\n for issue in feed.entry:\n label_texts = [label.text for label in issue.label]\n self.assert_('label0' in label_texts, 'Issue does not have label label0')\n", "method_code": " def get_issues(self, project_name, desired_class=gdata.projecthosting.data.IssuesFeed, **kwargs):\n \"\"\"Get a feed of issues for a particular project.\n \n Args:\n project_name str The name of the project.\n query Query Set returned issues parameters.\n \n Returns:\n data.IssuesFeed\n \"\"\"\n return self.get_feed(gdata.projecthosting.data.ISSUES_FULL_FEED % project_name, desired_class=desired_class, **kwargs)\n ", "context": "class ProjectHostingClient(gdata.client.GDClient):\n def get_issues(self, project_name, desired_class=gdata.projecthosting.data.IssuesFeed, **kwargs): ...\n def add_issue(self, project_name, title, content, author, status=None, owner=None, labels=None, ccs=None, **kwargs): ...\n def update_issue(self, project_name, issue_id, author, comment=None, summary=None, status=None, owner=None, labels=None, ccs=None, **kwargs): ...\n def get_comments(self, project_name, issue_id, desired_class=gdata.projecthosting.data.CommentsFeed, **kwargs): ...\n def update(self, entry, auth_token=None, force=False, **kwargs): ...\n def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs): ...\n\n api_version = '1.0'\n auth_service = 'code'\n auth_scopes = gdata.gauth.AUTH_SCOPES['code']\n host = 'code.google.com'\n ssl = True\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_get_issues", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002255.py"} {"focal_file": "gdata-2.0.17/src/gdata/projecthosting/client.py", "focal_class": null, "focal_method": "get_comments", "tests": "import unittest\n\nclass Test_get_comments(unittest.TestCase):\n def test_get_comments(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_cache(self.client, 'test_create_update_delete')\n created = self.create_issue()\n issue_id = created.id.text.split('/')[-1]\n for i in range(2):\n update_response = self.client.update_issue(self.project_name, issue_id, self.owner, comment='My comment here %s' % i)\n comments_feed = self.client.get_comments(self.project_name, issue_id)\n self.assertEqual(2, len(comments_feed.entry))\n", "method_code": " def get_comments(self, project_name, issue_id, desired_class=gdata.projecthosting.data.CommentsFeed, **kwargs):\n \"\"\"Get a feed of all updates to an issue.\n \n Args:\n project_name str The name of the issue's project.\n issue_id str The issue number needing updated.\n \n Returns:\n data.CommentsFeed\n \"\"\"\n return self.get_feed(gdata.projecthosting.data.COMMENTS_FULL_FEED % (project_name, issue_id), desired_class=desired_class, **kwargs)\n ", "context": "class ProjectHostingClient(gdata.client.GDClient):\n def get_comments(self, project_name, issue_id, desired_class=gdata.projecthosting.data.CommentsFeed, **kwargs): ...\n def get_issues(self, project_name, desired_class=gdata.projecthosting.data.IssuesFeed, **kwargs): ...\n def add_issue(self, project_name, title, content, author, status=None, owner=None, labels=None, ccs=None, **kwargs): ...\n def update_issue(self, project_name, issue_id, author, comment=None, summary=None, status=None, owner=None, labels=None, ccs=None, **kwargs): ...\n def update(self, entry, auth_token=None, force=False, **kwargs): ...\n def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs): ...\n\n api_version = '1.0'\n auth_service = 'code'\n auth_scopes = gdata.gauth.AUTH_SCOPES['code']\n host = 'code.google.com'\n ssl = True\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_get_comments", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002256.py"} {"focal_file": "gdata-2.0.17/src/gdata/spreadsheets/data.py", "focal_class": null, "focal_method": "get_spreadsheet_key", "tests": "import unittest\n\nclass Test_get_spreadsheet_key(unittest.TestCase):\n def test_get_spreadsheet_key(self):\n self.assertEqual(self.spreadsheet.get_spreadsheet_key(), 'key')\n self.spreadsheet.id.text = '42'\n self.assertEqual(self.spreadsheet.GetSpreadsheetKey(), '42')\n", "method_code": " def get_spreadsheet_key(self):\n \"\"\"Extracts the spreadsheet key unique to this spreadsheet.\"\"\"\n return self.get_id().split('/')[-1]\n ", "context": "class Spreadsheet(gdata.data.GDEntry):\n def get_spreadsheet_key(self): ...\n def find_worksheets_feed(self): ...\n\n FindWorksheetsFeed = find_worksheets_feed\n GetSpreadsheetKey = get_spreadsheet_key\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_get_spreadsheet_key", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002257.py"} {"focal_file": "gdata-2.0.17/src/gdata/spreadsheets/data.py", "focal_class": null, "focal_method": "get_worksheet_id", "tests": "import unittest\n\nclass Test_get_worksheet_id(unittest.TestCase):\n def test_get_worksheet_id(self):\n self.assertEqual(self.worksheets.entry[0].get_worksheet_id(), '1')\n self.worksheets.entry[0].id.text = '////spam'\n self.assertEqual(self.worksheets.entry[0].GetWorksheetId(), 'spam')\n", "method_code": " def get_worksheet_id(self):\n \"\"\"The worksheet ID identifies this worksheet in its spreadsheet.\"\"\"\n return self.get_id().split('/')[-1]\n \n row_count = RowCount\n col_count = ColCount\n GetWorksheetId = get_worksheet_id\n", "context": "class WorksheetEntry(gdata.data.GDEntry):\n def get_worksheet_id(self): ...", "repository": "bigsnarfdude/webscraping", "test_name": "test_get_worksheet_id", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002258.py"} {"focal_file": "gdata-2.0.17/src/gdata/spreadsheets/data.py", "focal_class": null, "focal_method": "add_set_cell", "tests": "import unittest\n\nclass Test_add_set_cell(unittest.TestCase):\n def test_set_cell(self):\n self.feed.add_set_cell(1, 2, 'value')\n self.assertEqual(len(self.feed.entry), 1)\n self.assertEqual(self.feed.entry[0].id.text, 'https://spreadsheets.google.com/feeds/cells/skey/wid/private/full/R1C2')\n self.assertEqual(self.feed.entry[0].cell.row, '1')\n self.assertEqual(self.feed.entry[0].cell.col, '2')\n self.assertEqual(self.feed.entry[0].cell.input_value, 'value')\n self.assertEqual(self.feed.entry[0].batch_operation.type, 'update')\n self.assertEqual(self.feed.entry[0].batch_id.text, '0')\n self.feed.add_set_cell(3, 1, 'spam')\n self.assertEqual(len(self.feed.entry), 2)\n self.assertEqual(self.feed.entry[1].id.text, 'https://spreadsheets.google.com/feeds/cells/skey/wid/private/full/R3C1')\n self.assertEqual(self.feed.entry[1].cell.row, '3')\n self.assertEqual(self.feed.entry[1].cell.col, '1')\n self.assertEqual(self.feed.entry[1].cell.input_value, 'spam')\n self.assertEqual(self.feed.entry[1].batch_operation.type, 'update')\n self.assertEqual(self.feed.entry[1].batch_id.text, '1')\n", "method_code": " def add_set_cell(self, row, col, input_value):\n \"\"\"Adds a request to change the contents of a cell to this batch request.\n \n Args:\n row: int, The row number for this cell. Numbering starts at 1.\n col: int, The column number for this cell. Starts at 1.\n input_value: str, The desired formula/content this cell should contain.\n \"\"\"\n self.add_update(CellEntry(id=atom.data.Id(text=BATCH_ENTRY_ID_TEMPLATE % (self.id.text, row, col)), cell=Cell(col=str(col), row=str(row), input_value=input_value)))\n return self\n \n entry = [CellEntry]\n AddSetCell = add_set_cell\n", "context": "class CellsFeed(gdata.data.BatchFeed):\n def add_set_cell(self, row, col, input_value): ...", "repository": "bigsnarfdude/webscraping", "test_name": "test_set_cell", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002259.py"} {"focal_file": "gdata-2.0.17/src/gdata/spreadsheets/client.py", "focal_class": null, "focal_method": "add_worksheet", "tests": "import unittest\n\nclass Test_add_worksheet(unittest.TestCase):\n def test_create_update_delete_worksheet(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_cache(self.client, 'test_create_update_delete_worksheet')\n spreadsheet_id = conf.options.get_value('spreadsheetid')\n original_worksheets = self.client.get_worksheets(spreadsheet_id)\n self.assert_(isinstance(original_worksheets, gdata.spreadsheets.data.WorksheetsFeed))\n worksheet_count = int(original_worksheets.total_results.text)\n created = self.client.add_worksheet(spreadsheet_id, 'a test worksheet', 4, 8)\n self.assert_(isinstance(created, gdata.spreadsheets.data.WorksheetEntry))\n self.assertEqual(created.title.text, 'a test worksheet')\n self.assertEqual(created.row_count.text, '4')\n self.assertEqual(created.col_count.text, '8')\n updated_worksheets = self.client.get_worksheets(spreadsheet_id)\n new_worksheet_count = int(updated_worksheets.total_results.text)\n self.assertEqual(worksheet_count + 1, new_worksheet_count)\n self.client.delete(created)\n updated_worksheets = self.client.get_worksheets(spreadsheet_id)\n new_worksheet_count = int(updated_worksheets.total_results.text)\n self.assertEqual(worksheet_count, new_worksheet_count)\n", "method_code": " def add_worksheet(self, spreadsheet_key, title, rows, cols, auth_token=None, **kwargs):\n \"\"\"Creates a new worksheet entry in the spreadsheet.\n \n Args:\n spreadsheet_key: str, The unique ID of this containing spreadsheet. This\n can be the ID from the URL or as provided in a\n Spreadsheet entry.\n title: str, The title to be used in for the worksheet.\n rows: str or int, The number of rows this worksheet should start with.\n cols: str or int, The number of columns this worksheet should start with.\n auth_token: An object which sets the Authorization HTTP header in its\n modify_request method. Recommended classes include\n gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken\n among others. Represents the current user. Defaults to None\n and if None, this method will look for a value in the\n auth_token member of SpreadsheetsClient.\n \"\"\"\n new_worksheet = gdata.spreadsheets.data.WorksheetEntry(title=atom.data.Title(text=title), row_count=gdata.spreadsheets.data.RowCount(text=str(rows)), col_count=gdata.spreadsheets.data.ColCount(text=str(cols)))\n return self.post(new_worksheet, WORKSHEETS_URL % spreadsheet_key, auth_token=auth_token, **kwargs)\n ", "context": "class SpreadsheetsClient(gdata.client.GDClient):\n def add_worksheet(self, spreadsheet_key, title, rows, cols, auth_token=None, **kwargs): ...\n def get_spreadsheets(self, auth_token=None, desired_class=gdata.spreadsheets.data.SpreadsheetsFeed, **kwargs): ...\n def get_worksheets(self, spreadsheet_key, auth_token=None, desired_class=gdata.spreadsheets.data.WorksheetsFeed, **kwargs): ...\n def get_worksheet(self, spreadsheet_key, worksheet_id, desired_class=gdata.spreadsheets.data.WorksheetEntry, auth_token=None, **kwargs): ...\n def add_table(self, spreadsheet_key, title, summary, worksheet_name, header_row, num_rows, start_row, insertion_mode, column_headers, auth_token=None, **kwargs): ...\n def get_tables(self, spreadsheet_key, desired_class=gdata.spreadsheets.data.TablesFeed, auth_token=None, **kwargs): ...\n def add_record(self, spreadsheet_key, table_id, fields, title=None, auth_token=None, **kwargs): ...\n def get_records(self, spreadsheet_key, table_id, desired_class=gdata.spreadsheets.data.RecordsFeed, auth_token=None, **kwargs): ...\n def get_record(self, spreadsheet_key, table_id, record_id, desired_class=gdata.spreadsheets.data.Record, auth_token=None, **kwargs): ...\n def get_cells(self, spreadsheet_key, worksheet_id, desired_class=gdata.spreadsheets.data.CellsFeed, auth_token=None, **kwargs): ...\n def get_cell(self, spreadsheet_key, worksheet_id, row_num, col_num, desired_class=gdata.spreadsheets.data.CellEntry, auth_token=None, **kwargs): ...\n def get_list_feed(self, spreadsheet_key, worksheet_id, desired_class=gdata.spreadsheets.data.ListsFeed, auth_token=None, **kwargs): ...\n def add_list_entry(self, list_entry, spreadsheet_key, worksheet_id, auth_token=None, **kwargs): ...\n\n api_version = '3'\n auth_service = 'wise'\n auth_scopes = gdata.gauth.AUTH_SCOPES['wise']\n ssl = True\n GetSpreadsheets = get_spreadsheets\n GetWorksheets = get_worksheets\n AddWorksheet = add_worksheet\n GetWorksheet = get_worksheet\n AddTable = add_table\n GetTables = get_tables\n AddRecord = add_record\n GetRecords = get_records\n GetRecord = get_record\n GetCells = get_cells\n GetCell = get_cell\n GetListFeed = get_list_feed\n AddListEntry = add_list_entry\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_create_update_delete_worksheet", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002260.py"} {"focal_file": "gdata-2.0.17/src/gdata/spreadsheets/client.py", "focal_class": null, "focal_method": "get_list_feed", "tests": "import unittest\n\nclass Test_get_list_feed(unittest.TestCase):\n def test_crud_on_list_feed(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_cache(self.client, 'test_crud_on_list_feed')\n spreadsheet_id = conf.options.get_value('spreadsheetid')\n test_worksheet = self.client.add_worksheet(spreadsheet_id, 'worksheet x', rows=30, cols=3)\n worksheet_id = test_worksheet.get_worksheet_id()\n self.set_cell(spreadsheet_id, worksheet_id, 1, 1, 'cola')\n self.set_cell(spreadsheet_id, worksheet_id, 1, 2, 'colb')\n self.set_cell(spreadsheet_id, worksheet_id, 1, 3, 'colc')\n entry = gdata.spreadsheets.data.ListEntry()\n entry.from_dict({'cola': 'alpha', 'colb': 'beta', 'colc': 'gamma'})\n added = self.client.add_list_entry(entry, spreadsheet_id, worksheet_id)\n self.assert_(isinstance(added, gdata.spreadsheets.data.ListEntry))\n self.assertEquals(added.get_value('cola'), 'alpha')\n added.from_dict({'cola': '1', 'colb': '2', 'colc': '3'})\n updated = self.client.update(added)\n self.assert_(isinstance(updated, gdata.spreadsheets.data.ListEntry))\n self.assertEquals(updated.get_value('cola'), '1')\n rows = self.client.get_list_feed(spreadsheet_id, worksheet_id)\n self.assertEquals(len(rows.entry), 1)\n self.client.delete(updated)\n rows = self.client.get_list_feed(spreadsheet_id, worksheet_id)\n self.assertEquals(len(rows.entry), 0)\n self.client.delete(test_worksheet, force=True)\n", "method_code": " def get_list_feed(self, spreadsheet_key, worksheet_id, desired_class=gdata.spreadsheets.data.ListsFeed, auth_token=None, **kwargs):\n \"\"\"Retrieves the value rows from the worksheet's list feed.\n \n The list feed is a view of the spreadsheet in which the first row is used\n for column names and subsequent rows up to the first blank line are\n records.\n \n Args:\n spreadsheet_key: str, The unique ID of this containing spreadsheet. This\n can be the ID from the URL or as provided in a\n Spreadsheet entry.\n worksheet_id: str, The unique ID of the worksheet in this spreadsheet\n whose cells we want. This can be obtained using\n WorksheetEntry's get_worksheet_id method.\n desired_class: class descended from atom.core.XmlElement to which a\n successful response should be converted. If there is no\n converter function specified (converter=None) then the\n desired_class will be used in calling the\n atom.core.parse function. If neither\n the desired_class nor the converter is specified, an\n HTTP reponse object will be returned. Defaults to\n gdata.spreadsheets.data.ListsFeed.\n auth_token: An object which sets the Authorization HTTP header in its\n modify_request method. Recommended classes include\n gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken\n among others. Represents the current user. Defaults to None\n and if None, this method will look for a value in the\n auth_token member of SpreadsheetsClient.\n \"\"\"\n return self.get_feed(LISTS_URL % (spreadsheet_key, worksheet_id), auth_token=auth_token, desired_class=desired_class, **kwargs)\n ", "context": "class SpreadsheetsClient(gdata.client.GDClient):\n def get_list_feed(self, spreadsheet_key, worksheet_id, desired_class=gdata.spreadsheets.data.ListsFeed, auth_token=None, **kwargs): ...\n def get_spreadsheets(self, auth_token=None, desired_class=gdata.spreadsheets.data.SpreadsheetsFeed, **kwargs): ...\n def get_worksheets(self, spreadsheet_key, auth_token=None, desired_class=gdata.spreadsheets.data.WorksheetsFeed, **kwargs): ...\n def add_worksheet(self, spreadsheet_key, title, rows, cols, auth_token=None, **kwargs): ...\n def get_worksheet(self, spreadsheet_key, worksheet_id, desired_class=gdata.spreadsheets.data.WorksheetEntry, auth_token=None, **kwargs): ...\n def add_table(self, spreadsheet_key, title, summary, worksheet_name, header_row, num_rows, start_row, insertion_mode, column_headers, auth_token=None, **kwargs): ...\n def get_tables(self, spreadsheet_key, desired_class=gdata.spreadsheets.data.TablesFeed, auth_token=None, **kwargs): ...\n def add_record(self, spreadsheet_key, table_id, fields, title=None, auth_token=None, **kwargs): ...\n def get_records(self, spreadsheet_key, table_id, desired_class=gdata.spreadsheets.data.RecordsFeed, auth_token=None, **kwargs): ...\n def get_record(self, spreadsheet_key, table_id, record_id, desired_class=gdata.spreadsheets.data.Record, auth_token=None, **kwargs): ...\n def get_cells(self, spreadsheet_key, worksheet_id, desired_class=gdata.spreadsheets.data.CellsFeed, auth_token=None, **kwargs): ...\n def get_cell(self, spreadsheet_key, worksheet_id, row_num, col_num, desired_class=gdata.spreadsheets.data.CellEntry, auth_token=None, **kwargs): ...\n def add_list_entry(self, list_entry, spreadsheet_key, worksheet_id, auth_token=None, **kwargs): ...\n\n api_version = '3'\n auth_service = 'wise'\n auth_scopes = gdata.gauth.AUTH_SCOPES['wise']\n ssl = True\n GetSpreadsheets = get_spreadsheets\n GetWorksheets = get_worksheets\n AddWorksheet = add_worksheet\n GetWorksheet = get_worksheet\n AddTable = add_table\n GetTables = get_tables\n AddRecord = add_record\n GetRecords = get_records\n GetRecord = get_record\n GetCells = get_cells\n GetCell = get_cell\n GetListFeed = get_list_feed\n AddListEntry = add_list_entry\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_crud_on_list_feed", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002261.py"} {"focal_file": "gdata-2.0.17/src/gdata/youtube/client.py", "focal_class": null, "focal_method": "get_video_entry", "tests": "import unittest\n\nclass Test_get_video_entry(unittest.TestCase):\n def test_retrieve_video_entry(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_cache(self.client, 'test_retrieve_video_entry')\n entry = self.client.get_video_entry(video_id=conf.options.get_value('videoid'))\n self.assertTrue(entry.etag)\n", "method_code": " def get_video_entry(self, uri=None, video_id=None, auth_token=None, **kwargs):\n \"\"\"Retrieve a YouTubeVideoEntry.\n \n Either a uri or a video_id must be provided.\n \n Args:\n uri: An optional string representing the URI of the entry that is to\n be retrieved.\n video_id: An optional string representing the ID of the video.\n \n Returns:\n A YouTubeVideoFeed if successfully retrieved.\n \n Raises:\n YouTubeError: You must provide at least a uri or a video_id to the\n GetYouTubeVideoEntry() method.\n \"\"\"\n if uri is None and video_id is None:\n raise YouTubeError('You must provide at least a uri or a video_id to the get_youtube_video_entry() method')\n elif video_id and uri is None:\n uri = '%s/%s' % (YOUTUBE_VIDEO_FEED_URI, video_id)\n return self.get_feed(uri, desired_class=gdata.youtube.data.VideoEntry, auth_token=auth_token, **kwargs)\n ", "context": "class YouTubeClient(gdata.client.GDClient):\n def get_video_entry(self, uri=None, video_id=None, auth_token=None, **kwargs): ...\n def get_videos(self, uri=YOUTUBE_VIDEO_FEED_URI, auth_token=None, desired_class=gdata.youtube.data.VideoFeed, **kwargs): ...\n def get_user_feed(self, uri=None, username=None): ...\n def get_caption_feed(self, uri): ...\n def get_caption_track(self, track_url, client_id, developer_key, auth_token=None, **kwargs): ...\n def create_track(self, video_id, title, language, body, client_id, developer_key, auth_token=None, title_type='text', **kwargs): ...\n def delete_track(self, video_id, track, client_id, developer_key, auth_token=None, **kwargs): ...\n def update_track(self, video_id, track, body, client_id, developer_key, auth_token=None, **kwargs): ...\n\n api_version = '2'\n auth_service = YOUTUBE_SERVICE\n auth_scopes = ['https://%s' % YOUTUBE_SERVER]\n ssl = True\n GetVideos = get_videos\n GetUserFeed = get_user_feed\n GetVideoEntry = get_video_entry\n GetCaptionFeed = get_caption_feed\n GetCaptionTrack = get_caption_track\n CreateTrack = create_track\n DeleteTrack = delete_track\n UpdateTrack = update_track\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_retrieve_video_entry", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002262.py"} {"focal_file": "gdata-2.0.17/src/gdata/youtube/client.py", "focal_class": null, "focal_method": "get_user_feed", "tests": "import unittest\n\nclass Test_get_user_feed(unittest.TestCase):\n def test_retrieve_user_feed(self):\n if not conf.options.get_value('runlive') == 'true':\n return\n conf.configure_cache(self.client, 'test_retrieve_video_has_entries')\n entries = self.client.get_user_feed(username='joegregoriotest')\n self.assertTrue(len(entries.entry) > 0)\n", "method_code": " def get_user_feed(self, uri=None, username=None):\n \"\"\"Retrieve a YouTubeVideoFeed of user uploaded videos.\n \n Either a uri or a username must be provided. This will retrieve list\n of videos uploaded by specified user. The uri will be of format\n \"http://gdata.youtube.com/feeds/api/users/{username}/uploads\".\n \n Args:\n uri: An optional string representing the URI of the user feed that is\n to be retrieved.\n username: An optional string representing the username.\n \n Returns:\n A YouTubeUserFeed if successfully retrieved.\n \n Raises:\n YouTubeError: You must provide at least a uri or a username to the\n GetYouTubeUserFeed() method.\n \"\"\"\n if uri is None and username is None:\n raise YouTubeError('You must provide at least a uri or a username to the GetYouTubeUserFeed() method')\n elif username and (not uri):\n uri = '%s%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads')\n return self.get_feed(uri, desired_class=gdata.youtube.data.VideoFeed)\n ", "context": "class YouTubeClient(gdata.client.GDClient):\n def get_user_feed(self, uri=None, username=None): ...\n def get_videos(self, uri=YOUTUBE_VIDEO_FEED_URI, auth_token=None, desired_class=gdata.youtube.data.VideoFeed, **kwargs): ...\n def get_video_entry(self, uri=None, video_id=None, auth_token=None, **kwargs): ...\n def get_caption_feed(self, uri): ...\n def get_caption_track(self, track_url, client_id, developer_key, auth_token=None, **kwargs): ...\n def create_track(self, video_id, title, language, body, client_id, developer_key, auth_token=None, title_type='text', **kwargs): ...\n def delete_track(self, video_id, track, client_id, developer_key, auth_token=None, **kwargs): ...\n def update_track(self, video_id, track, body, client_id, developer_key, auth_token=None, **kwargs): ...\n\n api_version = '2'\n auth_service = YOUTUBE_SERVICE\n auth_scopes = ['https://%s' % YOUTUBE_SERVER]\n ssl = True\n GetVideos = get_videos\n GetUserFeed = get_user_feed\n GetVideoEntry = get_video_entry\n GetCaptionFeed = get_caption_feed\n GetCaptionTrack = get_caption_track\n CreateTrack = create_track\n DeleteTrack = delete_track\n UpdateTrack = update_track\n", "repository": "bigsnarfdude/webscraping", "test_name": "test_retrieve_user_feed", "smells": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002263.py"} {"focal_file": "http-server/httplib2-0.8/python3/httplib2/__init__.py", "focal_class": null, "focal_method": "_parse_cache_control", "tests": "import unittest\n\nclass Test_parse_cache_control(unittest.TestCase):\n def testParseCacheControl(self):\n self.assertEqual({}, httplib2._parse_cache_control({}))\n self.assertEqual({'no-cache': 1}, httplib2._parse_cache_control({'cache-control': ' no-cache'}))\n cc = httplib2._parse_cache_control({'cache-control': ' no-cache, max-age = 7200'})\n self.assertEqual(cc['no-cache'], 1)\n self.assertEqual(cc['max-age'], '7200')\n cc = httplib2._parse_cache_control({'cache-control': ' , '})\n self.assertEqual(cc[''], 1)\n try:\n cc = httplib2._parse_cache_control({'cache-control': 'Max-age=3600;post-check=1800,pre-check=3600'})\n self.assertTrue('max-age' in cc)\n except:\n self.fail('Should not throw exception')\n", "method_code": "def _parse_cache_control(headers):\n retval = {}\n if 'cache-control' in headers:\n parts = headers['cache-control'].split(',')\n parts_with_args = [tuple([x.strip().lower() for x in part.split('=', 1)]) for part in parts if -1 != part.find('=')]\n parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find('=')]\n retval = dict(parts_with_args + parts_wo_args)\n return retval", "context": "def _parse_cache_control(headers): ...\ndef has_timeout(timeout): ...\ndef _get_end2end_headers(response): ...\ndef parse_uri(uri): ...\ndef urlnorm(uri): ...\ndef safename(filename): ...\ndef _normalize_headers(headers): ...\ndef _parse_cache_control(headers): ...\ndef _parse_www_authenticate(headers, headername='www-authenticate'): ...\ndef _entry_disposition(response_headers, request_headers): ...\ndef _decompressContent(response, new_content): ...\ndef _bind_write_headers(msg): ...\ndef _updateCache(request_headers, response_headers, content, cache, cachekey): ...\ndef _cnonce(): ...\ndef _wsse_username_token(cnonce, iso_now, password): ...\ndef proxy_info_from_environment(method='http'): ...\ndef proxy_info_from_url(url, method='http'): ...\n", "repository": "ZhouYii/AppProtocol", "test_name": "testParseCacheControl", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002264.py"} {"focal_file": "http-server/httplib2-0.8/python3/httplib2/__init__.py", "focal_class": null, "focal_method": "_normalize_headers", "tests": "import unittest\n\nclass Test_normalize_headers(unittest.TestCase):\n def testNormalizeHeaders(self):\n h = httplib2._normalize_headers({'Cache-Control': 'no-cache', 'Other': 'Stuff'})\n self.assertTrue('cache-control' in h)\n self.assertTrue('other' in h)\n self.assertEqual('Stuff', h['other'])\n", "method_code": "def _normalize_headers(headers):\n return dict([(key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for key, value in headers.items()])", "context": "def _normalize_headers(headers): ...\ndef has_timeout(timeout): ...\ndef _get_end2end_headers(response): ...\ndef parse_uri(uri): ...\ndef urlnorm(uri): ...\ndef safename(filename): ...\ndef _normalize_headers(headers): ...\ndef _parse_cache_control(headers): ...\ndef _parse_www_authenticate(headers, headername='www-authenticate'): ...\ndef _entry_disposition(response_headers, request_headers): ...\ndef _decompressContent(response, new_content): ...\ndef _bind_write_headers(msg): ...\ndef _updateCache(request_headers, response_headers, content, cache, cachekey): ...\ndef _cnonce(): ...\ndef _wsse_username_token(cnonce, iso_now, password): ...\ndef proxy_info_from_environment(method='http'): ...\ndef proxy_info_from_url(url, method='http'): ...\n", "repository": "ZhouYii/AppProtocol", "test_name": "testNormalizeHeaders", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002265.py"} {"focal_file": "http-server/httplib2-0.8/python3/httplib2/__init__.py", "focal_class": null, "focal_method": "_parse_www_authenticate", "tests": "import unittest\n\nclass Test_parse_www_authenticate(unittest.TestCase):\n def testParseWWWAuthenticateEmpty(self):\n res = httplib2._parse_www_authenticate({})\n self.assertEqual(len(list(res.keys())), 0)\n\n def testParseWWWAuthenticate(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Test realm=\"test realm\" , foo=foo ,bar=\"bar\", baz=baz,qux=qux'})\n self.assertEqual(len(list(res.keys())), 1)\n self.assertEqual(len(list(res['test'].keys())), 5)\n res = httplib2._parse_www_authenticate({'www-authenticate': 'T*!%#st realm=to*!%#en, to*!%#en=\"quoted string\"'})\n self.assertEqual(len(list(res.keys())), 1)\n self.assertEqual(len(list(res['t*!%#st'].keys())), 2)\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Test realm=\"a \\\\\"test\\\\\" realm\"'})\n self.assertEqual(len(list(res.keys())), 1)\n self.assertEqual(res['test']['realm'], 'a \"test\" realm')\n\n def testParseWWWAuthenticateBasic(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Basic realm=\"me\"'})\n basic = res['basic']\n self.assertEqual('me', basic['realm'])\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Basic realm=\"me\", algorithm=\"MD5\"'})\n basic = res['basic']\n self.assertEqual('me', basic['realm'])\n self.assertEqual('MD5', basic['algorithm'])\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Basic realm=\"me\", algorithm=MD5'})\n basic = res['basic']\n self.assertEqual('me', basic['realm'])\n self.assertEqual('MD5', basic['algorithm'])\n\n def testParseWWWAuthenticateBasic2(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Basic realm=\"me\",other=\"fred\" '})\n basic = res['basic']\n self.assertEqual('me', basic['realm'])\n self.assertEqual('fred', basic['other'])\n\n def testParseWWWAuthenticateBasic3(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Basic REAlm=\"me\" '})\n basic = res['basic']\n self.assertEqual('me', basic['realm'])\n\n def testParseWWWAuthenticateDigest(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Digest realm=\"testrealm@host.com\", qop=\"auth,auth-int\", nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"'})\n digest = res['digest']\n self.assertEqual('testrealm@host.com', digest['realm'])\n self.assertEqual('auth,auth-int', digest['qop'])\n\n def testParseWWWAuthenticateMultiple(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Digest realm=\"testrealm@host.com\", qop=\"auth,auth-int\", nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", opaque=\"5ccc069c403ebaf9f0171e9517f40e41\" Basic REAlm=\"me\" '})\n digest = res['digest']\n self.assertEqual('testrealm@host.com', digest['realm'])\n self.assertEqual('auth,auth-int', digest['qop'])\n self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])\n self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])\n basic = res['basic']\n self.assertEqual('me', basic['realm'])\n\n def testParseWWWAuthenticateMultiple2(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Digest realm=\"testrealm@host.com\", qop=\"auth,auth-int\", nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", opaque=\"5ccc069c403ebaf9f0171e9517f40e41\", Basic REAlm=\"me\" '})\n digest = res['digest']\n self.assertEqual('testrealm@host.com', digest['realm'])\n self.assertEqual('auth,auth-int', digest['qop'])\n self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])\n self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])\n basic = res['basic']\n self.assertEqual('me', basic['realm'])\n\n def testParseWWWAuthenticateMultiple3(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Digest realm=\"testrealm@host.com\", qop=\"auth,auth-int\", nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", opaque=\"5ccc069c403ebaf9f0171e9517f40e41\", Basic REAlm=\"me\", WSSE realm=\"foo\", profile=\"UsernameToken\"'})\n digest = res['digest']\n self.assertEqual('testrealm@host.com', digest['realm'])\n self.assertEqual('auth,auth-int', digest['qop'])\n self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])\n self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])\n basic = res['basic']\n self.assertEqual('me', basic['realm'])\n wsse = res['wsse']\n self.assertEqual('foo', wsse['realm'])\n self.assertEqual('UsernameToken', wsse['profile'])\n\n def testParseWWWAuthenticateMultiple4(self):\n res = httplib2._parse_www_authenticate({'www-authenticate': 'Digest realm=\"test-real.m@host.com\", qop \\t=\\t\"\\tauth,auth-int\", nonce=\"(*)&^&$%#\",opaque=\"5ccc069c403ebaf9f0171e9517f40e41\", Basic REAlm=\"me\", WSSE realm=\"foo\", profile=\"UsernameToken\"'})\n digest = res['digest']\n self.assertEqual('test-real.m@host.com', digest['realm'])\n self.assertEqual('\\tauth,auth-int', digest['qop'])\n self.assertEqual('(*)&^&$%#', digest['nonce'])\n\n def testParseWWWAuthenticateMalformed(self):\n try:\n res = httplib2._parse_www_authenticate({'www-authenticate': 'OAuth \"Facebook Platform\" \"invalid_token\" \"Invalid OAuth access token.\"'})\n self.fail('should raise an exception')\n except httplib2.MalformedHeader:\n pass\n", "method_code": "def _parse_www_authenticate(headers, headername='www-authenticate'):\n \"\"\"Returns a dictionary of dictionaries, one dict\n per auth_scheme.\"\"\"\n retval = {}\n if headername in headers:\n try:\n authenticate = headers[headername].strip()\n www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED\n while authenticate:\n if headername == 'authentication-info':\n auth_scheme, the_rest = ('digest', authenticate)\n else:\n auth_scheme, the_rest = authenticate.split(' ', 1)\n match = www_auth.search(the_rest)\n auth_params = {}\n while match:\n if match and len(match.groups()) == 3:\n key, value, the_rest = match.groups()\n auth_params[key.lower()] = UNQUOTE_PAIRS.sub('\\\\1', value)\n match = www_auth.search(the_rest)\n retval[auth_scheme.lower()] = auth_params\n authenticate = the_rest.strip()\n except ValueError:\n raise MalformedHeader('WWW-Authenticate')\n return retval", "context": "def _parse_www_authenticate(headers, headername='www-authenticate'): ...\ndef has_timeout(timeout): ...\ndef _get_end2end_headers(response): ...\ndef parse_uri(uri): ...\ndef urlnorm(uri): ...\ndef safename(filename): ...\ndef _normalize_headers(headers): ...\ndef _parse_cache_control(headers): ...\ndef _parse_www_authenticate(headers, headername='www-authenticate'): ...\ndef _entry_disposition(response_headers, request_headers): ...\ndef _decompressContent(response, new_content): ...\ndef _bind_write_headers(msg): ...\ndef _updateCache(request_headers, response_headers, content, cache, cachekey): ...\ndef _cnonce(): ...\ndef _wsse_username_token(cnonce, iso_now, password): ...\ndef proxy_info_from_environment(method='http'): ...\ndef proxy_info_from_url(url, method='http'): ...\n", "repository": "ZhouYii/AppProtocol", "test_name": "testParseWWWAuthenticateEmpty", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002266.py"} {"focal_file": "http-server/httplib2-0.8/python3/httplib2/__init__.py", "focal_class": null, "focal_method": "proxy_info_from_url", "tests": "import unittest\n\nclass Test_proxy_info_from_url(unittest.TestCase):\n def test_from_url(self):\n pi = httplib2.proxy_info_from_url('http://myproxy.example.com')\n self.assertEqual(pi.proxy_host, 'myproxy.example.com')\n self.assertEqual(pi.proxy_port, 80)\n self.assertEqual(pi.proxy_user, None)\n", "method_code": "def proxy_info_from_url(url, method='http'):\n \"\"\"\n Construct a ProxyInfo from a URL (such as http_proxy env var)\n \"\"\"\n url = urllib.parse.urlparse(url)\n username = None\n password = None\n port = None\n if '@' in url[1]:\n ident, host_port = url[1].split('@', 1)\n if ':' in ident:\n username, password = ident.split(':', 1)\n else:\n password = ident\n else:\n host_port = url[1]\n if ':' in host_port:\n host, port = host_port.split(':', 1)\n else:\n host = host_port\n if port:\n port = int(port)\n else:\n port = dict(https=443, http=80)[method]\n proxy_type = 3\n return ProxyInfo(proxy_type=proxy_type, proxy_host=host, proxy_port=port, proxy_user=username or None, proxy_pass=password or None)", "context": "def proxy_info_from_url(url, method='http'): ...\ndef has_timeout(timeout): ...\ndef _get_end2end_headers(response): ...\ndef parse_uri(uri): ...\ndef urlnorm(uri): ...\ndef safename(filename): ...\ndef _normalize_headers(headers): ...\ndef _parse_cache_control(headers): ...\ndef _parse_www_authenticate(headers, headername='www-authenticate'): ...\ndef _entry_disposition(response_headers, request_headers): ...\ndef _decompressContent(response, new_content): ...\ndef _bind_write_headers(msg): ...\ndef _updateCache(request_headers, response_headers, content, cache, cachekey): ...\ndef _cnonce(): ...\ndef _wsse_username_token(cnonce, iso_now, password): ...\ndef proxy_info_from_environment(method='http'): ...\ndef proxy_info_from_url(url, method='http'): ...\n", "repository": "ZhouYii/AppProtocol", "test_name": "test_from_url", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002267.py"} {"focal_file": "http-server/httplib2-0.8/python3/httplib2/__init__.py", "focal_class": null, "focal_method": "proxy_info_from_environment", "tests": "import unittest\n\nclass Test_proxy_info_from_environment(unittest.TestCase):\n def test_from_env_none(self):\n os.environ.clear()\n pi = httplib2.proxy_info_from_environment()\n self.assertEqual(pi, None)\n", "method_code": "def proxy_info_from_environment(method='http'):\n \"\"\"\n Read proxy info from the environment variables.\n \"\"\"\n if method not in ('http', 'https'):\n return\n env_var = method + '_proxy'\n url = os.environ.get(env_var, os.environ.get(env_var.upper()))\n if not url:\n return\n return proxy_info_from_url(url, method)", "context": "def proxy_info_from_environment(method='http'): ...\ndef has_timeout(timeout): ...\ndef _get_end2end_headers(response): ...\ndef parse_uri(uri): ...\ndef urlnorm(uri): ...\ndef safename(filename): ...\ndef _normalize_headers(headers): ...\ndef _parse_cache_control(headers): ...\ndef _parse_www_authenticate(headers, headername='www-authenticate'): ...\ndef _entry_disposition(response_headers, request_headers): ...\ndef _decompressContent(response, new_content): ...\ndef _bind_write_headers(msg): ...\ndef _updateCache(request_headers, response_headers, content, cache, cachekey): ...\ndef _cnonce(): ...\ndef _wsse_username_token(cnonce, iso_now, password): ...\ndef proxy_info_from_environment(method='http'): ...\ndef proxy_info_from_url(url, method='http'): ...\n", "repository": "ZhouYii/AppProtocol", "test_name": "test_from_env_none", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002268.py"} {"focal_file": "src/common/utils.py", "focal_class": null, "focal_method": "render_string_with_secrets", "tests": "import unittest\n\nclass Test_render_string_with_secrets(unittest.TestCase):\n def test_render_with_secret(self):\n user_commands = ['sleep <% $secrets.time %>', 'sleep <% $secrets.time[0] %>', 'sleep <% $secrets.time.time1 %>', 'echo <% $secrets.time.date.year %> && sleep <% $secrets.time.date.workingDay.0 %>']\n expected_commands = ['sleep 10', 'sleep 10', 'sleep 10', 'echo 2019 && sleep 1']\n with open('render_test_secrets.yaml') as f:\n secrets = list(yaml.safe_load_all(f.read()))\n for user_command, expected_command, secret in zip(user_commands, expected_commands, secrets):\n res = render_string_with_secrets(user_command, secret)\n self.assertEqual(res, expected_command)\n", "method_code": "def render_string_with_secrets(string, secrets) -> str:\n if not secrets:\n return string\n secret_dict = _convert_to_dict(secrets)\n parsed = pystache.parse(string, delimiters=('<%', '%>'))\n for token in parsed._parse_tree:\n if isinstance(token, pystache.parser._EscapeNode):\n token.key = re.sub('\\\\[(\\\\d+)\\\\]', '.\\\\1', token.key)\n return pystache.Renderer().render(parsed, {'$secrets': secret_dict})", "context": "def render_string_with_secrets(string, secrets) -> str: ...\ndef init_logger(): ...\ndef _convert_to_dict(obj) -> dict: ...\ndef enable_request_debug_log(func): ...\ndef render_string_with_secrets(string, secrets) -> str: ...\n", "repository": "microsoft/openpai-runtime", "test_name": "test_render_with_secret", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002269.py"} {"focal_file": "tclwrapper/tclutil.py", "focal_class": null, "focal_method": "tclstring_to_nested_list", "tests": "import unittest\n\nclass Test_tclstring_to_nested_list(unittest.TestCase):\n def test_tclstring_to_nested_list(self):\n\n def check_tclstring_to_nested_list(tclstring, nestedlist):\n x = tclutil.tclstring_to_nested_list(tclstring)\n self.assertEqual(x, nestedlist)\n check_tclstring_to_nested_list('', ())\n check_tclstring_to_nested_list('a', ('a',))\n check_tclstring_to_nested_list('a b', ('a', 'b'))\n check_tclstring_to_nested_list('a b c', ('a', 'b', 'c'))\n check_tclstring_to_nested_list('abc', ('abc',))\n check_tclstring_to_nested_list('{a b} c', (('a', 'b'), 'c'))\n check_tclstring_to_nested_list('{a {b c}} d', (('a', ('b', 'c')), 'd'))\n\n def test_tclstring_to_nested_list_with_levels(self):\n\n def check_tclstring_to_nested_list_with_levels(levels, tclstring, nestedlist):\n x = tclutil.tclstring_to_nested_list(tclstring, levels=levels)\n self.assertEqual(x, nestedlist)\n check_tclstring_to_nested_list_with_levels(0, 'a b c d', 'a b c d')\n check_tclstring_to_nested_list_with_levels(1, 'a b c d', ('a', 'b', 'c', 'd'))\n check_tclstring_to_nested_list_with_levels(2, 'a b c d', (('a',), ('b',), ('c',), ('d',)))\n check_tclstring_to_nested_list_with_levels(3, 'a b c d', ((('a',),), (('b',),), (('c',),), (('d',),)))\n check_tclstring_to_nested_list_with_levels(0, '{a b} {c d} {e f} {g h}', '{a b} {c d} {e f} {g h}')\n check_tclstring_to_nested_list_with_levels(1, '{a b} {c d} {e f} {g h}', ('a b', 'c d', 'e f', 'g h'))\n check_tclstring_to_nested_list_with_levels(2, '{a b} {c d} {e f} {g h}', (('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')))\n check_tclstring_to_nested_list_with_levels(0, '{a {b c}} d', '{a {b c}} d')\n check_tclstring_to_nested_list_with_levels(1, '{a {b c}} d', ('a {b c}', 'd'))\n check_tclstring_to_nested_list_with_levels(2, '{a {b c}} d', (('a', 'b c'), ('d',)))\n", "method_code": "def tclstring_to_nested_list(tclstring, levels=None):\n \"\"\"\n Parses the given Tcl string as a nested list.\n\n If levels is given, then parse tclstring as if it had the given number of\n levels of nesting. Otherwise parse tclstring into a nested tuple using\n _tkinter's split method\n \"\"\"\n if levels is None:\n ret = _tcl.tk.split(tclstring)\n if isinstance(ret, str):\n if ret == '':\n return ()\n else:\n return (ret,)\n else:\n return ret\n elif levels < 0:\n raise ValueError('levels must be non-negative')\n elif levels == 0:\n return tclstring\n else:\n return tuple([tclstring_to_nested_list(x, levels - 1) for x in tclstring_to_list(tclstring)])", "context": "def tclstring_to_nested_list(tclstring, levels=None): ...\ndef tclstring_to_list(tclstring): ...\ndef tclstring_to_nested_list(tclstring, levels=None): ...\ndef tclstring_to_flat_list(tclstring): ...\ndef list_to_tclstring(in_list): ...\ndef nested_list_to_tclstring(nested_list): ...\n", "repository": "csail-csg/tclwrapper", "test_name": "test_tclstring_to_nested_list", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002270.py"} {"focal_file": "tclwrapper/tclutil.py", "focal_class": null, "focal_method": "nested_list_to_tclstring", "tests": "import unittest\n\nclass Test_nested_list_to_tclstring(unittest.TestCase):\n def test_nested_list_to_tclstring(self):\n x = tclutil.nested_list_to_tclstring(TestTCLUtil.list_repr)\n self.assertEqual(x, TestTCLUtil.tclstring_repr)\n y = tclutil.nested_list_to_tclstring(TestTCLUtil.tuple_repr)\n self.assertEqual(y, TestTCLUtil.tclstring_repr)\n", "method_code": "def nested_list_to_tclstring(nested_list):\n items = []\n for item in nested_list:\n if isinstance(item, str):\n if ' ' in item:\n items.append('{' + item + '}')\n else:\n items.append(item)\n else:\n items.append('{' + nested_list_to_tclstring(item) + '}')\n return ' '.join(items)", "context": "def nested_list_to_tclstring(nested_list): ...\ndef tclstring_to_list(tclstring): ...\ndef tclstring_to_nested_list(tclstring, levels=None): ...\ndef tclstring_to_flat_list(tclstring): ...\ndef list_to_tclstring(in_list): ...\ndef nested_list_to_tclstring(nested_list): ...\n", "repository": "csail-csg/tclwrapper", "test_name": "test_nested_list_to_tclstring", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002271.py"} {"focal_file": "tclwrapper/tclutil.py", "focal_class": null, "focal_method": "tclstring_to_flat_list", "tests": "import unittest\n\nclass Test_tclstring_to_flat_list(unittest.TestCase):\n def test_tclstring_to_flat_list(self):\n x = tclutil.tclstring_to_flat_list(TestTCLUtil.tclstring_repr)\n self.assertEqual(x, TestTCLUtil.flat_list_repr)\n", "method_code": "def tclstring_to_flat_list(tclstring):\n return tclstring.replace('{', ' ').replace('}', ' ').split()", "context": "def tclstring_to_flat_list(tclstring): ...\ndef tclstring_to_list(tclstring): ...\ndef tclstring_to_nested_list(tclstring, levels=None): ...\ndef tclstring_to_flat_list(tclstring): ...\ndef list_to_tclstring(in_list): ...\ndef nested_list_to_tclstring(nested_list): ...\n", "repository": "csail-csg/tclwrapper", "test_name": "test_tclstring_to_flat_list", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002272.py"} {"focal_file": "lib/tree.py", "focal_class": null, "focal_method": "switch_branch", "tests": "import unittest\n\nclass Test_switch_branch(unittest.TestCase):\n def test_navigate_branch(self):\n t = new_tree('test.libundo-session')\n t.insert('My name is Joe.')\n self.assertEqual(t.text(), 'My name is Joe.')\n self.assertEqual(t.head().idx, 1)\n t.insert('My name is actually Bob.')\n self.assertEqual(t.text(), 'My name is actually Bob.')\n self.assertEqual(t.head().idx, 2)\n self.assertEqual(t.head().parent.idx, 1)\n self.assertEqual(t.undo()[0], 'My name is Joe.')\n t.insert('My name is Bob.')\n self.assertEqual(t.text(), 'My name is Bob.')\n self.assertEqual(t.head().idx, 3)\n self.assertEqual(t.head().parent.idx, 1)\n self.assertEqual(t.undo()[0], 'My name is Joe.')\n self.assertEqual(t.head().idx, 1)\n self.assertEqual(t.redo()[0], 'My name is actually Bob.')\n self.assertEqual(t.head().idx, 2)\n self.assertEqual(t.undo()[0], 'My name is Joe.')\n t.switch_branch(1)\n self.assertEqual(t.redo()[0], 'My name is Bob.')\n", "method_code": " def switch_branch(self, direction):\n \"\"\"Switch to the next branch in `direction`.\n \"\"\"\n n = len(self.head().children)\n if n <= 1:\n self._b_idx = 0\n elif direction and self._b_idx + 1 < n:\n self._b_idx = self._b_idx + 1\n elif not direction and self._b_idx - 1 >= 0:\n self._b_idx = self._b_idx - 1\n else:\n self._b_idx = 0 if self._b_idx == n - 1 else n - 1\n ", "context": "class UndoTree():\n def switch_branch(self, direction): ...\n def __init__(self): ...\n def __len__(self): ...\n def insert(self, buf, pos=None): ...\n def undo(self): ...\n def redo(self): ...\n def branch(self): ...\n def text(self): ...\n def nodes(self): ...\n def head(self): ...\n def _search(self, idx): ...\n def _find_parent(self): ...\n def _patch(self, s1, s2): ...\n def _apply_patch(self, idx): ...\n\n self._root = None\n self._total = 0\n self._n_idx = 0\n self._b_idx = 0\n self._buf = None\n self._dmp = diff_match_patch()\n self._index = collections.OrderedDict()\n", "repository": "libundo/Sublundo", "test_name": "test_navigate_branch", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002273.py"} {"focal_file": "lib/tree.py", "focal_class": null, "focal_method": "branch", "tests": "import unittest\n\nclass Test_branch(unittest.TestCase):\n def test_switch_branch(self):\n t = new_tree('test.libundo-session')\n self.assertEqual(t.branch(), 0)\n t.insert('One')\n t.insert('Two')\n t.switch_branch(1)\n self.assertEqual(t.branch(), 0)\n t.undo()\n t.insert('Three')\n self.assertEqual(t.branch(), 0)\n t.switch_branch(1)\n self.assertEqual(t.branch(), 0)\n t.undo()\n t.switch_branch(0)\n self.assertEqual(t.branch(), 1)\n t.switch_branch(1)\n self.assertEqual(t.branch(), 0)\n t.redo()\n self.assertEqual(t.head().idx, 2)\n t.insert('Four')\n t.insert('Five')\n self.assertEqual(t.head().idx, 5)\n self.assertEqual(t.head().parent.idx, 4)\n t.undo()\n self.assertEqual(t.head().idx, 4)\n self.assertEqual(t.head().parent.idx, 2)\n t.undo()\n self.assertEqual(t.head().idx, 2)\n self.assertEqual(t.head().parent.idx, 1)\n t.undo()\n self.assertEqual(t.head().idx, 1)\n self.assertEqual(t.head().parent, None)\n t.switch_branch(1)\n t.redo()\n self.assertEqual(t.head().idx, 3)\n self.assertEqual(t.head().parent.idx, 1)\n t.undo()\n self.assertEqual(t.head().idx, 1)\n t.switch_branch(1)\n t.redo()\n self.assertEqual(t.head().idx, 2)\n t.redo()\n self.assertEqual(t.head().idx, 4)\n t.redo()\n self.assertEqual(t.head().idx, 5)\n", "method_code": " def branch(self):\n \"\"\"Return the active branch index.\n \"\"\"\n return self._b_idx\n ", "context": "class UndoTree():\n def branch(self): ...\n def __init__(self): ...\n def __len__(self): ...\n def insert(self, buf, pos=None): ...\n def undo(self): ...\n def redo(self): ...\n def text(self): ...\n def nodes(self): ...\n def head(self): ...\n def switch_branch(self, direction): ...\n def _search(self, idx): ...\n def _find_parent(self): ...\n def _patch(self, s1, s2): ...\n def _apply_patch(self, idx): ...\n\n self._root = None\n self._total = 0\n self._n_idx = 0\n self._b_idx = 0\n self._buf = None\n self._dmp = diff_match_patch()\n self._index = collections.OrderedDict()\n", "repository": "libundo/Sublundo", "test_name": "test_switch_branch", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002274.py"} {"focal_file": "source/registry/calculator.py", "focal_class": null, "focal_method": "get_object", "tests": "import unittest\n\nclass Test_get_object(unittest.TestCase):\n def test_get_object(self):\n expected = FakeCalculator()\n Registry.put_object('calculator', expected)\n calculator = Registry.get_object('calculator')\n self.assertEqual(expected, calculator)\n", "method_code": " def get_object(cls, name):\n return cls.objects_.get(name, None)\n ", "context": "class Registry():\n @classmethod\n def get_object(cls, name): ...\n def put_object(cls, name, object_): ...\n\n objects_ = dict()\n", "repository": "goagile/poeaa", "test_name": "test_get_object", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002275.py"} {"focal_file": "source/registry/calculator.py", "focal_class": null, "focal_method": "calc_sum", "tests": "import unittest\n\nclass Test_calc_sum(unittest.TestCase):\n def test_calc_sum(self):\n fake_calculator = FakeCalculator()\n Registry.put_object('calculator', fake_calculator)\n calculator = Registry.get_object('calculator')\n result = calculator.calc_sum([1, 3, 6, 5])\n self.assertEqual(15, result)\n", "method_code": " def calc_sum(self, sequence):\n return sum(sequence)\n ", "context": "class FakeCalculator():\n def calc_sum(self, sequence): ...", "repository": "goagile/poeaa", "test_name": "test_calc_sum", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002276.py"} {"focal_file": "source/registry/person_finder.py", "focal_class": null, "focal_method": "get_person_finder", "tests": "import unittest\n\nclass Test_get_person_finder(unittest.TestCase):\n def test_get_person_finder(self):\n expected_person = Person('Petrov', 'Ivan')\n fake_person_finder = FakePersonFinder({1: expected_person})\n Registry.set_person_finder(fake_person_finder)\n person_finder = Registry.get_person_finder()\n self.assertEqual(fake_person_finder, person_finder)\n", "method_code": " def get_person_finder(cls):\n return cls.person_finder\n ", "context": "class Registry():\n @classmethod\n def get_person_finder(cls): ...\n def __init__(self): ...\n def set_person_finder(cls, person_finder): ...\n\n self.person_finder = None\n", "repository": "goagile/poeaa", "test_name": "test_get_person_finder", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002277.py"} {"focal_file": "source/registry/person_finder.py", "focal_class": null, "focal_method": "find_person", "tests": "import unittest\n\nclass Test_find_person(unittest.TestCase):\n def test_find_person(self):\n expected_person = Person('Petrov', 'Ivan')\n fake_person_finder = FakePersonFinder({1: expected_person})\n Registry.set_person_finder(fake_person_finder)\n person_finder = Registry.get_person_finder()\n person = person_finder.find_person(person_id=1)\n self.assertEqual(expected_person, person)\n", "method_code": " def find_person(self, person_id):\n return self.dict_[person_id]\n ", "context": "class FakePersonFinder():\n def find_person(self, person_id): ...\n def __init__(self, dict_): ...\n\n self.dict_ = dict_\n", "repository": "goagile/poeaa", "test_name": "test_find_person", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002278.py"} {"focal_file": "paramsfile.py", "focal_class": null, "focal_method": "read", "tests": "import unittest\n\nclass Test_read(unittest.TestCase):\n def test_read(self):\n pf = ParamsFile()\n pf.read(self.fparams)\n self.assertValues(pf)\n", "method_code": " def read(self, filename=None):\n if not filename:\n filename = self.filename\n with open(filename, 'r') as f:\n self.readstream(f)\n ", "context": "class ParamsFile(object):\n def read(self, filename=None): ...\n def __init__(self, filename='PARAMS'): ...\n def readstream(self, stream): ...\n def writestream(self, stream): ...\n def write(self, filename=None): ...\n\n self.filename = filename\n self._fields = [('Sig', 'Sig.out', str, 'File to output self-energy.'), ('Gf', 'Gf.out', str, \"File to output Green's function.\"), ('Delta', 'Delta.inp', str, 'File of input hybridization function.'), ('cix', 'ctqmc.cix', str, 'Cix file describing atomic states.'), ('U', 0.0, float, 'Coulomb repulsion (F0)'), ('mu', 0.0, float, 'QMC chemical potential'), ('beta', 1.0, float, 'Inverse temperature'), ('M', 1000000, int, 'Total number of Monte Carlo steps'), ('warmup', 0, int, 'Warmup number of QMC steps'), ('nom', 200, int, 'Number of Matsubara frequency points sampled'), ('Nmax', 2000, int, 'Maximum perturbation order allowed'), ('Segment', 2, int, 'Whether to use the segment representation of impurity trace'), ('tsample', 1000, int, 'How often to record measurements'), ('SampleGtau', 1000, int, 'How often to update G(tau)'), ('GlobalFlip', 1000000000, int, 'How often to try a global flip'), ('CleanUpdate', 1000000, int, 'How often to make clean update'), ('Ncout', 1000000, int, 'How often to print out info'), ('Naver', 1000000000, int, 'How often to print out debug info'), ('Ntau', 1000, int, 'Number of imaginary time points (only for debugging)'), ('aom', 30, int, 'Number of frequency points used to determine the value of sigma at nom'), ('sderiv', 0.02, float, 'Maximum derivative mismatch accepted for tail concatenation'), ('FastTrace', 0, int, 'Speeds up code for full-U calculation'), ('LazyTrace', 0, int, 'Speeds up code for full-U calculation'), ('PChangeOrder', 0.9, float, 'Ratio between trial steps: add-remove-a-kink / move-a-kink'), ('minM', 1e-10, float, 'The smallest allowed value for the atomic trace'), ('minD', 1e-10, float, 'The smallest allowed value for the determinant'), ('Ncorrect', -1, int, 'Which baths should not be corrected'), ('fastFilesystem', 0, int, 'Whether to write out Gaver and Delta.tau')]\n", "repository": "correlatedmaterialslaboratory/dmft-model", "test_name": "test_read", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002279.py"} {"focal_file": "census/core.py", "focal_class": null, "focal_method": "tables", "tests": "import unittest\n\nclass Test_tables(unittest.TestCase):\n def test_tables(self):\n self.client('acs5').tables()\n self.client('acs5').tables(2010)\n self.client('sf1').tables()\n", "method_code": " def tables(self, year=None):\n \"\"\"\n Returns a list of the data tables available from this source.\n \"\"\"\n if year is None:\n year = self.default_year\n tables_url = self.groups_url % (year, self.dataset)\n resp = self.session.get(tables_url)\n return resp.json()['groups']\n ", "context": "class Client(object):\n def tables(self, year=None): ...\n def __init__(self, key, year=None, session=None, retries=3): ...\n def fields(self, year=None, flat=False): ...\n def get(self, fields, geo, year=None, **kwargs): ...\n def query(self, fields, geo, year=None, sort_by_geoid=False, **kwargs): ...\n def _field_type(self, field, year): ...\n def us(self, fields, **kwargs): ...\n def state(self, fields, state_fips, **kwargs): ...\n def state_county(self, fields, state_fips, county_fips, **kwargs): ...\n def state_place(self, fields, state_fips, place, **kwargs): ...\n def state_district(self, fields, state_fips, district, **kwargs): ...\n def state_congressional_district(self, fields, state_fips, congressional_district, **kwargs): ...\n def state_legislative_district_upper(self, fields, state_fips, legislative_district, **kwargs): ...\n def state_legislative_district_lower(self, fields, state_fips, legislative_district, **kwargs): ...\n\n self._key = key\n self.session = session or new_session()\n self.retries = retries\n\n endpoint_url = 'https://api.census.gov/data/%s/%s'\n definitions_url = 'https://api.census.gov/data/%s/%s/variables.json'\n definition_url = 'https://api.census.gov/data/%s/%s/variables/%s.json'\n groups_url = 'https://api.census.gov/data/%s/%s/groups.json'\n", "repository": "datamade/census", "test_name": "test_tables", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002280.py"} {"focal_file": "src/pybel/canonicalize.py", "focal_class": null, "focal_method": "postpend_location", "tests": "import unittest\n\nclass Test_postpend_location(unittest.TestCase):\n def test_postpend_location_failure(self):\n with self.assertRaises(ValueError):\n postpend_location('', dict(name='failure'))\n", "method_code": "def postpend_location(bel_string: str, location_model) -> str:\n \"\"\"Rip off the closing parentheses and adds canonicalized modification.\n\n I did this because writing a whole new parsing model for the data would be sad and difficult\n\n :param bel_string: BEL string representing node\n :param dict location_model: A dictionary containing keys :code:`pybel.constants.TO_LOC` and\n :code:`pybel.constants.FROM_LOC`\n :return: A part of a BEL string representing the location\n \"\"\"\n if not all((k in location_model for k in {NAMESPACE, NAME})):\n raise ValueError('Location model missing namespace and/or name keys: {}'.format(location_model))\n return '{}, loc({}:{}))'.format(bel_string[:-1], location_model[NAMESPACE], ensure_quotes(location_model[NAME]))", "context": "def postpend_location(bel_string: str, location_model) -> str: ...\ndef to_bel_script(graph, path: Union[str, TextIO], use_identifiers: bool=True) -> None: ...\ndef to_bel_script_gz(graph, path, **kwargs) -> None: ...\ndef to_bel_script_lines(graph, use_identifiers: bool=True) -> Iterable[str]: ...\ndef postpend_location(bel_string: str, location_model) -> str: ...\ndef _decanonicalize_edge_node(node: BaseEntity, edge_data: EdgeData, node_position: str, *, use_identifiers: bool=True) -> str: ...\ndef edge_to_tuple(source: BaseEntity, target: BaseEntity, data: EdgeData, use_identifiers: bool=True) -> Tuple[str, str, str]: ...\ndef edge_to_bel(source: BaseEntity, target: BaseEntity, data: EdgeData, sep: Optional[str]=None, use_identifiers: bool=True) -> str: ...\ndef _sort_qualified_edges_helper(t: EdgeTuple) -> Tuple[str, str, str]: ...\ndef sort_qualified_edges(graph) -> Iterable[EdgeTuple]: ...\ndef _citation_sort_key(t: EdgeTuple) -> Tuple[str, str]: ...\ndef _evidence_sort_key(t: EdgeTuple) -> str: ...\ndef _set_annotation_to_str(annotation_data: Mapping[str, List[Entity]], key: str, use_curie: bool=False) -> str: ...\ndef _unset_annotation_to_str(keys: List[str]) -> str: ...\ndef _to_bel_lines_header(graph) -> Iterable[str]: ...\ndef group_citation_edges(edges: Iterable[EdgeTuple]) -> Iterable[Tuple[Tuple[str, str], Iterable[EdgeTuple]]]: ...\ndef group_evidence_edges(edges: Iterable[EdgeTuple]) -> Iterable[Tuple[str, Iterable[EdgeTuple]]]: ...\ndef _to_bel_lines_body(graph, use_identifiers: bool=False) -> Iterable[str]: ...\ndef _to_bel_lines_footer(graph, use_identifiers: bool=False) -> Iterable[str]: ...\ndef calculate_canonical_name(node: BaseEntity, use_identifiers: bool=True) -> str: ...\n", "repository": "pybel/pybel", "test_name": "test_postpend_location_failure", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002281.py"} {"focal_file": "src/pybel/io/pynpa.py", "focal_class": null, "focal_method": "to_npa_layers", "tests": "import unittest\n\nclass Test_to_npa_layers(unittest.TestCase):\n def test_export_layers(self):\n \"\"\"Test that the layers are exported right.\"\"\"\n ppi_layer, tf_layer = to_npa_layers(self.graph)\n self.assertIsInstance(ppi_layer, dict)\n self.assertIsInstance(tf_layer, dict)\n self.assertLess(0, len(ppi_layer), msg='PPI layer was not populated')\n self.assertLess(0, len(tf_layer), msg='TF layer was not populated')\n self.assertIn((g2, g3), ppi_layer)\n self.assertEqual(+1, ppi_layer[g2, g3])\n self.assertIn((g1, g2), tf_layer)\n self.assertEqual(+1, tf_layer[g1, g2])\n", "method_code": "def to_npa_layers(graph: BELGraph, cartesian_expansion: bool=False, direct_tf_only: bool=False) -> Tuple[Layer, Layer]:\n \"\"\"Get the two layers for the network.\n\n :param graph: A BEL graph\n :param cartesian_expansion: If true, applies cartesian expansion on both reactions (reactants x products)\n as well as list abundances using :func:`list_abundance_cartesian_expansion` and\n :func:`reaction_cartesian_expansion`\n :param direct_tf_only: If true, only uses directlyIncreases and directlyDecreases relations for TF relations\n ``complex(p(X), g(Y)) =>/=| r(Y)``. If false, also allows indirect relations ``complex(p(X), g(Y)) ->/-| r(Y)``.\n \"\"\"\n if cartesian_expansion:\n list_abundance_cartesian_expansion(graph)\n reaction_cartesian_expansion(graph)\n transcription_layer = {(u.get_rna().get_gene(), v.get_gene()): r for u, v, r in get_tf_pairs(graph, direct_only=direct_tf_only)}\n logger.info('extracted %d pairs for the transcription layer', len(transcription_layer))\n ppi_layer = {}\n for u, v, d in graph.edges(data=True):\n u, v = (_normalize(u), _normalize(v))\n if u is None or v is None:\n continue\n if (u, v) in transcription_layer:\n continue\n relation = d[RELATION]\n if relation in CAUSAL_INCREASE_RELATIONS:\n ppi_layer[u, v] = +1\n elif relation in CAUSAL_DECREASE_RELATIONS:\n ppi_layer[u, v] = -1\n logger.info('extracted %d pairs for the ppi layer', len(ppi_layer))\n return (ppi_layer, transcription_layer)", "context": "def to_npa_layers(graph: BELGraph, cartesian_expansion: bool=False, direct_tf_only: bool=False) -> Tuple[Layer, Layer]: ...\ndef to_npa_directory(graph: BELGraph, directory: str, **kwargs) -> None: ...\ndef to_npa_dfs(graph: BELGraph, cartesian_expansion: bool=False, nomenclature_method_first_layer: Optional[str]=None, nomenclature_method_second_layer: Optional[str]=None, direct_tf_only: bool=False) -> Tuple[pd.DataFrame, pd.DataFrame]: ...\ndef _get_df(layer: Layer, method: Optional[str]=None) -> pd.DataFrame: ...\ndef _normalize_layer(layer: Layer, method: Optional[str]=None) -> List[Tuple[str, str, int]]: ...\ndef to_npa_layers(graph: BELGraph, cartesian_expansion: bool=False, direct_tf_only: bool=False) -> Tuple[Layer, Layer]: ...\ndef _normalize(n): ...\n", "repository": "pybel/pybel", "test_name": "test_export_layers", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002282.py"} {"focal_file": "src/pybel/io/spia.py", "focal_class": null, "focal_method": "build_spia_matrices", "tests": "import unittest\n\nclass Test_build_spia_matrices(unittest.TestCase):\n def test_build_matrix(self):\n \"\"\"Test build empty matrix.\"\"\"\n node_names = get_matrix_index(self.sialic_acid_graph)\n matrix_dict = build_spia_matrices(node_names)\n nodes = {'PTPN11', 'TREM2', 'PTPN6', 'TYROBP', 'CD33', 'SYK'}\n self.assertEqual(set(matrix_dict['activation'].columns), nodes)\n self.assertEqual(set(matrix_dict['repression'].index), nodes)\n", "method_code": "def build_spia_matrices(nodes: Set[str]) -> Dict[str, pd.DataFrame]:\n \"\"\"Build an adjacency matrix for each KEGG relationship and return in a dictionary.\n\n :param nodes: A set of HGNC gene symbols\n :return: Dictionary of adjacency matrix for each relationship\n \"\"\"\n nodes = list(sorted(nodes))\n matrices = OrderedDict()\n for relation in KEGG_RELATIONS:\n matrices[relation] = pd.DataFrame(0, index=nodes, columns=nodes)\n return matrices", "context": "def build_spia_matrices(nodes: Set[str]) -> Dict[str, pd.DataFrame]: ...\ndef to_spia_excel(graph: BELGraph, path: str) -> None: ...\ndef to_spia_tsvs(graph: BELGraph, directory: str) -> None: ...\ndef to_spia_dfs(graph: BELGraph) -> SPIADataFrames: ...\ndef get_matrix_index(graph: BELGraph) -> Set[str]: ...\ndef build_spia_matrices(nodes: Set[str]) -> Dict[str, pd.DataFrame]: ...\ndef update_spia_matrices(spia_matrices: Dict[str, pd.DataFrame], u: CentralDogma, v: CentralDogma, edge_data: EdgeData) -> None: ...\ndef spia_matrices_to_excel(spia_matrices: SPIADataFrames, path: str) -> None: ...\ndef spia_matrices_to_tsvs(spia_matrices: SPIADataFrames, directory: str) -> None: ...\n", "repository": "pybel/pybel", "test_name": "test_build_matrix", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002283.py"} {"focal_file": "src/pybel/io/spia.py", "focal_class": null, "focal_method": "update_spia_matrices", "tests": "import unittest\n\nclass Test_update_spia_matrices(unittest.TestCase):\n def test_update_matrix_expression(self):\n \"\"\"Test updating the matrix with RNA expression.\"\"\"\n sub = protein(namespace='HGNC', name='A', identifier='1')\n obj = rna(namespace='HGNC', name='B', identifier='2')\n index = {'A', 'B'}\n test_dict = {}\n test_matrix = DataFrame(0, index=index, columns=index)\n test_dict['expression'] = test_matrix\n update_spia_matrices(test_dict, sub, obj, {'relation': 'increases'})\n self.assertEqual(test_dict['expression']['A']['B'], 1)\n self.assertEqual(test_dict['expression']['A']['A'], 0)\n self.assertEqual(test_dict['expression']['B']['A'], 0)\n self.assertEqual(test_dict['expression']['B']['B'], 0)\n\n def test_update_matrix_repression(self):\n \"\"\"Test updating the matrix with RNA repression.\"\"\"\n sub = protein(namespace='HGNC', name='A', identifier='1')\n obj = rna(namespace='HGNC', name='B', identifier='2')\n index = {'A', 'B'}\n test_dict = {}\n test_matrix = DataFrame(0, index=index, columns=index)\n test_dict['repression'] = test_matrix\n update_spia_matrices(test_dict, sub, obj, {'relation': 'decreases'})\n self.assertEqual(test_dict['repression']['A']['B'], 1)\n self.assertEqual(test_dict['repression']['A']['A'], 0)\n self.assertEqual(test_dict['repression']['B']['A'], 0)\n self.assertEqual(test_dict['repression']['B']['B'], 0)\n\n def test_update_matrix_activation(self):\n \"\"\"Test updating the matrix with activation.\"\"\"\n sub = protein(namespace='HGNC', name='A', identifier='1')\n obj = protein(namespace='HGNC', name='B', identifier='2')\n index = {'A', 'B'}\n test_dict = {}\n test_matrix = DataFrame(0, index=index, columns=index)\n test_dict['activation'] = test_matrix\n update_spia_matrices(test_dict, sub, obj, {'relation': 'increases'})\n self.assertEqual(test_dict['activation']['A']['B'], 1)\n self.assertEqual(test_dict['activation']['A']['A'], 0)\n self.assertEqual(test_dict['activation']['B']['A'], 0)\n self.assertEqual(test_dict['activation']['B']['B'], 0)\n\n def test_update_matrix_association(self):\n \"\"\"Test updating the matrix with association.\"\"\"\n sub = protein(namespace='HGNC', name='A', identifier='1')\n obj = protein(namespace='HGNC', name='B', identifier='2')\n index = {'A', 'B'}\n test_dict = {}\n test_matrix = DataFrame(0, index=index, columns=index)\n test_dict['binding_association'] = test_matrix\n update_spia_matrices(test_dict, sub, obj, {'relation': 'association'})\n self.assertEqual(test_dict['binding_association']['A']['B'], 1)\n self.assertEqual(test_dict['binding_association']['A']['A'], 0)\n self.assertEqual(test_dict['binding_association']['B']['A'], 0)\n self.assertEqual(test_dict['binding_association']['B']['B'], 0)\n\n def test_update_matrix_pmods(self):\n \"\"\"Test updating the matrix with multiple protein modifications.\"\"\"\n sub = protein(namespace='HGNC', name='A', identifier='1')\n obj = protein(namespace='HGNC', name='B', identifier='2', variants=[pmod('Ub'), pmod('Ph')])\n index = {'A', 'B'}\n test_dict = {}\n test_matrix = DataFrame(0, index=index, columns=index)\n test_dict['activation_ubiquination'] = test_matrix\n test_dict['activation_phosphorylation'] = test_matrix\n update_spia_matrices(test_dict, sub, obj, {'relation': 'increases'})\n self.assertEqual(test_dict['activation_ubiquination']['A']['B'], 1)\n self.assertEqual(test_dict['activation_ubiquination']['A']['A'], 0)\n self.assertEqual(test_dict['activation_ubiquination']['B']['A'], 0)\n self.assertEqual(test_dict['activation_ubiquination']['B']['B'], 0)\n self.assertEqual(test_dict['activation_phosphorylation']['A']['B'], 1)\n self.assertEqual(test_dict['activation_phosphorylation']['A']['A'], 0)\n self.assertEqual(test_dict['activation_phosphorylation']['B']['A'], 0)\n self.assertEqual(test_dict['activation_phosphorylation']['B']['B'], 0)\n", "method_code": "def update_spia_matrices(spia_matrices: Dict[str, pd.DataFrame], u: CentralDogma, v: CentralDogma, edge_data: EdgeData) -> None:\n \"\"\"Populate the adjacency matrix.\"\"\"\n if u.namespace.lower() != 'hgnc' or v.namespace.lower() != 'hgnc':\n return\n u_name = u.name\n v_name = v.name\n relation = edge_data[RELATION]\n if relation in CAUSAL_INCREASE_RELATIONS:\n if v.variants and any((isinstance(variant, ProteinModification) for variant in v.variants)):\n for variant in v.variants:\n if not isinstance(variant, ProteinModification):\n continue\n elif variant.entity.name in UB_NAMES:\n spia_matrices['activation_ubiquination'][u_name][v_name] = 1\n elif variant.entity.name in PH_NAMES:\n spia_matrices['activation_phosphorylation'][u_name][v_name] = 1\n elif isinstance(v, (Gene, Rna)):\n spia_matrices['expression'][u_name][v_name] = 1\n else:\n spia_matrices['activation'][u_name][v_name] = 1\n elif relation in CAUSAL_DECREASE_RELATIONS:\n if v.variants and any((isinstance(variant, ProteinModification) for variant in v.variants)):\n for variant in v.variants:\n if not isinstance(variant, ProteinModification):\n continue\n elif variant.entity.name in UB_NAMES:\n spia_matrices['inhibition_ubiquination'][u_name][v_name] = 1\n elif variant.entity.name in PH_NAMES:\n spia_matrices['inhibition_phosphorylation'][u_name][v_name] = 1\n elif isinstance(v, (Gene, Rna)):\n spia_matrices['repression'][u_name][v_name] = 1\n else:\n spia_matrices['inhibition'][u_name][v_name] = 1\n elif relation == ASSOCIATION:\n spia_matrices['binding_association'][u_name][v_name] = 1", "context": "def update_spia_matrices(spia_matrices: Dict[str, pd.DataFrame], u: CentralDogma, v: CentralDogma, edge_data: EdgeData) -> None: ...\ndef to_spia_excel(graph: BELGraph, path: str) -> None: ...\ndef to_spia_tsvs(graph: BELGraph, directory: str) -> None: ...\ndef to_spia_dfs(graph: BELGraph) -> SPIADataFrames: ...\ndef get_matrix_index(graph: BELGraph) -> Set[str]: ...\ndef build_spia_matrices(nodes: Set[str]) -> Dict[str, pd.DataFrame]: ...\ndef update_spia_matrices(spia_matrices: Dict[str, pd.DataFrame], u: CentralDogma, v: CentralDogma, edge_data: EdgeData) -> None: ...\ndef spia_matrices_to_excel(spia_matrices: SPIADataFrames, path: str) -> None: ...\ndef spia_matrices_to_tsvs(spia_matrices: SPIADataFrames, directory: str) -> None: ...\n", "repository": "pybel/pybel", "test_name": "test_update_matrix_expression", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002284.py"} {"focal_file": "src/pybel/testing/utils.py", "focal_class": null, "focal_method": "n", "tests": "import unittest\n\nclass Test_n(unittest.TestCase):\n def test_protein_activates_protein(self):\n \"\"\"Test conversion of ``p(A) -> p(D)``.\"\"\"\n self.graph.add_increases(a, d, citation=n(), evidence='')\n att_df, sif_df = self._get_dfs()\n att_df = att_df[ATT_COLS]\n self.assertEqual(2, len(att_df.index))\n self.assertEqual([['N-{name}-1'.format(name=name), a.name, a.identifier], ['N-{name}-2'.format(name=name), d.name, d.identifier]], att_df.values.tolist())\n self.assertEqual(1, len(sif_df))\n self.assertEqual([['N-{name}-1'.format(name=name), 'activation', 'N-{name}-2'.format(name=name)]], sif_df.values.tolist())\n", "method_code": "def n() -> str:\n \"\"\"Return a UUID string for testing.\"\"\"\n return str(uuid4())[:15]", "context": "def n() -> str: ...\ndef get_uri_name(url: str) -> str: ...\ndef n() -> str: ...\ndef make_dummy_namespaces(manager: Manager, graph: BELGraph) -> None: ...\ndef make_dummy_annotations(manager: Manager, graph: BELGraph): ...\n", "repository": "pybel/pybel", "test_name": "test_protein_activates_protein", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002285.py"} {"focal_file": "src/pybel/io/hipathia.py", "focal_class": null, "focal_method": "group_delimited_list", "tests": "import unittest\n\nclass Test_group_delimited_list(unittest.TestCase):\n def test_group_delimited(self):\n self.assertEqual([[5335, 5336], [9047]], group_delimited_list([5335, 5336, '/', 9047], '/'))\n", "method_code": "def group_delimited_list(entries: List[str], sep: str='/') -> List[List[str]]:\n \"\"\"Group delimited things in a list.\"\"\"\n return [list(b) for a, b in groupby(entries, lambda z: z == sep) if not a]", "context": "def group_delimited_list(entries: List[str], sep: str='/') -> List[List[str]]: ...\ndef from_hipathia_paths(name: str, att_path: str, sif_path: str) -> BELGraph: ...\ndef group_delimited_list(entries: List[str], sep: str='/') -> List[List[str]]: ...\ndef _p(identifier: str): ...\ndef _f(identifier: str): ...\ndef from_hipathia_dfs(name: str, att_df: pd.DataFrame, sif_df: pd.DataFrame) -> BELGraph: ...\ndef to_hipathia(graph: BELGraph, directory: str, draw: bool=True) -> None: ...\ndef _is_node_family(graph: BELGraph, node: Protein) -> Optional[Set[Protein]]: ...\ndef to_hipathia_dfs(graph: BELGraph, draw_directory: Optional[str]=None) -> Union[Tuple[None, None], Tuple[pd.DataFrame, pd.DataFrame]]: ...\ndef make_hsa047370() -> BELGraph: ...\n", "repository": "pybel/pybel", "test_name": "test_group_delimited", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002286.py"} {"focal_file": "src/pybel/manager/citation_utils.py", "focal_class": null, "focal_method": "sanitize_date", "tests": "import unittest\n\nclass Test_sanitize_date(unittest.TestCase):\n def test_sanitize_1(self):\n \"\"\"Test YYYY Mon DD.\"\"\"\n self.assertEqual('2012-12-19', sanitize_date('2012 Dec 19'))\n\n def test_sanitize_2(self):\n \"\"\"Test YYYY Mon.\"\"\"\n self.assertEqual('2012-12-01', sanitize_date('2012 Dec'))\n\n def test_sanitize_3(self):\n \"\"\"Test YYYY.\"\"\"\n self.assertEqual('2012-01-01', sanitize_date('2012'))\n\n def test_sanitize_4(self):\n \"\"\"Test YYYY Mon-Mon.\"\"\"\n self.assertEqual('2012-10-01', sanitize_date('2012 Oct-Dec'))\n\n def test_sanitize_5(self):\n \"\"\"Test YYYY Season.\"\"\"\n self.assertEqual('2012-03-01', sanitize_date('2012 Spring'))\n\n def test_sanitize_6(self):\n \"\"\"Test YYYY Mon DD-DD.\"\"\"\n self.assertEqual('2012-12-12', sanitize_date('2012 Dec 12-15'))\n\n def test_sanitize_7(self):\n \"\"\"Test YYYY Mon DD-Mon DD.\"\"\"\n self.assertEqual('2005-01-29', sanitize_date('2005 Jan 29-Feb 4'))\n\n def test_sanitize_nope(self):\n \"\"\"Test failure.\"\"\"\n self.assertEqual(None, sanitize_date('2012 Early Spring'))\n", "method_code": "def sanitize_date(publication_date: str) -> str:\n \"\"\"Sanitize lots of different date strings into ISO-8601.\"\"\"\n if re1.search(publication_date):\n return datetime.strptime(publication_date, '%Y %b %d').strftime('%Y-%m-%d')\n if re2.search(publication_date):\n return datetime.strptime(publication_date, '%Y %b').strftime('%Y-%m-01')\n if re3.search(publication_date):\n return publication_date + '-01-01'\n if re4.search(publication_date):\n return datetime.strptime(publication_date[:-4], '%Y %b').strftime('%Y-%m-01')\n s = re5.search(publication_date)\n if s:\n year, season = s.groups()\n return '{}-{}-01'.format(year, season_map[season])\n s = re6.search(publication_date)\n if s:\n return datetime.strptime(publication_date, '%Y %b %d-{}'.format(s.groups()[0])).strftime('%Y-%m-%d')\n s = re7.search(publication_date)\n if s:\n return datetime.strptime(publication_date, '%Y %b %d-{}'.format(s.groups()[0])).strftime('%Y-%m-%d')", "context": "def sanitize_date(publication_date: str) -> str: ...\ndef sanitize_date(publication_date: str) -> str: ...\ndef clean_pubmed_identifiers(identifiers: Iterable[str]) -> List[str]: ...\ndef get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): ...\ndef enrich_citation_model(manager: Manager, citation: models.Citation, p: Mapping[str, Any]) -> bool: ...\ndef get_citations_by_pmids(manager: Manager, pmids: Iterable[Union[str, int]], *, group_size: Optional[int]=None, offline: bool=False) -> Tuple[Dict[str, Dict], Set[str]]: ...\ndef _get_citations_by_identifiers(manager: Manager, identifiers: Iterable[Union[str, int]], *, group_size: Optional[int]=None, offline: bool=False, prefix: Optional[str]=None) -> Tuple[Dict[str, Dict], Set[str]]: ...\ndef _help_enrich_pmids(identifiers: Iterable[str], *, manager, unenriched_models, enriched_models, errors): ...\ndef _help_enrich_pmc_identifiers(identifiers: Iterable[str], *, manager: Manager, unenriched_models, enriched_models, errors): ...\ndef _get_citation_models(identifiers: Iterable[str], *, prefix: str, manager: Manager, chunksize: int=200) -> Iterable[models.Citation]: ...\ndef enrich_pubmed_citations(graph: BELGraph, *, manager: Optional[Manager]=None, group_size: Optional[int]=None, offline: bool=False) -> Set[str]: ...\ndef enrich_pmc_citations(graph: BELGraph, *, manager: Optional[Manager]=None, group_size: Optional[int]=None, offline: bool=False) -> Set[str]: ...\ndef _enrich_citations(graph: BELGraph, manager: Optional[Manager], group_size: Optional[int]=None, offline: bool=False, prefix: Optional[str]=None) -> Set[str]: ...\ndef get_pmc_csl_item(pmcid: str) -> Mapping[str, Any]: ...\ndef enrich_citation_model_from_pmc(manager: Manager, citation: models.Citation, csl: Mapping[str, Any]) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_sanitize_1", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002287.py"} {"focal_file": "src/pybel/manager/citation_utils.py", "focal_class": null, "focal_method": "enrich_pubmed_citations", "tests": "import unittest\n\nclass Test_enrich_pubmed_citations(unittest.TestCase):\n @mock_get_pubmed_citation_response\n def test_enrich_pubmed_overwrite(self, *_):\n citation = self.manager.get_or_create_citation(namespace=CITATION_TYPE_PUBMED, identifier=self.pmid)\n self.manager.session.commit()\n self.assertIsNone(citation.date)\n self.assertIsNone(citation.title)\n enrich_pubmed_citations(manager=self.manager, graph=self.graph)\n _, _, d = list(self.graph.edges(data=True))[0]\n citation_dict = d[CITATION]\n self.assertIsInstance(citation_dict, CitationDict)\n self.assertIn(CITATION_JOURNAL, citation_dict)\n self.assertIn(CITATION_DATE, citation_dict)\n self.assertEqual('1998-05-01', citation_dict[CITATION_DATE])\n self.assertIn(CITATION_AUTHORS, citation_dict)\n self.assertEqual({'Lewell XQ', 'Judd DB', 'Watson SP', 'Hann MM'}, set(citation_dict[CITATION_AUTHORS]))\n\n @mock_get_pubmed_citation_response\n def test_enrich_pubmed_graph(self, *_):\n enrich_pubmed_citations(manager=self.manager, graph=self.graph)\n _, _, d = list(self.graph.edges(data=True))[0]\n citation_dict = d[CITATION]\n self.assertIsInstance(citation_dict, CitationDict)\n self.assertIn(CITATION_JOURNAL, citation_dict)\n self.assertIn(CITATION_DATE, citation_dict)\n self.assertEqual('1998-05-01', citation_dict[CITATION_DATE])\n self.assertIn(CITATION_AUTHORS, citation_dict)\n self.assertEqual({'Lewell XQ', 'Judd DB', 'Watson SP', 'Hann MM'}, set(citation_dict[CITATION_AUTHORS]))\n", "method_code": "def enrich_pubmed_citations(graph: BELGraph, *, manager: Optional[Manager]=None, group_size: Optional[int]=None, offline: bool=False) -> Set[str]:\n \"\"\"Overwrite all PubMed citations with values from NCBI's eUtils lookup service.\n\n :param graph: A BEL graph\n :param manager: A PyBEL database manager\n :param group_size: The number of PubMed identifiers to query at a time. Defaults to 200 identifiers.\n :param offline: An override for when you don't want to hit the eUtils\n :return: A set of PMIDs for which the eUtils service crashed\n \"\"\"\n return _enrich_citations(manager=manager, graph=graph, group_size=group_size, offline=offline, prefix='pubmed')", "context": "def enrich_pubmed_citations(graph: BELGraph, *, manager: Optional[Manager]=None, group_size: Optional[int]=None, offline: bool=False) -> Set[str]: ...\ndef sanitize_date(publication_date: str) -> str: ...\ndef clean_pubmed_identifiers(identifiers: Iterable[str]) -> List[str]: ...\ndef get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): ...\ndef enrich_citation_model(manager: Manager, citation: models.Citation, p: Mapping[str, Any]) -> bool: ...\ndef get_citations_by_pmids(manager: Manager, pmids: Iterable[Union[str, int]], *, group_size: Optional[int]=None, offline: bool=False) -> Tuple[Dict[str, Dict], Set[str]]: ...\ndef _get_citations_by_identifiers(manager: Manager, identifiers: Iterable[Union[str, int]], *, group_size: Optional[int]=None, offline: bool=False, prefix: Optional[str]=None) -> Tuple[Dict[str, Dict], Set[str]]: ...\ndef _help_enrich_pmids(identifiers: Iterable[str], *, manager, unenriched_models, enriched_models, errors): ...\ndef _help_enrich_pmc_identifiers(identifiers: Iterable[str], *, manager: Manager, unenriched_models, enriched_models, errors): ...\ndef _get_citation_models(identifiers: Iterable[str], *, prefix: str, manager: Manager, chunksize: int=200) -> Iterable[models.Citation]: ...\ndef enrich_pubmed_citations(graph: BELGraph, *, manager: Optional[Manager]=None, group_size: Optional[int]=None, offline: bool=False) -> Set[str]: ...\ndef enrich_pmc_citations(graph: BELGraph, *, manager: Optional[Manager]=None, group_size: Optional[int]=None, offline: bool=False) -> Set[str]: ...\ndef _enrich_citations(graph: BELGraph, manager: Optional[Manager], group_size: Optional[int]=None, offline: bool=False, prefix: Optional[str]=None) -> Set[str]: ...\ndef get_pmc_csl_item(pmcid: str) -> Mapping[str, Any]: ...\ndef enrich_citation_model_from_pmc(manager: Manager, citation: models.Citation, csl: Mapping[str, Any]) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002288.py"} {"focal_file": "src/pybel/manager/citation_utils.py", "focal_class": null, "focal_method": "_enrich_citations", "tests": "import unittest\n\nclass Test_enrich_citations(unittest.TestCase):\n @mock_get_pmc_csl_item\n def test_enrich_pmc(self, *_):\n errors = _enrich_citations(manager=self.manager, graph=self.graph, prefix='pmc')\n self.assertEqual(0, len(errors), msg=f'Got errors: {errors}')\n _, _, d = list(self.graph.edges(data=True))[0]\n citation_dict = d[CITATION]\n self.assertIsInstance(citation_dict, CitationDict)\n self.assertEqual('pmc', citation_dict.namespace)\n self.assertEqual(self.citation_identifier, citation_dict.identifier)\n self.assertIn(CITATION_JOURNAL, citation_dict)\n self.assertEqual('PLoS computational biology', citation_dict[CITATION_JOURNAL])\n self.assertIn(CITATION_DATE, citation_dict)\n self.assertEqual('2019-06-24', citation_dict[CITATION_DATE])\n self.assertIn(CITATION_AUTHORS, citation_dict)\n self.assertLess(0, len(citation_dict[CITATION_AUTHORS]))\n", "method_code": "def _enrich_citations(graph: BELGraph, manager: Optional[Manager], group_size: Optional[int]=None, offline: bool=False, prefix: Optional[str]=None) -> Set[str]:\n \"\"\"Overwrite all citations of the given prefix using the predefined lookup functions.\n\n :param graph: A BEL Graph\n :param group_size: The number of identifiers to query at a time. Defaults to 200 identifiers.\n :return: A set of identifiers for which lookup was not possible\n \"\"\"\n if manager is None:\n manager = Manager()\n if prefix is None:\n prefix = 'pubmed'\n identifiers = {identifier for identifier in get_citation_identifiers(graph, prefix) if identifier}\n identifier_map, errors = _get_citations_by_identifiers(manager, identifiers=identifiers, group_size=group_size, offline=offline, prefix=prefix)\n for u, v, k in filter_edges(graph, CITATION_PREDICATES[prefix]):\n identifier = graph[u][v][k][CITATION].identifier\n identifier_data = identifier_map.get(identifier)\n if identifier_data is None:\n logger.warning('Missing data for %s:%s', prefix, identifier)\n errors.add(identifier)\n continue\n graph[u][v][k][CITATION].update(identifier_data)\n return errors", "context": "def _enrich_citations(graph: BELGraph, manager: Optional[Manager], group_size: Optional[int]=None, offline: bool=False, prefix: Optional[str]=None) -> Set[str]: ...\ndef sanitize_date(publication_date: str) -> str: ...\ndef clean_pubmed_identifiers(identifiers: Iterable[str]) -> List[str]: ...\ndef get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): ...\ndef enrich_citation_model(manager: Manager, citation: models.Citation, p: Mapping[str, Any]) -> bool: ...\ndef get_citations_by_pmids(manager: Manager, pmids: Iterable[Union[str, int]], *, group_size: Optional[int]=None, offline: bool=False) -> Tuple[Dict[str, Dict], Set[str]]: ...\ndef _get_citations_by_identifiers(manager: Manager, identifiers: Iterable[Union[str, int]], *, group_size: Optional[int]=None, offline: bool=False, prefix: Optional[str]=None) -> Tuple[Dict[str, Dict], Set[str]]: ...\ndef _help_enrich_pmids(identifiers: Iterable[str], *, manager, unenriched_models, enriched_models, errors): ...\ndef _help_enrich_pmc_identifiers(identifiers: Iterable[str], *, manager: Manager, unenriched_models, enriched_models, errors): ...\ndef _get_citation_models(identifiers: Iterable[str], *, prefix: str, manager: Manager, chunksize: int=200) -> Iterable[models.Citation]: ...\ndef enrich_pubmed_citations(graph: BELGraph, *, manager: Optional[Manager]=None, group_size: Optional[int]=None, offline: bool=False) -> Set[str]: ...\ndef enrich_pmc_citations(graph: BELGraph, *, manager: Optional[Manager]=None, group_size: Optional[int]=None, offline: bool=False) -> Set[str]: ...\ndef _enrich_citations(graph: BELGraph, manager: Optional[Manager], group_size: Optional[int]=None, offline: bool=False, prefix: Optional[str]=None) -> Set[str]: ...\ndef get_pmc_csl_item(pmcid: str) -> Mapping[str, Any]: ...\ndef enrich_citation_model_from_pmc(manager: Manager, citation: models.Citation, csl: Mapping[str, Any]) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002289.py"} {"focal_file": "src/pybel/manager/models.py", "focal_class": null, "focal_method": "to_json", "tests": "import unittest\n\nclass Test_to_json(unittest.TestCase):\n def test_to_json(self):\n model_json = self.model.to_json()\n self.assertIn(METADATA_NAME, model_json)\n self.assertEqual(self.name, model_json[METADATA_NAME])\n self.assertIn(METADATA_VERSION, model_json)\n self.assertEqual(self.version, model_json[METADATA_VERSION])\n self.assertIn('created', model_json)\n self.assertEqual(str(self.created), model_json['created'])\n self.assertEqual(self.expected, model_json)\n", "method_code": " def to_json(self, include_id: bool=False) -> Mapping[str, str]:\n \"\"\"Return the most useful entries as a dictionary.\n \n :param include_id: If true, includes the model identifier\n \"\"\"\n result = {'keyword': self.keyword, 'name': self.name, 'version': self.version}\n if self.url:\n result['url'] = self.url\n else:\n result['pattern'] = self.pattern\n if include_id:\n result['id'] = self.id\n return result\n ", "context": "class Namespace(Base):\n def to_json(self, include_id: bool=False) -> Mapping[str, str]: ...\n def __str__(self): ...\n def get_term_to_encodings(self) -> Mapping[Tuple[Optional[str], str], str]: ...\n\n __tablename__ = NAMESPACE_TABLE_NAME\n id = Column(Integer, primary_key=True)\n uploaded = Column(DateTime, nullable=False, default=datetime.datetime.utcnow, doc='The date of upload')\n keyword = Column(String(255), nullable=True, index=True, doc='Keyword that is used in a BEL file to identify a specific namespace')\n pattern = Column(String(255), nullable=True, index=True, doc='Contains regex pattern for value identification.')\n miriam_id = Column(String(16), nullable=True, doc='MIRIAM resource identifier matching the regular expression ``^MIR:001\\\\d{5}$``')\n miriam_name = Column(String(255), nullable=True)\n miriam_namespace = Column(String(255), nullable=True)\n miriam_uri = Column(String(255), nullable=True)\n miriam_description = Column(Text, nullable=True)\n version = Column(String(255), nullable=True, doc='Version of the namespace')\n url = Column(String(255), nullable=True, unique=True, index=True, doc='BELNS Resource location as URL')\n name = Column(String(255), nullable=True, doc='Name of the given namespace')\n domain = Column(String(255), nullable=True, doc='Domain for which this namespace is valid')\n species = Column(String(255), nullable=True, doc='Taxonomy identifiers for which this namespace is valid')\n description = Column(Text, nullable=True, doc='Optional short description of the namespace')\n created = Column(DateTime, nullable=True, doc='DateTime of the creation of the namespace definition file')\n query_url = Column(Text, nullable=True, doc='URL that can be used to query the namespace (externally from PyBEL)')\n author = Column(String(255), nullable=True, doc='The author of the namespace')\n license = Column(String(255), nullable=True, doc='License information')\n contact = Column(String(255), nullable=True, doc='Contact information')\n citation = Column(String(255), nullable=True)\n citation_description = Column(Text, nullable=True)\n citation_version = Column(String(255), nullable=True)\n citation_published = Column(Date, nullable=True)\n citation_url = Column(String(255), nullable=True)\n is_annotation = Column(Boolean)\n", "repository": "pybel/pybel", "test_name": "test_to_json", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002290.py"} {"focal_file": "src/pybel/parser/parse_control.py", "focal_class": null, "focal_method": "get_annotations", "tests": "import unittest\n\nclass Test_get_annotations(unittest.TestCase):\n def test_custom_annotation_list(self):\n s = [SET_CITATION_TEST, 'SET Custom1 = {\"Custom1_A\",\"Custom1_B\"}']\n self.parser.parse_lines(s)\n expected_annotation = {'Custom1': [Entity(namespace='Custom1', identifier='Custom1_A'), Entity(namespace='Custom1', identifier='Custom1_B')]}\n self.assertEqual(expected_annotation, self.parser.annotations)\n expected_dict = {ANNOTATIONS: expected_annotation, CITATION: test_citation_dict, EVIDENCE: None}\n self.assertEqual(expected_dict, self.parser.get_annotations())\n", "method_code": " def get_annotations(self) -> Dict[str, Any]:\n \"\"\"Get the current annotations.\"\"\"\n return {EVIDENCE: self.evidence, CITATION: self.get_citation(), ANNOTATIONS: self.annotations.copy()}\n ", "context": "class ControlParser(BaseParser):\n def get_annotations(self) -> Dict[str, Any]: ...\n def __init__(self, annotation_to_term: Optional[Mapping[str, Set[str]]]=None, annotation_to_pattern: Optional[Mapping[str, Pattern]]=None, annotation_to_local: Optional[Mapping[str, Set[str]]]=None, citation_clearing: bool=True, required_annotations: Optional[List[str]]=None) -> None: ...\n def _in_debug_mode(self) -> bool: ...\n def citation_is_set(self) -> bool: ...\n def has_enumerated_annotation(self, annotation: str) -> bool: ...\n def has_regex_annotation(self, annotation: str) -> bool: ...\n def has_local_annotation(self, annotation: str) -> bool: ...\n def has_annotation(self, annotation: str) -> bool: ...\n def raise_for_undefined_annotation(self, line: str, position: int, annotation: str) -> None: ...\n def raise_for_invalid_annotation_value(self, line: str, position: int, key: str, value: str) -> None: ...\n def raise_for_missing_citation(self, line: str, position: int) -> None: ...\n def handle_annotation_key(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def handle_set_statement_group(self, _, __, tokens: ParseResults) -> ParseResults: ...\n def handle_set_citation(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def handle_set_evidence(self, _, __, tokens: ParseResults) -> ParseResults: ...\n def handle_set_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def handle_set_command_list(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def handle_unset_statement_group(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def handle_unset_citation(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def handle_unset_evidence(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def validate_unset_command(self, line: str, position: int, annotation: str) -> None: ...\n def handle_unset_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def handle_unset_list(self, line: str, position: int, tokens: ParseResults) -> ParseResults: ...\n def handle_unset_all(self, _, __, tokens) -> ParseResults: ...\n def get_citation(self) -> Optional[CitationDict]: ...\n def get_missing_required_annotations(self) -> List[str]: ...\n def clear_citation(self) -> None: ...\n def clear(self) -> None: ...\n\n self.citation_clearing = citation_clearing\n self.annotation_to_term = annotation_to_term or {}\n self.annotation_to_pattern = annotation_to_pattern or {}\n self.annotation_to_local = annotation_to_local or {}\n self.statement_group = None\n self.citation_db = None\n self.citation_db_id = None\n self.evidence = None\n self.annotations = {}\n self.required_annotations = required_annotations or []\n self.set_statement_group = set_statement_group_stub().setParseAction(self.handle_set_statement_group)\n self.set_citation = set_citation_stub.setParseAction(self.handle_set_citation)\n self.set_evidence = set_evidence_stub.setParseAction(self.handle_set_evidence)\n self.set_command = set_command_prefix + qid('value')\n self.set_command_list = set_command_prefix + delimited_quoted_list('values')\n self.unset_command = annotation_key('key')\n self.unset_evidence = supporting_text_tags(EVIDENCE)\n self.unset_citation = Suppress(BEL_KEYWORD_CITATION)\n self.unset_statement_group = Suppress(BEL_KEYWORD_STATEMENT_GROUP)\n self.unset_list = delimited_unquoted_list('values')\n self.unset_all = unset_all.setParseAction(self.handle_unset_all)\n self.set_statements = set_tag('action') + MatchFirst([self.set_statement_group, self.set_citation, self.set_evidence, self.set_command, self.set_command_list])\n self.unset_statements = unset_tag('action') + MatchFirst([self.unset_all, self.unset_citation, self.unset_evidence, self.unset_statement_group, self.unset_command, self.unset_list])\n self.language = self.set_statements | self.unset_statements\n", "repository": "pybel/pybel", "test_name": "test_custom_annotation_list", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002291.py"} {"focal_file": "src/pybel/utils.py", "focal_class": null, "focal_method": "subdict_matches", "tests": "import unittest\n\nclass Test_subdict_matches(unittest.TestCase):\n def test_dict_matches_1(self):\n target = {'k1': 'v1', 'k2': 'v2'}\n query = {'k1': 'v1', 'k2': 'v2'}\n self.assertTrue(subdict_matches(target, query))\n\n def test_dict_matches_2(self):\n target = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}\n query = {'k1': 'v1', 'k2': 'v2'}\n self.assertTrue(subdict_matches(target, query))\n\n def test_dict_matches_3(self):\n target = {'k1': 'v1'}\n query = {'k1': 'v1', 'k2': 'v2'}\n self.assertFalse(subdict_matches(target, query))\n\n def test_dict_matches_4(self):\n target = {'k1': 'v1', 'k2': 'v4', 'k3': 'v3'}\n query = {'k1': 'v1', 'k2': 'v2'}\n self.assertFalse(subdict_matches(target, query))\n\n def test_dict_matches_5(self):\n target = {'k1': 'v1', 'k2': 'v2'}\n query = {'k1': 'v1', 'k2': ['v2', 'v3']}\n self.assertTrue(subdict_matches(target, query))\n\n def test_dict_matches_6(self):\n target = {'k1': 'v1', 'k2': ['v2', 'v3']}\n query = {'k1': 'v1', 'k2': 'v4'}\n self.assertFalse(subdict_matches(target, query))\n\n def test_dict_matches_7_partial(self):\n \"\"\"Tests a partial match\"\"\"\n target = {'k1': 'v1', 'k2': 'v2'}\n query = {'k1': 'v1', 'k2': {'v2': 'v3'}}\n self.assertFalse(subdict_matches(target, query))\n\n def test_dict_matches_7_exact(self):\n \"\"\"Test a partial match.\"\"\"\n target = {'k1': 'v1', 'k2': 'v2'}\n query = {'k1': 'v1', 'k2': {'v2': 'v3'}}\n self.assertFalse(subdict_matches(target, query, partial_match=False))\n\n def test_dict_matches_8_partial(self):\n \"\"\"Test a partial match.\"\"\"\n target = {'k1': 'v1', 'k2': {'v2': 'v3', 'v4': 'v5'}}\n query = {'k1': 'v1', 'k2': {'v2': 'v3'}}\n self.assertTrue(subdict_matches(target, query))\n", "method_code": "def subdict_matches(target: Mapping, query: Mapping, partial_match: bool=True) -> bool:\n \"\"\"Check if all the keys in the query dict are in the target dict, and that their values match.\n\n 1. Checks that all keys in the query dict are in the target dict\n 2. Matches the values of the keys in the query dict\n a. If the value is a string, then must match exactly\n b. If the value is a set/list/tuple, then will match any of them\n c. If the value is a dict, then recursively check if that subdict matches\n\n :param target: The dictionary to search\n :param query: A query dict with keys to match\n :param partial_match: Should the query values be used as partial or exact matches? Defaults to :code:`True`.\n :return: if all keys in b are in target_dict and their values match\n \"\"\"\n for k, v in query.items():\n if k not in target:\n return False\n elif not isinstance(v, (int, str, dict, Iterable)):\n raise ValueError('invalid value: {}'.format(v))\n elif isinstance(v, (int, str)) and target[k] != v:\n return False\n elif isinstance(v, dict):\n if partial_match:\n if not isinstance(target[k], dict):\n return False\n elif not subdict_matches(target[k], v, partial_match):\n return False\n elif not partial_match and target[k] != v:\n return False\n elif isinstance(v, Iterable) and target[k] not in v:\n return False\n return True", "context": "def subdict_matches(target: Mapping, query: Mapping, partial_match: bool=True) -> bool: ...\ndef expand_dict(flat_dict, sep: str='_'): ...\ndef flatten_dict(data: Mapping[str, Any], parent_key: str='', sep: str='_') -> Mapping[str, str]: ...\ndef tokenize_version(version_string: str) -> Tuple[int, int, int]: ...\ndef ensure_quotes(s: str) -> str: ...\ndef valid_date(s: str) -> bool: ...\ndef valid_date_version(s: str) -> bool: ...\ndef _validate_date_fmt(s: str, fmt: str) -> bool: ...\ndef parse_datetime(s: str) -> datetime.date: ...\ndef _get_citation_str(data: Mapping) -> Optional[str]: ...\ndef hash_edge(source, target, edge_data: EdgeData) -> str: ...\ndef _get_edge_tuple(source, target, edge_data: EdgeData) -> Tuple[str, str, Optional[str], Optional[str], CanonicalEdge]: ...\ndef subdict_matches(target: Mapping, query: Mapping, partial_match: bool=True) -> bool: ...\ndef hash_dump(data) -> str: ...\ndef canonicalize_edge(edge_data: EdgeData) -> CanonicalEdge: ...\ndef _canonicalize_edge_modifications(edge_data: EdgeData) -> Optional[Tuple]: ...\ndef get_corresponding_pickle_path(path: str) -> str: ...\ndef multidict(pairs: typing.Iterable[Tuple[X, Y]]) -> Mapping[X, List[Y]]: ...\n", "repository": "pybel/pybel", "test_name": "test_dict_matches_1", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002292.py"} {"focal_file": "src/pybel/struct/getters.py", "focal_class": null, "focal_method": "get_tf_pairs", "tests": "import unittest\n\nclass Test_get_tf_pairs(unittest.TestCase):\n def test_get_tf_pairs(self):\n \"\"\"Test iterating over transcription factor pairs.\"\"\"\n graph = BELGraph()\n p1, p2, p3 = (Protein('test', str(i)) for i in range(1, 4))\n r4, r5, r6 = (Rna('test', str(j)) for j in range(4, 7))\n g4 = r4.get_gene()\n self.assertIsNotNone(g4)\n g5 = r5.get_gene()\n self.assertIsNotNone(g5)\n c14, c25 = (ComplexAbundance([p1, g4]), ComplexAbundance([p2, g5]))\n _tf_up(graph, p1, r4)\n _tf_down(graph, p2, r5)\n graph.add_correlation(p3, r6, citation=n(), evidence=n())\n self.assertEqual({p1, p2, p3, r4, r5, r6, g4, g5, c14, c25}, set(graph))\n expected_edges = [(c14, r4), (p1, c14), (g4, c14), (c25, r5), (p2, c25), (g5, c25), (p3, r6), (r6, p3)]\n sorted_expected_edges = sorted(expected_edges, key=_bel_pair_key)\n sorted_actual_edges = sorted(graph.edges(), key=_bel_pair_key)\n self.assertEqual(sorted_expected_edges, sorted_actual_edges)\n pairs = set(get_tf_pairs(graph))\n expected_pairs = {(p1, r4, +1), (p2, r5, -1)}\n self.assertEqual(expected_pairs, pairs)\n", "method_code": "def get_tf_pairs(graph: BELGraph, direct_only: bool=False) -> Iterable[Tuple[Protein, Rna, int]]:\n \"\"\"Iterate pairs of ``p(X)`` and ``r(Y)`` such that ``complex(p(X), g(Y)) -> r(Y)``.\n\n :param graph: A BEL graph\n :param direct_only: If true, only uses directlyIncreases and directlyDecreases relations. Otherwise, allows\n indirect relations.\n \"\"\"\n if direct_only:\n _inc, _dec = ({DIRECTLY_INCREASES}, {DIRECTLY_DECREASES})\n else:\n _inc, _dec = (CAUSAL_INCREASE_RELATIONS, CAUSAL_DECREASE_RELATIONS)\n for tf in _iterate_proteins(graph):\n for tf_gene in graph[tf]:\n if not isinstance(tf_gene, ComplexAbundance):\n continue\n if tf not in tf_gene.members:\n continue\n other_members = [m for m in tf_gene.members if m != tf]\n if 1 != len(other_members):\n continue\n target_gene = other_members[0]\n if not isinstance(target_gene, Gene):\n continue\n if target_gene.variants:\n target_gene = target_gene.get_parent()\n target_rna = target_gene.get_rna()\n if target_rna not in graph:\n continue\n for edge in graph[tf_gene][target_rna].values():\n relation = edge[RELATION]\n if relation in _inc:\n yield (tf, target_rna, +1)\n elif relation in _dec:\n yield (tf, target_rna, -1)", "context": "def get_tf_pairs(graph: BELGraph, direct_only: bool=False) -> Iterable[Tuple[Protein, Rna, int]]: ...\ndef get_tf_pairs(graph: BELGraph, direct_only: bool=False) -> Iterable[Tuple[Protein, Rna, int]]: ...\ndef _iterate_proteins(graph: BELGraph) -> Iterable[Protein]: ...\n", "repository": "pybel/pybel", "test_name": "test_get_tf_pairs", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002293.py"} {"focal_file": "src/pybel/struct/node_utils.py", "focal_class": null, "focal_method": "reaction_cartesian_expansion", "tests": "import unittest\n\nclass Test_reaction_cartesian_expansion(unittest.TestCase):\n def test_flatten_reaction(self):\n \"\"\"Test flattening a reaction.\"\"\"\n single_reaction_graph_copy = single_reaction_graph.copy()\n self.assertEqual(single_reaction_graph_copy.number_of_nodes(), 7)\n self.assertEqual(single_reaction_graph_copy.number_of_edges(), 7)\n reaction_cartesian_expansion(single_reaction_graph_copy)\n self.assertEqual(single_reaction_graph_copy.number_of_nodes(), 6)\n self.assertEqual(single_reaction_graph_copy.number_of_edges(), 8)\n pairs = [(glucose, INCREASES, glucose_6_phosphate), (glucose, INCREASES, adp), (hk1, INCREASES, glucose_6_phosphate), (hk1, INCREASES, adp), (atp, INCREASES, glucose_6_phosphate), (atp, INCREASES, adp), (phosphate, INCREASES, glucose_6_phosphate), (phosphate, INCREASES, adp)]\n for source, target, data in single_reaction_graph_copy.edges(data=True):\n self.assertIn((source, INCREASES, target), pairs)\n\n def test_flatten_reaction_2(self):\n \"\"\"Test flattening a qualified reaction.\"\"\"\n node_increases_reaction_graph = BELGraph()\n glycolisis_step_1 = Reaction(reactants=[glucose, hk1, atp], products=[glucose_6_phosphate, adp, hk1])\n node_increases_reaction_graph.add_increases(glucose_6_phosphate, glycolisis_step_1, citation='X', evidence='X')\n self.assertEqual(node_increases_reaction_graph.number_of_nodes(), 6)\n self.assertEqual(node_increases_reaction_graph.number_of_edges(), 7)\n reaction_cartesian_expansion(node_increases_reaction_graph)\n self.assertEqual(node_increases_reaction_graph.number_of_nodes(), 5)\n self.assertEqual(node_increases_reaction_graph.number_of_edges(), 12)\n\n def test_flatten_reaction_3(self):\n \"\"\"Test flattening a graph containing 2 reactions connected to each other.\"\"\"\n two_reactions_graph = BELGraph()\n reaction_1 = Reaction(reactants=[glucose, atp], products=hk1)\n reaction_2 = Reaction(reactants=glucose_6_phosphate, products=adp)\n two_reactions_graph.add_increases(reaction_1, reaction_2, citation='X', evidence='X')\n self.assertEqual(two_reactions_graph.number_of_nodes(), 7)\n self.assertEqual(two_reactions_graph.number_of_edges(), 6)\n reaction_cartesian_expansion(two_reactions_graph)\n self.assertEqual(two_reactions_graph.number_of_nodes(), 5)\n self.assertEqual(two_reactions_graph.number_of_edges(), 8)\n", "method_code": "def reaction_cartesian_expansion(graph, accept_unqualified_edges: bool=True) -> None:\n \"\"\"Expand all reactions to simple subject-predicate-object networks.\"\"\"\n for u, v, d in list(graph.edges(data=True)):\n if CITATION not in d and accept_unqualified_edges:\n _reaction_cartesian_expansion_unqualified_helper(graph, u, v, d)\n continue\n if isinstance(u, Reaction) and isinstance(v, Reaction):\n catalysts = _get_catalysts_in_reaction(u) | _get_catalysts_in_reaction(v)\n for reactant, product in chain(itt.product(u.reactants, u.products), itt.product(v.reactants, v.products)):\n if reactant in catalysts or product in catalysts:\n continue\n graph.add_increases(reactant, product, citation=d.get(CITATION), evidence=d.get(EVIDENCE), annotations=d.get(ANNOTATIONS))\n for product, reactant in itt.product(u.products, u.reactants):\n if reactant in catalysts or product in catalysts:\n continue\n graph.add_qualified_edge(product, reactant, relation=d[RELATION], citation=d.get(CITATION), evidence=d.get(EVIDENCE), annotations=d.get(ANNOTATIONS))\n elif isinstance(u, Reaction):\n catalysts = _get_catalysts_in_reaction(u)\n for product in u.products:\n if product in catalysts:\n continue\n if v not in u.products and v not in u.reactants:\n graph.add_increases(product, v, citation=d.get(CITATION), evidence=d.get(EVIDENCE), annotations=d.get(ANNOTATIONS))\n for reactant in u.reactants:\n graph.add_increases(reactant, product, citation=d.get(CITATION), evidence=d.get(EVIDENCE), annotations=d.get(ANNOTATIONS))\n elif isinstance(v, Reaction):\n catalysts = _get_catalysts_in_reaction(v)\n for reactant in v.reactants:\n if reactant in catalysts:\n continue\n if u not in v.products and u not in v.reactants:\n graph.add_increases(u, reactant, citation=d.get(CITATION), evidence=d.get(EVIDENCE), annotations=d.get(ANNOTATIONS))\n for product in v.products:\n graph.add_increases(reactant, product, citation=d.get(CITATION), evidence=d.get(EVIDENCE), annotations=d.get(ANNOTATIONS))\n _remove_reaction_nodes(graph)", "context": "def reaction_cartesian_expansion(graph, accept_unqualified_edges: bool=True) -> None: ...\ndef flatten_list_abundance(node: ListAbundance) -> ListAbundance: ...\ndef list_abundance_expansion(graph) -> None: ...\ndef list_abundance_cartesian_expansion(graph) -> None: ...\ndef _reaction_cartesian_expansion_unqualified_helper(graph, u: BaseEntity, v: BaseEntity, d: dict) -> None: ...\ndef _get_catalysts_in_reaction(reaction: Reaction) -> Set[BaseAbundance]: ...\ndef reaction_cartesian_expansion(graph, accept_unqualified_edges: bool=True) -> None: ...\ndef remove_reified_nodes(graph) -> None: ...\ndef _remove_list_abundance_nodes(graph): ...\ndef _remove_reaction_nodes(graph): ...\ndef _remove_typed_nodes(graph, cls: Union[Type[BaseEntity], Tuple[Type[BaseEntity], ...]]) -> None: ...\n", "repository": "pybel/pybel", "test_name": "test_flatten_reaction", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002294.py"} {"focal_file": "src/pybel/struct/operations.py", "focal_class": null, "focal_method": "left_full_join", "tests": "import unittest\n\nclass Test_left_full_join(unittest.TestCase):\n def test_function(self):\n \"\"\"Test full joining two networks using the function.\"\"\"\n left_full_join(self.g, self.h)\n self._help_check_result(self.g)\n self._help_check_initial_h(self.h)\n", "method_code": "def left_full_join(g, h) -> None:\n \"\"\"Add all nodes and edges from ``h`` to ``g``, in-place for ``g``.\n\n :param pybel.BELGraph g: A BEL graph\n :param pybel.BELGraph h: A BEL graph\n\n Example usage:\n\n >>> import pybel\n >>> g = pybel.from_bel_script('...')\n >>> h = pybel.from_bel_script('...')\n >>> left_full_join(g, h)\n \"\"\"\n g.add_nodes_from(((node, data) for node, data in h.nodes(data=True) if node not in g))\n g.add_edges_from(((u, v, key, data) for u, v, key, data in h.edges(keys=True, data=True) if u not in g or v not in g[u] or key not in g[u][v]))\n update_metadata(h, g)\n g.warnings.extend(h.warnings)", "context": "def left_full_join(g, h) -> None: ...\ndef subgraph(graph, nodes: Iterable[BaseEntity]): ...\ndef left_full_join(g, h) -> None: ...\ndef left_outer_join(g, h) -> None: ...\ndef _left_outer_join_graphs(target, graphs): ...\ndef union(graphs, use_tqdm: bool=False): ...\ndef left_node_intersection_join(g, h): ...\ndef node_intersection(graphs): ...\n", "repository": "pybel/pybel", "test_name": "test_function", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002295.py"} {"focal_file": "src/pybel/struct/operations.py", "focal_class": null, "focal_method": "union", "tests": "import unittest\n\nclass Test_union(unittest.TestCase):\n def test_union(self):\n \"\"\"Test that the union of a pair of graphs is the same as the full join.\"\"\"\n j = union([self.g, self.h])\n self._help_check_result(j)\n self._help_check_initial_g(self.g)\n self._help_check_initial_h(self.h)\n", "method_code": "def union(graphs, use_tqdm: bool=False):\n \"\"\"Take the union over a collection of graphs into a new graph.\n\n Assumes iterator is longer than 2, but not infinite.\n\n :param iter[BELGraph] graphs: An iterator over BEL graphs. Can't be infinite.\n :param use_tqdm: Should a progress bar be displayed?\n :return: A merged graph\n :rtype: BELGraph\n\n Example usage:\n\n >>> import pybel\n >>> g = pybel.from_bel_script('...')\n >>> h = pybel.from_bel_script('...')\n >>> k = pybel.from_bel_script('...')\n >>> merged = union([g, h, k])\n \"\"\"\n it = iter(graphs)\n if use_tqdm:\n it = tqdm(it, desc='taking union')\n try:\n target = next(it)\n except StopIteration as e:\n raise ValueError('no graphs given') from e\n try:\n graph = next(it)\n except StopIteration:\n return target\n else:\n target = target.copy()\n left_full_join(target, graph)\n for graph in it:\n left_full_join(target, graph)\n return target", "context": "def union(graphs, use_tqdm: bool=False): ...\ndef subgraph(graph, nodes: Iterable[BaseEntity]): ...\ndef left_full_join(g, h) -> None: ...\ndef left_outer_join(g, h) -> None: ...\ndef _left_outer_join_graphs(target, graphs): ...\ndef union(graphs, use_tqdm: bool=False): ...\ndef left_node_intersection_join(g, h): ...\ndef node_intersection(graphs): ...\n", "repository": "pybel/pybel", "test_name": "test_union", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002296.py"} {"focal_file": "src/pybel/struct/operations.py", "focal_class": null, "focal_method": "left_outer_join", "tests": "import unittest\n\nclass Test_left_outer_join(unittest.TestCase):\n def test_left_outer_join(self):\n left_outer_join(self.g, self.h)\n self._help_check_initial_h(self.h)\n self._help_check_result(self.g)\n\n def test_left_outer_exhaustive_join(self):\n self.g &= self.h\n left_outer_join(self.g, self.h)\n self._help_check_initial_h(self.h)\n self._help_check_result(self.g)\n", "method_code": "def left_outer_join(g, h) -> None:\n \"\"\"Only add components from the ``h`` that are touching ``g``.\n\n Algorithm:\n\n 1. Identify all weakly connected components in ``h``\n 2. Add those that have an intersection with the ``g``\n\n :param BELGraph g: A BEL graph\n :param BELGraph h: A BEL graph\n\n Example usage:\n\n >>> import pybel\n >>> g = pybel.from_bel_script('...')\n >>> h = pybel.from_bel_script('...')\n >>> left_outer_join(g, h)\n \"\"\"\n g_nodes = set(g)\n for comp in nx.weakly_connected_components(h):\n if g_nodes.intersection(comp):\n h_subgraph = subgraph(h, comp)\n left_full_join(g, h_subgraph)", "context": "def left_outer_join(g, h) -> None: ...\ndef subgraph(graph, nodes: Iterable[BaseEntity]): ...\ndef left_full_join(g, h) -> None: ...\ndef left_outer_join(g, h) -> None: ...\ndef _left_outer_join_graphs(target, graphs): ...\ndef union(graphs, use_tqdm: bool=False): ...\ndef left_node_intersection_join(g, h): ...\ndef node_intersection(graphs): ...\n", "repository": "pybel/pybel", "test_name": "test_left_outer_join", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002297.py"} {"focal_file": "src/pybel/struct/operations.py", "focal_class": null, "focal_method": "left_node_intersection_join", "tests": "import unittest\n\nclass Test_left_node_intersection_join(unittest.TestCase):\n def test_left_node_intersection_join(self):\n j = left_node_intersection_join(self.g, self.h)\n self._help_check_join(j)\n self._help_check_initialize_h(self.h)\n self._help_check_initialize_g(self.g)\n", "method_code": "def left_node_intersection_join(g, h):\n \"\"\"Take the intersection over two graphs.\n\n This intersection of two graphs is defined by the union of the\n sub-graphs induced over the intersection of their nodes\n\n :param BELGraph g: A BEL graph\n :param BELGraph h: A BEL graph\n :rtype: BELGraph\n\n Example usage:\n\n >>> import pybel\n >>> g = pybel.from_bel_script('...')\n >>> h = pybel.from_bel_script('...')\n >>> merged = left_node_intersection_join(g, h)\n \"\"\"\n intersecting = set(g).intersection(set(h))\n g_inter = subgraph(g, intersecting)\n h_inter = subgraph(h, intersecting)\n left_full_join(g_inter, h_inter)\n return g_inter", "context": "def left_node_intersection_join(g, h): ...\ndef subgraph(graph, nodes: Iterable[BaseEntity]): ...\ndef left_full_join(g, h) -> None: ...\ndef left_outer_join(g, h) -> None: ...\ndef _left_outer_join_graphs(target, graphs): ...\ndef union(graphs, use_tqdm: bool=False): ...\ndef left_node_intersection_join(g, h): ...\ndef node_intersection(graphs): ...\n", "repository": "pybel/pybel", "test_name": "test_left_node_intersection_join", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002298.py"} {"focal_file": "src/pybel/struct/operations.py", "focal_class": null, "focal_method": "node_intersection", "tests": "import unittest\n\nclass Test_node_intersection(unittest.TestCase):\n def test_node_intersection(self):\n j = node_intersection([self.h, self.g])\n self._help_check_join(j)\n self._help_check_initialize_h(self.h)\n self._help_check_initialize_g(self.g)\n\n def test_intersection_failure(self):\n with self.assertRaises(ValueError):\n node_intersection([])\n\n def test_intersection_trivial(self):\n res = node_intersection([self.g])\n self.assertEqual(self.g, res)\n", "method_code": "def node_intersection(graphs):\n \"\"\"Take the node intersection over a collection of graphs into a new graph.\n\n This intersection is defined the same way as by :func:`left_node_intersection_join`\n\n :param iter[BELGraph] graphs: An iterable of graphs. Since it's iterated over twice, it gets converted to a\n tuple first, so this isn't a safe operation for infinite lists.\n :rtype: BELGraph\n\n Example usage:\n\n >>> import pybel\n >>> g = pybel.from_bel_script('...')\n >>> h = pybel.from_bel_script('...')\n >>> k = pybel.from_bel_script('...')\n >>> merged = node_intersection([g, h, k])\n \"\"\"\n graphs = tuple(graphs)\n n_graphs = len(graphs)\n if n_graphs == 0:\n raise ValueError('no graphs given')\n if n_graphs == 1:\n return graphs[0]\n nodes = set(graphs[0].nodes())\n for graph in graphs[1:]:\n nodes.intersection_update(graph)\n return union((subgraph(graph, nodes) for graph in graphs))", "context": "def node_intersection(graphs): ...\ndef subgraph(graph, nodes: Iterable[BaseEntity]): ...\ndef left_full_join(g, h) -> None: ...\ndef left_outer_join(g, h) -> None: ...\ndef _left_outer_join_graphs(target, graphs): ...\ndef union(graphs, use_tqdm: bool=False): ...\ndef left_node_intersection_join(g, h): ...\ndef node_intersection(graphs): ...\n", "repository": "pybel/pybel", "test_name": "test_node_intersection", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002299.py"} {"focal_file": "src/pybel/struct/filters/edge_predicate_builders.py", "focal_class": null, "focal_method": "build_pmid_inclusion_filter", "tests": "import unittest\n\nclass Test_build_pmid_inclusion_filter(unittest.TestCase):\n def test_build_pmid_inclusion_filter(self):\n \"\"\"Test building a predicate for a single PubMed identifier.\"\"\"\n pmid_inclusion_filter = build_pmid_inclusion_filter(pmid1)\n self.assertTrue(pmid_inclusion_filter({CITATION: citation_dict(namespace=CITATION_TYPE_PUBMED, identifier=pmid1)}))\n self.assertFalse(pmid_inclusion_filter({CITATION: citation_dict(namespace=CITATION_TYPE_PUBMED, identifier=pmid2)}))\n\n def test_build_pmid_set_inclusion_filter(self):\n \"\"\"Test building a predicate for multiple PubMed identifiers.\"\"\"\n pmids = {pmid1, pmid2}\n pmid_inclusion_filter = build_pmid_inclusion_filter(pmids)\n self.assertTrue(pmid_inclusion_filter({CITATION: citation_dict(namespace=CITATION_TYPE_PUBMED, identifier=pmid1)}))\n self.assertTrue(pmid_inclusion_filter({CITATION: citation_dict(namespace=CITATION_TYPE_PUBMED, identifier=pmid2)}))\n self.assertFalse(pmid_inclusion_filter({CITATION: citation_dict(namespace=CITATION_TYPE_PUBMED, identifier=pmid3)}))\n", "method_code": "def build_pmid_inclusion_filter(pmids: Strings) -> EdgePredicate:\n \"\"\"Build an edge predicate that passes for edges with citations from the given PubMed identifier(s).\n\n :param pmids: A PubMed identifier or list of PubMed identifiers to filter for\n \"\"\"\n if isinstance(pmids, str):\n\n @edge_predicate\n def pmid_inclusion_filter(edge_data: EdgeData) -> bool:\n \"\"\"Pass for edges with PubMed citations matching the contained PubMed identifier.\"\"\"\n return has_pubmed(edge_data) and edge_data[CITATION].identifier == pmids\n elif isinstance(pmids, Iterable):\n pmids = set(pmids)\n\n @edge_predicate\n def pmid_inclusion_filter(edge_data: EdgeData) -> bool:\n \"\"\"Pass for edges with PubMed citations matching one of the contained PubMed identifiers.\"\"\"\n return has_pubmed(edge_data) and edge_data[CITATION].identifier in pmids\n else:\n raise TypeError\n return pmid_inclusion_filter", "context": "def build_pmid_inclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef _annotation_dict_all_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool: ...\ndef build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef _annotation_dict_any_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool: ...\ndef build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: ...\ndef build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: ...\ndef build_relation_predicate(relations: Strings) -> EdgePredicate: ...\ndef build_pmid_inclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef build_author_inclusion_filter(authors: Strings) -> EdgePredicate: ...\n", "repository": "pybel/pybel", "test_name": "test_build_pmid_inclusion_filter", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002300.py"} {"focal_file": "src/pybel/struct/filters/edge_predicate_builders.py", "focal_class": null, "focal_method": "build_author_inclusion_filter", "tests": "import unittest\n\nclass Test_build_author_inclusion_filter(unittest.TestCase):\n def test_build_author_inclusion_filter(self):\n \"\"\"Test building a predicate for a single author.\"\"\"\n author_inclusion_filter = build_author_inclusion_filter(author1)\n self.assertTrue(author_inclusion_filter({CITATION: citation_dict(namespace=CITATION_TYPE_PUBMED, identifier=pmid3, authors=[author1])}))\n self.assertTrue(author_inclusion_filter({CITATION: citation_dict(namespace=CITATION_TYPE_PUBMED, identifier=pmid3, authors=[author1, author2])}))\n self.assertFalse(author_inclusion_filter({CITATION: citation_dict(namespace=CITATION_TYPE_PUBMED, identifier=pmid3, authors=[author3])}))\n\n def test_build_author_set_inclusion_filter(self):\n \"\"\"Test building a predicate for multiple authors.\"\"\"\n author = {author1, author2}\n author_inclusion_filter = build_author_inclusion_filter(author)\n self.assertTrue(author_inclusion_filter({CITATION: {CITATION_AUTHORS: [author1]}}))\n self.assertTrue(author_inclusion_filter({CITATION: {CITATION_AUTHORS: [author1, author2]}}))\n self.assertFalse(author_inclusion_filter({CITATION: {CITATION_AUTHORS: [author3]}}))\n", "method_code": "def build_author_inclusion_filter(authors: Strings) -> EdgePredicate:\n \"\"\"Build an edge predicate that passes for edges with citations written by the given author(s).\"\"\"\n if isinstance(authors, str):\n\n @edge_predicate\n def author_filter(edge_data: EdgeData) -> bool:\n \"\"\"Pass for edges with citations with an author that matches the contained author.\"\"\"\n return has_authors(edge_data) and authors in edge_data[CITATION][CITATION_AUTHORS]\n elif isinstance(authors, Iterable):\n authors = set(authors)\n\n @edge_predicate\n def author_filter(edge_data: EdgeData) -> bool:\n \"\"\"Pass for edges with citations with an author that matches one or more of the contained authors.\"\"\"\n return has_authors(edge_data) and any((author in edge_data[CITATION][CITATION_AUTHORS] for author in authors))\n else:\n raise TypeError\n return author_filter", "context": "def build_author_inclusion_filter(authors: Strings) -> EdgePredicate: ...\ndef _annotation_dict_all_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool: ...\ndef build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef _annotation_dict_any_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool: ...\ndef build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: ...\ndef build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: ...\ndef build_relation_predicate(relations: Strings) -> EdgePredicate: ...\ndef build_pmid_inclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef build_author_inclusion_filter(authors: Strings) -> EdgePredicate: ...\n", "repository": "pybel/pybel", "test_name": "test_build_author_inclusion_filter", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002301.py"} {"focal_file": "src/pybel/struct/filters/node_predicate_builders.py", "focal_class": null, "focal_method": "data_missing_key_builder", "tests": "import unittest\n\nclass Test_data_missing_key_builder(unittest.TestCase):\n def test_data_missing_key_builder(self):\n \"\"\"Test the data_missing_key_builder function.\"\"\"\n graph = BELGraph()\n p1 = protein('HGNC', n())\n p2 = protein('HGNC', n())\n graph.add_node_from_data(p1)\n graph.add_node_from_data(p2)\n key, other_key = ('k1', 'k2')\n data_missing_key = data_missing_key_builder(key)\n graph.nodes[p1][key] = n()\n graph.nodes[p2][other_key] = n()\n nodes = set(filter_nodes(graph, data_missing_key))\n self.assertNotIn(p1, nodes)\n self.assertIn(p2, nodes)\n", "method_code": "def data_missing_key_builder(key: str) -> NodePredicate:\n \"\"\"Build a filter that passes only on nodes that don't have the given key in their data dictionary.\n\n :param str key: A key for the node's data dictionary\n \"\"\"\n\n def data_does_not_contain_key(graph: BELGraph, node: BaseEntity) -> bool:\n \"\"\"Pass only for a node that doesn't contain the enclosed key in its data dictionary.\"\"\"\n return key not in graph.nodes[node]\n return data_does_not_contain_key", "context": "def data_missing_key_builder(key: str) -> NodePredicate: ...\ndef function_inclusion_filter_builder(func: Strings) -> NodePredicate: ...\ndef _single_function_inclusion_filter_builder(func: str) -> NodePredicate: ...\ndef _collection_function_inclusion_builder(funcs: Iterable[str]) -> NodePredicate: ...\ndef function_exclusion_filter_builder(func: Strings) -> NodePredicate: ...\ndef data_missing_key_builder(key: str) -> NodePredicate: ...\ndef build_node_data_search(key: Union[str, List[str]], data_predicate: Callable[[Any], bool]) -> NodePredicate: ...\ndef build_node_graph_data_search(key: Union[str, List[str]], data_predicate: Callable[[Any], bool]) -> NodePredicate: ...\ndef _get_multi_value(d, keys): ...\ndef _get_single_value(d, key): ...\ndef build_node_key_search(query: Strings, key: Union[str, List[str]]) -> NodePredicate: ...\ndef build_node_name_search(query: Strings) -> NodePredicate: ...\ndef namespace_inclusion_builder(namespace: Strings) -> NodePredicate: ...\n", "repository": "pybel/pybel", "test_name": "test_data_missing_key_builder", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002302.py"} {"focal_file": "src/pybel/struct/filters/node_predicate_builders.py", "focal_class": null, "focal_method": "build_node_graph_data_search", "tests": "import unittest\n\nclass Test_build_node_graph_data_search(unittest.TestCase):\n def test_build_node_data_search(self):\n \"\"\"Test build_node_data_search.\"\"\"\n\n def test_key_predicate(datum):\n \"\"\"Check the data is greater than zero.\n\n :rtype: bool\n \"\"\"\n return 0 < datum\n key = n()\n data_predicate = build_node_graph_data_search(key, test_key_predicate)\n graph = BELGraph()\n p1 = protein('HGNC', n())\n graph.add_node_from_data(p1)\n graph.nodes[p1][key] = 0\n self.assertFalse(data_predicate(graph, p1))\n p2 = protein('HGNC', n())\n graph.add_node_from_data(p2)\n graph.nodes[p2][key] = 5\n self.assertTrue(data_predicate(graph, p2))\n p3 = protein('HGNC', n())\n graph.add_node_from_data(p3)\n self.assertFalse(data_predicate(graph, p3))\n", "method_code": "def build_node_graph_data_search(key: Union[str, List[str]], data_predicate: Callable[[Any], bool]) -> NodePredicate:\n \"\"\"Build a function for testing data associated with the node in the graph.\n\n :param key: The node data dictionary key to check\n :param data_predicate: The filter to apply to the node data dictionary\n \"\"\"\n if isinstance(key, tuple):\n _getter = _get_multi_value\n else:\n _getter = _get_single_value\n\n def node_data_filter(graph: BELGraph, node: BaseEntity) -> bool:\n \"\"\"Pass if the given node has a given data annotated and passes the contained filter.\"\"\"\n value = _getter(graph.nodes[node], key)\n return value is not None and data_predicate(value)\n return node_data_filter", "context": "def build_node_graph_data_search(key: Union[str, List[str]], data_predicate: Callable[[Any], bool]) -> NodePredicate: ...\ndef function_inclusion_filter_builder(func: Strings) -> NodePredicate: ...\ndef _single_function_inclusion_filter_builder(func: str) -> NodePredicate: ...\ndef _collection_function_inclusion_builder(funcs: Iterable[str]) -> NodePredicate: ...\ndef function_exclusion_filter_builder(func: Strings) -> NodePredicate: ...\ndef data_missing_key_builder(key: str) -> NodePredicate: ...\ndef build_node_data_search(key: Union[str, List[str]], data_predicate: Callable[[Any], bool]) -> NodePredicate: ...\ndef build_node_graph_data_search(key: Union[str, List[str]], data_predicate: Callable[[Any], bool]) -> NodePredicate: ...\ndef _get_multi_value(d, keys): ...\ndef _get_single_value(d, key): ...\ndef build_node_key_search(query: Strings, key: Union[str, List[str]]) -> NodePredicate: ...\ndef build_node_name_search(query: Strings) -> NodePredicate: ...\ndef namespace_inclusion_builder(namespace: Strings) -> NodePredicate: ...\n", "repository": "pybel/pybel", "test_name": "test_build_node_data_search", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002303.py"} {"focal_file": "src/pybel/struct/filters/node_predicate_builders.py", "focal_class": null, "focal_method": "build_node_name_search", "tests": "import unittest\n\nclass Test_build_node_name_search(unittest.TestCase):\n def test_build_node_name_search(self):\n graph = BELGraph()\n p1 = protein('HGNC', 'APP')\n graph.add_node_from_data(p1)\n p2 = protein('HGNC', 'MAPK')\n graph.add_node_from_data(p2)\n node_name_search = build_node_name_search(query='APP')\n self.assertTrue(node_name_search(graph, p1))\n self.assertFalse(node_name_search(graph, p2))\n", "method_code": "def build_node_name_search(query: Strings) -> NodePredicate:\n \"\"\"Search nodes' names.\n\n Is a thin wrapper around :func:`build_node_key_search` with :data:`pybel.constants.NAME`\n\n :param query: The query string or strings to check if they're in the node name\n \"\"\"\n return build_node_key_search(query=query, key=[CONCEPT, NAME])", "context": "def build_node_name_search(query: Strings) -> NodePredicate: ...\ndef function_inclusion_filter_builder(func: Strings) -> NodePredicate: ...\ndef _single_function_inclusion_filter_builder(func: str) -> NodePredicate: ...\ndef _collection_function_inclusion_builder(funcs: Iterable[str]) -> NodePredicate: ...\ndef function_exclusion_filter_builder(func: Strings) -> NodePredicate: ...\ndef data_missing_key_builder(key: str) -> NodePredicate: ...\ndef build_node_data_search(key: Union[str, List[str]], data_predicate: Callable[[Any], bool]) -> NodePredicate: ...\ndef build_node_graph_data_search(key: Union[str, List[str]], data_predicate: Callable[[Any], bool]) -> NodePredicate: ...\ndef _get_multi_value(d, keys): ...\ndef _get_single_value(d, key): ...\ndef build_node_key_search(query: Strings, key: Union[str, List[str]]) -> NodePredicate: ...\ndef build_node_name_search(query: Strings) -> NodePredicate: ...\ndef namespace_inclusion_builder(namespace: Strings) -> NodePredicate: ...\n", "repository": "pybel/pybel", "test_name": "test_build_node_name_search", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002304.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "has_polarity", "tests": "import unittest\n\nclass Test_has_polarity(unittest.TestCase):\n def test_has_polarity_dict(self):\n for relation in POLAR_RELATIONS:\n self.assertTrue(has_polarity({RELATION: relation}))\n self.assertFalse(has_polarity({RELATION: ASSOCIATION}))\n\n def test_has_polarity(self):\n g = BELGraph()\n a, b, c = (protein(n(), n()) for _ in range(3))\n key1 = g.add_increases(a, b, citation=n(), evidence=n())\n self.assertTrue(has_polarity(g, a, b, key1))\n key2 = g.add_association(b, c, citation=n(), evidence=n())\n self.assertFalse(has_polarity(g, b, c, key2))\n", "method_code": "def has_polarity(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge has polarity.\"\"\"\n return edge_data[RELATION] in POLAR_RELATIONS", "context": "@edge_predicate\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_has_polarity_dict", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002305.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "has_provenance", "tests": "import unittest\n\nclass Test_has_provenance(unittest.TestCase):\n def test_has_provenance(self):\n self.assertFalse(has_provenance({}))\n self.assertFalse(has_provenance({CITATION: {}}))\n self.assertFalse(has_provenance({EVIDENCE: ''}))\n self.assertTrue(has_provenance({CITATION: {}, EVIDENCE: ''}))\n", "method_code": "def has_provenance(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge has provenance information (i.e. citation and evidence).\"\"\"\n return CITATION in edge_data and EVIDENCE in edge_data", "context": "@edge_predicate\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_has_provenance", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002306.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "has_pubmed", "tests": "import unittest\n\nclass Test_has_pubmed(unittest.TestCase):\n def test_has_pubmed(self):\n self.assertTrue(has_pubmed({CITATION: {NAMESPACE: CITATION_TYPE_PUBMED}}))\n self.assertFalse(has_pubmed({CITATION: {NAMESPACE: CITATION_TYPE_URL}}))\n self.assertFalse(has_pubmed({}))\n", "method_code": "def has_pubmed(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge has a PubMed citation.\"\"\"\n return CITATION in edge_data and edge_data[CITATION][NAMESPACE].lower() in ('pubmed', 'pmid')", "context": "@edge_predicate\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_has_pubmed", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002307.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "has_authors", "tests": "import unittest\n\nclass Test_has_authors(unittest.TestCase):\n def test_has_authors(self):\n self.assertFalse(has_authors({}))\n self.assertFalse(has_authors({CITATION: {}}))\n self.assertFalse(has_authors({CITATION: {CITATION_AUTHORS: []}}))\n self.assertTrue(has_authors({CITATION: {CITATION_AUTHORS: ['One guy']}}))\n", "method_code": "def has_authors(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge contains author information for its citation.\"\"\"\n return CITATION in edge_data and CITATION_AUTHORS in edge_data[CITATION] and edge_data[CITATION][CITATION_AUTHORS]", "context": "@edge_predicate\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_has_authors", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002308.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "is_causal_relation", "tests": "import unittest\n\nclass Test_is_causal_relation(unittest.TestCase):\n def test_is_causal(self):\n self.assertTrue(is_causal_relation({RELATION: INCREASES}))\n self.assertTrue(is_causal_relation({RELATION: DECREASES}))\n self.assertTrue(is_causal_relation({RELATION: DIRECTLY_INCREASES}))\n self.assertTrue(is_causal_relation({RELATION: DIRECTLY_DECREASES}))\n self.assertFalse(is_causal_relation({RELATION: ASSOCIATION}))\n self.assertFalse(is_causal_relation({RELATION: POSITIVE_CORRELATION}))\n", "method_code": "def is_causal_relation(edge_data: EdgeData) -> bool:\n \"\"\"Check if the given relation is causal.\"\"\"\n return edge_data[RELATION] in CAUSAL_RELATIONS", "context": "@edge_predicate\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_is_causal", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002309.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "is_direct_causal_relation", "tests": "import unittest\n\nclass Test_is_direct_causal_relation(unittest.TestCase):\n def test_is_direct_causal(self):\n self.assertTrue(is_direct_causal_relation({RELATION: DIRECTLY_INCREASES}))\n self.assertTrue(is_direct_causal_relation({RELATION: DIRECTLY_DECREASES}))\n self.assertFalse(is_direct_causal_relation({RELATION: INCREASES}))\n self.assertFalse(is_direct_causal_relation({RELATION: DECREASES}))\n self.assertFalse(is_direct_causal_relation({RELATION: ASSOCIATION}))\n self.assertFalse(is_direct_causal_relation({RELATION: POSITIVE_CORRELATION}))\n", "method_code": "def is_direct_causal_relation(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge is a direct causal relation.\"\"\"\n return edge_data[RELATION] in DIRECT_CAUSAL_RELATIONS", "context": "@edge_predicate\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_is_direct_causal", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002310.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "is_associative_relation", "tests": "import unittest\n\nclass Test_is_associative_relation(unittest.TestCase):\n def test_is_association(self):\n self.assertTrue(is_associative_relation({RELATION: ASSOCIATION}))\n self.assertFalse(is_associative_relation({RELATION: INCREASES}))\n self.assertFalse(is_associative_relation({RELATION: CAUSES_NO_CHANGE}))\n self.assertFalse(is_associative_relation({RELATION: DECREASES}))\n self.assertFalse(is_associative_relation({RELATION: DIRECTLY_INCREASES}))\n self.assertFalse(is_associative_relation({RELATION: DIRECTLY_DECREASES}))\n", "method_code": "def is_associative_relation(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge has an association relation.\"\"\"\n return edge_data[RELATION] == ASSOCIATION", "context": "@edge_predicate\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_is_association", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002311.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "edge_has_degradation", "tests": "import unittest\n\nclass Test_edge_has_degradation(unittest.TestCase):\n def test_has_degradation(self):\n self.assertTrue(edge_has_degradation({SOURCE_MODIFIER: {MODIFIER: DEGRADATION}}))\n self.assertTrue(edge_has_degradation({TARGET_MODIFIER: {MODIFIER: DEGRADATION}}))\n self.assertFalse(edge_has_degradation({SOURCE_MODIFIER: {MODIFIER: TRANSLOCATION}}))\n self.assertFalse(edge_has_degradation({SOURCE_MODIFIER: {MODIFIER: ACTIVITY}}))\n self.assertFalse(edge_has_degradation({SOURCE_MODIFIER: {LOCATION: None}}))\n self.assertFalse(edge_has_degradation({TARGET_MODIFIER: {MODIFIER: TRANSLOCATION}}))\n self.assertFalse(edge_has_degradation({TARGET_MODIFIER: {MODIFIER: ACTIVITY}}))\n self.assertFalse(edge_has_degradation({TARGET_MODIFIER: {LOCATION: None}}))\n", "method_code": "def edge_has_degradation(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge contains a degradation in either the subject or object.\"\"\"\n return _has_modifier(edge_data, DEGRADATION)", "context": "@edge_predicate\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_has_degradation", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002312.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "edge_has_translocation", "tests": "import unittest\n\nclass Test_edge_has_translocation(unittest.TestCase):\n def test_has_translocation(self):\n self.assertTrue(edge_has_translocation({SOURCE_MODIFIER: {MODIFIER: TRANSLOCATION}}))\n self.assertTrue(edge_has_translocation({TARGET_MODIFIER: {MODIFIER: TRANSLOCATION}}))\n self.assertFalse(edge_has_translocation({SOURCE_MODIFIER: {MODIFIER: ACTIVITY}}))\n self.assertFalse(edge_has_translocation({SOURCE_MODIFIER: {LOCATION: None}}))\n self.assertFalse(edge_has_translocation({SOURCE_MODIFIER: {MODIFIER: DEGRADATION}}))\n self.assertFalse(edge_has_translocation({TARGET_MODIFIER: {MODIFIER: ACTIVITY}}))\n self.assertFalse(edge_has_translocation({TARGET_MODIFIER: {LOCATION: None}}))\n self.assertFalse(edge_has_translocation({TARGET_MODIFIER: {MODIFIER: DEGRADATION}}))\n", "method_code": "def edge_has_translocation(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge has a translocation in either the subject or object.\"\"\"\n return _has_modifier(edge_data, TRANSLOCATION)", "context": "@edge_predicate\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_has_translocation", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002313.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "edge_has_activity", "tests": "import unittest\n\nclass Test_edge_has_activity(unittest.TestCase):\n def test_has_activity(self):\n self.assertTrue(edge_has_activity({SOURCE_MODIFIER: {MODIFIER: ACTIVITY}}))\n self.assertTrue(edge_has_activity({TARGET_MODIFIER: {MODIFIER: ACTIVITY}}))\n self.assertFalse(edge_has_activity({SOURCE_MODIFIER: {MODIFIER: TRANSLOCATION}}))\n self.assertFalse(edge_has_activity({TARGET_MODIFIER: {MODIFIER: TRANSLOCATION}}))\n self.assertFalse(edge_has_activity({SOURCE_MODIFIER: {LOCATION: None}}))\n self.assertFalse(edge_has_activity({SOURCE_MODIFIER: {MODIFIER: DEGRADATION}}))\n self.assertFalse(edge_has_activity({TARGET_MODIFIER: {LOCATION: None}}))\n self.assertFalse(edge_has_activity({TARGET_MODIFIER: {MODIFIER: DEGRADATION}}))\n", "method_code": "def edge_has_activity(edge_data: EdgeData) -> bool:\n \"\"\"Check if the edge contains an activity in either the subject or object.\"\"\"\n return _has_modifier(edge_data, ACTIVITY)", "context": "@edge_predicate\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_has_activity", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002314.py"} {"focal_file": "src/pybel/struct/filters/edge_predicates.py", "focal_class": null, "focal_method": "edge_has_annotation", "tests": "import unittest\n\nclass Test_edge_has_annotation(unittest.TestCase):\n def test_has_annotation(self):\n self.assertFalse(edge_has_annotation({}, 'Subgraph'))\n self.assertFalse(edge_has_annotation({ANNOTATIONS: {}}, 'Subgraph'))\n self.assertFalse(edge_has_annotation({ANNOTATIONS: {'Subgraph': None}}, 'Subgraph'))\n self.assertTrue(edge_has_annotation({ANNOTATIONS: {'Subgraph': 'value'}}, 'Subgraph'))\n self.assertFalse(edge_has_annotation({ANNOTATIONS: {'Nope': 'value'}}, 'Subgraph'))\n", "method_code": "def edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]:\n \"\"\"Check if an edge has the given annotation.\n\n :param edge_data: The data dictionary from a BELGraph's edge\n :param key: An annotation key\n :return: If the annotation key is present in the current data dictionary\n\n For example, it might be useful to print all edges that are annotated with 'Subgraph':\n\n >>> from pybel.examples import sialic_acid_graph\n >>> from pybel.examples.sialic_acid_example import sialic_acid_cd33_complex, cd33\n >>> edges = {\n ... (u, v)\n ... for u, v, data in sialic_acid_graph.edges(data=True)\n ... if edge_has_annotation(data, 'Species')\n ... }\n >>> assert (sialic_acid_cd33_complex, cd33) in edges\n \"\"\"\n annotations = edge_data.get(ANNOTATIONS)\n if annotations is None:\n return None\n return annotations.get(key)", "context": "def edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef edge_predicate(func: DictEdgePredicate) -> EdgePredicate: ...\ndef true_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef false_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\ndef has_provenance(edge_data: EdgeData) -> bool: ...\ndef has_pubmed(edge_data: EdgeData) -> bool: ...\ndef has_pmc(edge_data: EdgeData) -> bool: ...\ndef has_authors(edge_data: EdgeData) -> bool: ...\ndef is_causal_relation(edge_data: EdgeData) -> bool: ...\ndef not_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_direct_causal_relation(edge_data: EdgeData) -> bool: ...\ndef is_associative_relation(edge_data: EdgeData) -> bool: ...\ndef has_polarity(edge_data: EdgeData) -> bool: ...\ndef _has_modifier(edge_data: EdgeData, modifier: str) -> bool: ...\ndef edge_has_activity(edge_data: EdgeData) -> bool: ...\ndef edge_has_translocation(edge_data: EdgeData) -> bool: ...\ndef edge_has_degradation(edge_data: EdgeData) -> bool: ...\ndef edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]: ...\ndef has_pathology_causal(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: ...\n", "repository": "pybel/pybel", "test_name": "test_has_annotation", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002315.py"} {"focal_file": "src/pybel/struct/filters/edge_predicate_builders.py", "focal_class": null, "focal_method": "build_annotation_dict_any_filter", "tests": "import unittest\n\nclass Test_build_annotation_dict_any_filter(unittest.TestCase):\n def test_any_filter(self):\n graph = BELGraph()\n graph.annotation_list['A'] = set('12345')\n graph.add_increases(Protein(n(), n()), Protein(n(), n()), citation=n(), evidence=n(), annotations={'A': {'1', '2', '3'}})\n self.assertEqual(1, count_passed_edge_filter(graph, build_annotation_dict_any_filter(graph._clean_annotations({'A': {'1'}}))))\n self.assertEqual(1, count_passed_edge_filter(graph, build_annotation_dict_any_filter(graph._clean_annotations({'A': {'1', '2'}}))))\n self.assertEqual(1, count_passed_edge_filter(graph, build_annotation_dict_any_filter(graph._clean_annotations({'A': {'1', '2', '3'}}))))\n", "method_code": "def build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate:\n \"\"\"Build an edge predicate that passes for edges whose data dictionaries match the given dictionary.\n\n If the given dictionary is empty, will always evaluate to true.\n\n :param annotations: The annotation query dict to match\n \"\"\"\n if not annotations:\n return true_edge_predicate\n\n @edge_predicate\n def annotation_dict_any_filter(edge_data: EdgeData) -> bool:\n \"\"\"Check if the any of the annotations in the enclosed query match.\"\"\"\n return _annotation_dict_any_filter(edge_data, query=annotations)\n return annotation_dict_any_filter", "context": "def build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef _annotation_dict_all_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool: ...\ndef build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef _annotation_dict_any_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool: ...\ndef build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: ...\ndef build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: ...\ndef build_relation_predicate(relations: Strings) -> EdgePredicate: ...\ndef build_pmid_inclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef build_author_inclusion_filter(authors: Strings) -> EdgePredicate: ...\n", "repository": "pybel/pybel", "test_name": "test_any_filter", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002316.py"} {"focal_file": "src/pybel/struct/filters/edge_predicate_builders.py", "focal_class": null, "focal_method": "build_annotation_dict_all_filter", "tests": "import unittest\n\nclass Test_build_annotation_dict_all_filter(unittest.TestCase):\n def test_all_filter(self):\n graph = BELGraph()\n graph.annotation_list['A'] = set('12345')\n graph.add_increases(Protein(n(), n()), Protein(n(), n()), citation=n(), evidence=n(), annotations={'A': {'1', '2', '3'}})\n self.assertEqual(1, count_passed_edge_filter(graph, build_annotation_dict_all_filter(graph._clean_annotations({'A': {'1'}}))))\n self.assertEqual(1, count_passed_edge_filter(graph, build_annotation_dict_all_filter(graph._clean_annotations({'A': {'1', '2'}}))))\n self.assertEqual(1, count_passed_edge_filter(graph, build_annotation_dict_all_filter(graph._clean_annotations({'A': {'1', '2', '3'}}))))\n self.assertEqual(0, count_passed_edge_filter(graph, build_annotation_dict_all_filter(graph._clean_annotations({'A': {'1', '2', '3', '4'}}))))\n self.assertEqual(0, count_passed_edge_filter(graph, build_annotation_dict_all_filter(graph._clean_annotations({'A': {'4'}}))))\n", "method_code": "def build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate:\n \"\"\"Build an edge predicate for edges whose annotations are super-dictionaries of the given dictionary.\n\n If no annotations are given, will always evaluate to true.\n\n :param annotations: The annotation query dict to match\n \"\"\"\n if not annotations:\n return true_edge_predicate\n\n @edge_predicate\n def annotation_dict_all_filter(edge_data: EdgeData) -> bool:\n \"\"\"Check if the all of the annotations in the enclosed query match.\"\"\"\n return _annotation_dict_all_filter(edge_data, query=annotations)\n return annotation_dict_all_filter", "context": "def build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef _annotation_dict_all_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool: ...\ndef build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef _annotation_dict_any_filter(edge_data: EdgeData, query: Mapping[str, Iterable[str]]) -> bool: ...\ndef build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: ...\ndef build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: ...\ndef build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: ...\ndef build_relation_predicate(relations: Strings) -> EdgePredicate: ...\ndef build_pmid_inclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate: ...\ndef build_author_inclusion_filter(authors: Strings) -> EdgePredicate: ...\n", "repository": "pybel/pybel", "test_name": "test_all_filter", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002317.py"} {"focal_file": "src/pybel/testing/mock_manager.py", "focal_class": "MockQueryManager", "focal_method": "insert_graph", "tests": "import unittest\n\nclass Test_MockQueryManager_insert_graph(unittest.TestCase):\n def test_add_graph(self):\n \"\"\"Test adding a graph with insert_graph.\"\"\"\n manager = MockQueryManager()\n graph = egf_graph.copy()\n manager.insert_graph(graph)\n self.assertEqual(1, manager.count_networks())\n", "method_code": " def insert_graph(self, graph) -> Network:\n \"\"\"Insert a graph and ensure its nodes are cached.\n \n :param pybel.BELGraph graph:\n \"\"\"\n network_id = len(self.graphs)\n self.graphs.append(graph)\n self.id_graph[network_id] = graph\n for node in graph:\n self.hash_to_node[node.md5] = node\n return Network(id=network_id)\n ", "context": "class MockQueryManager():\n def insert_graph(self, graph) -> Network: ...\n def __init__(self, graphs=None): ...\n def count_networks(self) -> int: ...\n def get_graph_by_ids(self, network_ids: Iterable[int]): ...\n def get_dsl_by_hash(self, md5: str): ...\n\n self.graphs = []\n self.hash_to_node = {}\n self.id_graph = {}\n", "repository": "pybel/pybel", "test_name": "test_add_graph", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002318.py"} {"focal_file": "src/pybel/testing/generate.py", "focal_class": null, "focal_method": "generate_random_graph", "tests": "import unittest\n\nclass Test_generate_random_graph(unittest.TestCase):\n def test_random_sample(self):\n \"\"\"Test generating multiple random samples and combining them.\"\"\"\n graph = generate_random_graph(50, 1000)\n query = self.add_query(graph)\n query.append_seeding_sample(number_edges=10)\n query.append_seeding_sample(number_edges=10)\n result = self.run_query()\n self.assertIn(result.number_of_edges(), {16, 17, 18, 19, 20}, msg='This will rail randomly sometimes, lol')\n", "method_code": "def generate_random_graph(n_nodes, n_edges, namespace='NS'):\n \"\"\"Generate a sub-graph with random nodes and edges.\n\n :param int n_nodes: Number of nodes to make\n :param int n_edges: Number of edges to make\n :param str namespace: The namespace of the nodes to use\n :rtype: pybel.BELGraph\n \"\"\"\n graph = BELGraph()\n nodes = [protein(namespace=namespace, name=str(i)) for i in range(1, n_nodes)]\n edges = list(itt.combinations(nodes, r=2))\n edge_sample = random.sample(edges, n_edges)\n for u, v in edge_sample:\n graph.add_increases(u, v, citation=n(), evidence=n())\n return graph", "context": "def generate_random_graph(n_nodes, n_edges, namespace='NS'): ...\ndef generate_random_graph(n_nodes, n_edges, namespace='NS'): ...\n", "repository": "pybel/pybel", "test_name": "test_random_sample", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002319.py"} {"focal_file": "src/pybel/struct/summary/edge_summary.py", "focal_class": null, "focal_method": "get_annotation_values", "tests": "import unittest\n\nclass Test_get_annotation_values(unittest.TestCase):\n def test_get_annotation_values(self):\n \"\"\"Test getting annotation values.\"\"\"\n expected = {'Confidence': {Entity(namespace='Confidence', identifier='High'), Entity(namespace='Confidence', identifier='Low')}, 'Species': {Entity(namespace='Species', identifier='9606')}}\n self.assertEqual({'Confidence', 'Species'}, get_annotations(sialic_acid_graph))\n self.assertEqual({'Confidence': 8, 'Species': 8}, dict(count_annotations(sialic_acid_graph)))\n annotation_values_by_annotation = get_annotation_values_by_annotation(sialic_acid_graph)\n self.assertEqual(expected, annotation_values_by_annotation)\n annotation_values = get_annotation_values(sialic_acid_graph, 'Confidence')\n self.assertEqual(expected['Confidence'], annotation_values)\n", "method_code": "def get_annotation_values(graph: BELGraph, annotation: str) -> Set[Entity]:\n \"\"\"Get all values for the given annotation.\n\n :param graph: A BEL graph\n :param annotation: The annotation to summarize\n :return: A set of all annotation values\n \"\"\"\n return set(iter_annotation_values(graph, annotation))", "context": "def get_annotation_values(graph: BELGraph, annotation: str) -> Set[Entity]: ...\ndef iter_annotation_value_pairs(graph: BELGraph) -> Iterable[Tuple[str, Entity]]: ...\ndef iter_annotation_values(graph: BELGraph, annotation: str) -> Iterable[Entity]: ...\ndef _group_dict_set(iterator): ...\ndef get_annotation_values_by_annotation(graph: BELGraph) -> Mapping[str, Set[Entity]]: ...\ndef get_annotation_values(graph: BELGraph, annotation: str) -> Set[Entity]: ...\ndef count_relations(graph: BELGraph) -> Counter: ...\ndef get_unused_annotations(graph: BELGraph) -> Set[str]: ...\ndef get_annotations(graph: BELGraph) -> Set[str]: ...\ndef count_annotations(graph: BELGraph) -> Counter: ...\ndef _annotation_iter_helper(graph: BELGraph) -> Iterable[str]: ...\ndef get_unused_list_annotation_values(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef get_metaedge_to_key(graph: BELGraph) -> Mapping[CanonicalEdge, Set[Tuple[BaseEntity, BaseEntity, str]]]: ...\ndef iter_sample_metaedges(graph: BELGraph): ...\n", "repository": "pybel/pybel", "test_name": "test_get_annotation_values", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002320.py"} {"focal_file": "src/pybel/struct/summary/edge_summary.py", "focal_class": null, "focal_method": "get_unused_annotations", "tests": "import unittest\n\nclass Test_get_unused_annotations(unittest.TestCase):\n def test_get_unused_annotation_url(self):\n graph = BELGraph()\n name = n()\n graph.annotation_url[name] = n()\n self.assertEqual({name}, get_unused_annotations(graph))\n\n def test_get_unused_annotation_list(self):\n graph = BELGraph()\n name = n()\n graph.annotation_pattern[name] = {n(), n(), n()}\n self.assertEqual({name}, get_unused_annotations(graph))\n", "method_code": "def get_unused_annotations(graph: BELGraph) -> Set[str]:\n \"\"\"Get the set of all annotations that are defined in a graph, but are never used.\n\n :param graph: A BEL graph\n :return: A set of annotations\n \"\"\"\n return graph.defined_annotation_keywords - get_annotations(graph)", "context": "def get_unused_annotations(graph: BELGraph) -> Set[str]: ...\ndef iter_annotation_value_pairs(graph: BELGraph) -> Iterable[Tuple[str, Entity]]: ...\ndef iter_annotation_values(graph: BELGraph, annotation: str) -> Iterable[Entity]: ...\ndef _group_dict_set(iterator): ...\ndef get_annotation_values_by_annotation(graph: BELGraph) -> Mapping[str, Set[Entity]]: ...\ndef get_annotation_values(graph: BELGraph, annotation: str) -> Set[Entity]: ...\ndef count_relations(graph: BELGraph) -> Counter: ...\ndef get_unused_annotations(graph: BELGraph) -> Set[str]: ...\ndef get_annotations(graph: BELGraph) -> Set[str]: ...\ndef count_annotations(graph: BELGraph) -> Counter: ...\ndef _annotation_iter_helper(graph: BELGraph) -> Iterable[str]: ...\ndef get_unused_list_annotation_values(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef get_metaedge_to_key(graph: BELGraph) -> Mapping[CanonicalEdge, Set[Tuple[BaseEntity, BaseEntity, str]]]: ...\ndef iter_sample_metaedges(graph: BELGraph): ...\n", "repository": "pybel/pybel", "test_name": "test_get_unused_annotation_url", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002321.py"} {"focal_file": "src/pybel/struct/summary/edge_summary.py", "focal_class": null, "focal_method": "get_unused_list_annotation_values", "tests": "import unittest\n\nclass Test_get_unused_list_annotation_values(unittest.TestCase):\n def test_get_unused_annotation_list_values(self):\n \"\"\"Test getting unused annotation list values.\"\"\"\n graph = BELGraph()\n annotation_key = 'test'\n graph.annotation_list[annotation_key] = set('abc')\n graph.add_increases(protein(n(), n()), protein(n(), n()), citation=n(), evidence=n(), annotations={annotation_key: {'a'}})\n rv = get_unused_list_annotation_values(graph)\n self.assertIsInstance(rv, dict)\n self.assertEqual({annotation_key: set('bc')}, rv)\n", "method_code": "def get_unused_list_annotation_values(graph: BELGraph) -> Mapping[str, Set[str]]:\n \"\"\"Get all of the unused values for list annotations.\n\n :param graph: A BEL graph\n :return: A dictionary of {str annotation: set of str values that aren't used}\n \"\"\"\n result = {}\n for annotation, values in graph.annotation_list.items():\n unused = values - {e.identifier for e in get_annotation_values(graph, annotation)}\n if unused:\n result[annotation] = unused\n return result", "context": "def get_unused_list_annotation_values(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef iter_annotation_value_pairs(graph: BELGraph) -> Iterable[Tuple[str, Entity]]: ...\ndef iter_annotation_values(graph: BELGraph, annotation: str) -> Iterable[Entity]: ...\ndef _group_dict_set(iterator): ...\ndef get_annotation_values_by_annotation(graph: BELGraph) -> Mapping[str, Set[Entity]]: ...\ndef get_annotation_values(graph: BELGraph, annotation: str) -> Set[Entity]: ...\ndef count_relations(graph: BELGraph) -> Counter: ...\ndef get_unused_annotations(graph: BELGraph) -> Set[str]: ...\ndef get_annotations(graph: BELGraph) -> Set[str]: ...\ndef count_annotations(graph: BELGraph) -> Counter: ...\ndef _annotation_iter_helper(graph: BELGraph) -> Iterable[str]: ...\ndef get_unused_list_annotation_values(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef get_metaedge_to_key(graph: BELGraph) -> Mapping[CanonicalEdge, Set[Tuple[BaseEntity, BaseEntity, str]]]: ...\ndef iter_sample_metaedges(graph: BELGraph): ...\n", "repository": "pybel/pybel", "test_name": "test_get_unused_annotation_list_values", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002322.py"} {"focal_file": "src/pybel/struct/summary/node_summary.py", "focal_class": null, "focal_method": "get_functions", "tests": "import unittest\n\nclass Test_get_functions(unittest.TestCase):\n def test_functions_sialic(self):\n \"\"\"Test counting nodes and grouping by function on the sialic acid graph.\"\"\"\n result = {PROTEIN: 7, COMPLEX: 1, ABUNDANCE: 1}\n self.assertEqual(set(result), get_functions(sialic_acid_graph))\n self.assertEqual(Counter(result), count_functions(sialic_acid_graph))\n\n def test_functions_egf(self):\n \"\"\"Test counting nodes and grouping by function on the EGF graph.\"\"\"\n result = {PROTEIN: 10, COMPLEX: 1, BIOPROCESS: 1}\n self.assertEqual(set(result), get_functions(egf_graph))\n self.assertEqual(result, count_functions(egf_graph))\n", "method_code": "def get_functions(graph: BELGraph) -> Set[str]:\n \"\"\"Get the set of all functions used in this graph.\n\n :param graph: A BEL graph\n :return: A set of functions\n \"\"\"\n return set(_function_iterator(graph))", "context": "def get_functions(graph: BELGraph) -> Set[str]: ...\ndef _function_iterator(graph: BELGraph) -> Iterable[str]: ...\ndef get_functions(graph: BELGraph) -> Set[str]: ...\ndef count_functions(graph: BELGraph) -> typing.Counter[str]: ...\ndef _iterate_namespaces(graph: BELGraph) -> Iterable[str]: ...\ndef _iterate_edge_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef count_namespaces(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_unused_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_names(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef iterate_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef iterate_node_entities(node: BaseEntity) -> Iterable[Entity]: ...\ndef _identifier_filtered_iterator(graph) -> Iterable[Tuple[str, str]]: ...\ndef _get_node_names(data: Mapping[str, Any]) -> Iterable[Tuple[str, str]]: ...\ndef _namespace_filtered_iterator(graph: BELGraph, namespace: str) -> Iterable[str]: ...\ndef count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]: ...\ndef get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: ...\ndef count_variants(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]: ...\ndef get_top_pathologies(graph: BELGraph, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef get_ungrounded_nodes(graph: BELGraph) -> Set[BaseEntity]: ...\ndef node_is_grounded(node: BaseEntity) -> bool: ...\ndef get_degradations(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_activities(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_translocated(graph: BELGraph) -> Set[BaseEntity]: ...\ndef count_modifications(graph: BELGraph) -> Counter: ...\ndef remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: ...\n", "repository": "pybel/pybel", "test_name": "test_functions_sialic", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002323.py"} {"focal_file": "src/pybel/struct/summary/node_summary.py", "focal_class": null, "focal_method": "get_namespaces", "tests": "import unittest\n\nclass Test_get_namespaces(unittest.TestCase):\n def test_namespaces_egf(self):\n \"\"\"Test getting and counting namespaces' contents on the EGF graph.\"\"\"\n result = {'hgnc': 15, 'go': 7}\n self.assertEqual(set(result), get_namespaces(egf_graph))\n self.assertEqual(Counter(result), count_namespaces(egf_graph))\n", "method_code": "def get_namespaces(graph: BELGraph) -> Set[str]:\n \"\"\"Get the set of all namespaces used in this graph.\n\n :param graph: A BEL graph\n :return: A set of namespaces\n \"\"\"\n return set(_iterate_namespaces(graph))", "context": "def get_namespaces(graph: BELGraph) -> Set[str]: ...\ndef _function_iterator(graph: BELGraph) -> Iterable[str]: ...\ndef get_functions(graph: BELGraph) -> Set[str]: ...\ndef count_functions(graph: BELGraph) -> typing.Counter[str]: ...\ndef _iterate_namespaces(graph: BELGraph) -> Iterable[str]: ...\ndef _iterate_edge_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef count_namespaces(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_unused_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_names(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef iterate_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef iterate_node_entities(node: BaseEntity) -> Iterable[Entity]: ...\ndef _identifier_filtered_iterator(graph) -> Iterable[Tuple[str, str]]: ...\ndef _get_node_names(data: Mapping[str, Any]) -> Iterable[Tuple[str, str]]: ...\ndef _namespace_filtered_iterator(graph: BELGraph, namespace: str) -> Iterable[str]: ...\ndef count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]: ...\ndef get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: ...\ndef count_variants(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]: ...\ndef get_top_pathologies(graph: BELGraph, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef get_ungrounded_nodes(graph: BELGraph) -> Set[BaseEntity]: ...\ndef node_is_grounded(node: BaseEntity) -> bool: ...\ndef get_degradations(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_activities(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_translocated(graph: BELGraph) -> Set[BaseEntity]: ...\ndef count_modifications(graph: BELGraph) -> Counter: ...\ndef remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: ...\n", "repository": "pybel/pybel", "test_name": "test_namespaces_egf", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002324.py"} {"focal_file": "src/pybel/struct/summary/node_summary.py", "focal_class": null, "focal_method": "get_names_by_namespace", "tests": "import unittest\n\nclass Test_get_names_by_namespace(unittest.TestCase):\n def test_get_names_raise(self):\n \"\"\"Test that an index error is raised when trying to get names from a namespace that isn't present.\"\"\"\n with self.assertRaises(IndexError):\n get_names_by_namespace(sialic_acid_graph, 'NOPE')\n", "method_code": "def get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]:\n \"\"\"Get the set of all of the names in a given namespace that are in the graph.\n\n :param pybel.BELGraph graph: A BEL graph\n :param namespace: A namespace prefix\n :return: A set of names belonging to the given namespace that are in the given graph\n\n :raises IndexError: if the namespace is not defined in the graph.\n \"\"\"\n if namespace not in graph.defined_namespace_keywords:\n raise IndexError('{} is not defined in {}'.format(namespace, graph))\n return set(_namespace_filtered_iterator(graph, namespace))", "context": "def get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: ...\ndef _function_iterator(graph: BELGraph) -> Iterable[str]: ...\ndef get_functions(graph: BELGraph) -> Set[str]: ...\ndef count_functions(graph: BELGraph) -> typing.Counter[str]: ...\ndef _iterate_namespaces(graph: BELGraph) -> Iterable[str]: ...\ndef _iterate_edge_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef count_namespaces(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_unused_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_names(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef iterate_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef iterate_node_entities(node: BaseEntity) -> Iterable[Entity]: ...\ndef _identifier_filtered_iterator(graph) -> Iterable[Tuple[str, str]]: ...\ndef _get_node_names(data: Mapping[str, Any]) -> Iterable[Tuple[str, str]]: ...\ndef _namespace_filtered_iterator(graph: BELGraph, namespace: str) -> Iterable[str]: ...\ndef count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]: ...\ndef get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: ...\ndef count_variants(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]: ...\ndef get_top_pathologies(graph: BELGraph, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef get_ungrounded_nodes(graph: BELGraph) -> Set[BaseEntity]: ...\ndef node_is_grounded(node: BaseEntity) -> bool: ...\ndef get_degradations(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_activities(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_translocated(graph: BELGraph) -> Set[BaseEntity]: ...\ndef count_modifications(graph: BELGraph) -> Counter: ...\ndef remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: ...\n", "repository": "pybel/pybel", "test_name": "test_get_names_raise", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002325.py"} {"focal_file": "src/pybel/struct/summary/node_summary.py", "focal_class": null, "focal_method": "count_names_by_namespace", "tests": "import unittest\n\nclass Test_count_names_by_namespace(unittest.TestCase):\n def test_count_names_raise(self):\n \"\"\"Test that an index error is raised when trying to count a namespace that isn't present.\"\"\"\n with self.assertRaises(IndexError):\n count_names_by_namespace(sialic_acid_graph, 'NOPE')\n", "method_code": "def count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]:\n \"\"\"Get the set of all of the names in a given namespace that are in the graph.\n\n :param graph: A BEL graph\n :param namespace: A namespace prefix\n :return: A counter from {name: frequency}\n\n :raises IndexError: if the namespace is not defined in the graph.\n \"\"\"\n if namespace not in graph.defined_namespace_keywords:\n raise IndexError('{} is not defined in {}'.format(namespace, graph))\n return Counter(_namespace_filtered_iterator(graph, namespace))", "context": "def count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]: ...\ndef _function_iterator(graph: BELGraph) -> Iterable[str]: ...\ndef get_functions(graph: BELGraph) -> Set[str]: ...\ndef count_functions(graph: BELGraph) -> typing.Counter[str]: ...\ndef _iterate_namespaces(graph: BELGraph) -> Iterable[str]: ...\ndef _iterate_edge_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef count_namespaces(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_unused_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_names(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef iterate_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef iterate_node_entities(node: BaseEntity) -> Iterable[Entity]: ...\ndef _identifier_filtered_iterator(graph) -> Iterable[Tuple[str, str]]: ...\ndef _get_node_names(data: Mapping[str, Any]) -> Iterable[Tuple[str, str]]: ...\ndef _namespace_filtered_iterator(graph: BELGraph, namespace: str) -> Iterable[str]: ...\ndef count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]: ...\ndef get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: ...\ndef count_variants(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]: ...\ndef get_top_pathologies(graph: BELGraph, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef get_ungrounded_nodes(graph: BELGraph) -> Set[BaseEntity]: ...\ndef node_is_grounded(node: BaseEntity) -> bool: ...\ndef get_degradations(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_activities(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_translocated(graph: BELGraph) -> Set[BaseEntity]: ...\ndef count_modifications(graph: BELGraph) -> Counter: ...\ndef remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: ...\n", "repository": "pybel/pybel", "test_name": "test_count_names_raise", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002326.py"} {"focal_file": "src/pybel/struct/summary/node_summary.py", "focal_class": null, "focal_method": "count_variants", "tests": "import unittest\n\nclass Test_count_variants(unittest.TestCase):\n def test_count_variants(self):\n \"\"\"Test counting the number of variants in a graph.\"\"\"\n variants = count_variants(sialic_acid_graph)\n self.assertEqual(1, variants['pmod'])\n", "method_code": "def count_variants(graph: BELGraph) -> typing.Counter[str]:\n \"\"\"Count how many of each type of variant a graph has.\n\n :param graph: A BEL graph\n \"\"\"\n return Counter((variant_data[KIND] for data in graph if has_variant(graph, data) for variant_data in data[VARIANTS]))", "context": "def count_variants(graph: BELGraph) -> typing.Counter[str]: ...\ndef _function_iterator(graph: BELGraph) -> Iterable[str]: ...\ndef get_functions(graph: BELGraph) -> Set[str]: ...\ndef count_functions(graph: BELGraph) -> typing.Counter[str]: ...\ndef _iterate_namespaces(graph: BELGraph) -> Iterable[str]: ...\ndef _iterate_edge_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef count_namespaces(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_unused_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_names(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef iterate_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef iterate_node_entities(node: BaseEntity) -> Iterable[Entity]: ...\ndef _identifier_filtered_iterator(graph) -> Iterable[Tuple[str, str]]: ...\ndef _get_node_names(data: Mapping[str, Any]) -> Iterable[Tuple[str, str]]: ...\ndef _namespace_filtered_iterator(graph: BELGraph, namespace: str) -> Iterable[str]: ...\ndef count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]: ...\ndef get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: ...\ndef count_variants(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]: ...\ndef get_top_pathologies(graph: BELGraph, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef get_ungrounded_nodes(graph: BELGraph) -> Set[BaseEntity]: ...\ndef node_is_grounded(node: BaseEntity) -> bool: ...\ndef get_degradations(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_activities(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_translocated(graph: BELGraph) -> Set[BaseEntity]: ...\ndef count_modifications(graph: BELGraph) -> Counter: ...\ndef remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: ...\n", "repository": "pybel/pybel", "test_name": "test_count_variants", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002327.py"} {"focal_file": "src/pybel/struct/summary/node_summary.py", "focal_class": null, "focal_method": "count_pathologies", "tests": "import unittest\n\nclass Test_count_pathologies(unittest.TestCase):\n def test_count_pathologies(self):\n \"\"\"Test counting pathologies in the graph.\"\"\"\n graph = BELGraph()\n a, b = (protein(namespace='HGNC', name=n()) for _ in range(2))\n c, d = (pathology(namespace='DOID', name=n()) for _ in range(2))\n graph.add_association(a, c, citation=n(), evidence=n())\n graph.add_association(a, d, citation=n(), evidence=n())\n graph.add_association(b, d, citation=n(), evidence=n())\n pathology_counter = count_pathologies(graph)\n self.assertIn(c, pathology_counter)\n self.assertIn(d, pathology_counter)\n self.assertEqual(1, pathology_counter[c])\n self.assertEqual(2, pathology_counter[d])\n top_pathology_counter = get_top_pathologies(graph, n=1)\n self.assertEqual(1, len(top_pathology_counter))\n node, count = top_pathology_counter[0]\n self.assertEqual(d, node)\n self.assertEqual(2, count)\n", "method_code": "def count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]:\n \"\"\"Count the number of edges in which each pathology is incident.\n\n :param graph: A BEL graph\n \"\"\"\n edges = {tuple(sorted([u, v], key=lambda node: node.as_bel())) for u, v in graph.edges()}\n return Counter((node for node in itt.chain.from_iterable(edges) if isinstance(node, Pathology)))", "context": "def count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]: ...\ndef _function_iterator(graph: BELGraph) -> Iterable[str]: ...\ndef get_functions(graph: BELGraph) -> Set[str]: ...\ndef count_functions(graph: BELGraph) -> typing.Counter[str]: ...\ndef _iterate_namespaces(graph: BELGraph) -> Iterable[str]: ...\ndef _iterate_edge_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef count_namespaces(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_unused_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_names(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef iterate_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef iterate_node_entities(node: BaseEntity) -> Iterable[Entity]: ...\ndef _identifier_filtered_iterator(graph) -> Iterable[Tuple[str, str]]: ...\ndef _get_node_names(data: Mapping[str, Any]) -> Iterable[Tuple[str, str]]: ...\ndef _namespace_filtered_iterator(graph: BELGraph, namespace: str) -> Iterable[str]: ...\ndef count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]: ...\ndef get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: ...\ndef count_variants(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]: ...\ndef get_top_pathologies(graph: BELGraph, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef get_ungrounded_nodes(graph: BELGraph) -> Set[BaseEntity]: ...\ndef node_is_grounded(node: BaseEntity) -> bool: ...\ndef get_degradations(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_activities(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_translocated(graph: BELGraph) -> Set[BaseEntity]: ...\ndef count_modifications(graph: BELGraph) -> Counter: ...\ndef remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: ...\n", "repository": "pybel/pybel", "test_name": "test_count_pathologies", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002328.py"} {"focal_file": "src/pybel/struct/summary/node_summary.py", "focal_class": null, "focal_method": "get_top_hubs", "tests": "import unittest\n\nclass Test_get_top_hubs(unittest.TestCase):\n def test_get_top_hubs(self):\n \"\"\"Test counting pathologies in the graph.\"\"\"\n graph = BELGraph()\n a, b, c = (protein(n(), n()), protein(n(), n()), pathology(n(), n()))\n graph.add_association(a, b, citation=n(), evidence=n())\n graph.add_association(a, c, citation=n(), evidence=n())\n top_hubs = get_top_hubs(graph, n=1)\n self.assertEqual(1, len(top_hubs))\n node, degree = top_hubs[0]\n self.assertEqual(a, node)\n self.assertEqual(4, degree)\n", "method_code": "def get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]:\n \"\"\"Get the top hubs in the graph by BEL.\n\n :param graph: A BEL graph\n :param n: The number of top hubs to return. If None, returns all nodes\n \"\"\"\n return Counter(dict(graph.degree())).most_common(n=n)", "context": "def get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef _function_iterator(graph: BELGraph) -> Iterable[str]: ...\ndef get_functions(graph: BELGraph) -> Set[str]: ...\ndef count_functions(graph: BELGraph) -> typing.Counter[str]: ...\ndef _iterate_namespaces(graph: BELGraph) -> Iterable[str]: ...\ndef _iterate_edge_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef count_namespaces(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_unused_namespaces(graph: BELGraph) -> Set[str]: ...\ndef get_names(graph: BELGraph) -> Mapping[str, Set[str]]: ...\ndef iterate_entities(graph: BELGraph) -> Iterable[Entity]: ...\ndef iterate_node_entities(node: BaseEntity) -> Iterable[Entity]: ...\ndef _identifier_filtered_iterator(graph) -> Iterable[Tuple[str, str]]: ...\ndef _get_node_names(data: Mapping[str, Any]) -> Iterable[Tuple[str, str]]: ...\ndef _namespace_filtered_iterator(graph: BELGraph, namespace: str) -> Iterable[str]: ...\ndef count_names_by_namespace(graph: BELGraph, namespace: str) -> typing.Counter[str]: ...\ndef get_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: ...\ndef count_variants(graph: BELGraph) -> typing.Counter[str]: ...\ndef get_top_hubs(graph: BELGraph, *, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef count_pathologies(graph: BELGraph) -> typing.Counter[BaseEntity]: ...\ndef get_top_pathologies(graph: BELGraph, n: Optional[int]=15) -> List[Tuple[BaseEntity, int]]: ...\ndef get_ungrounded_nodes(graph: BELGraph) -> Set[BaseEntity]: ...\ndef node_is_grounded(node: BaseEntity) -> bool: ...\ndef get_degradations(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_activities(graph: BELGraph) -> Set[BaseEntity]: ...\ndef get_translocated(graph: BELGraph) -> Set[BaseEntity]: ...\ndef count_modifications(graph: BELGraph) -> Counter: ...\ndef remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]: ...\n", "repository": "pybel/pybel", "test_name": "test_get_top_hubs", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002329.py"} {"focal_file": "src/pybel/struct/mutation/induction/random_subgraph.py", "focal_class": null, "focal_method": "get_graph_with_random_edges", "tests": "import unittest\n\nclass Test_get_graph_with_random_edges(unittest.TestCase):\n def test_random_edges(self):\n \"\"\"Test getting a graph by random edges.\"\"\"\n n_nodes, n_edges, n_sample_edges = (15, 80, 40)\n graph = generate_random_graph(n_nodes=n_nodes, n_edges=n_edges)\n subgraph = get_graph_with_random_edges(graph, n_edges=n_sample_edges)\n self.assertEqual(n_sample_edges, subgraph.number_of_edges())\n", "method_code": "def get_graph_with_random_edges(graph: BELGraph, n_edges: int) -> BELGraph:\n \"\"\"Build a new graph from a seeding of edges.\n\n :param graph: A BEL graph\n :param n_edges: Number of edges to randomly select from the given graph\n \"\"\"\n rv = graph.child()\n rv.add_edges_from(_random_edge_iterator(graph, n_edges))\n return rv", "context": "@transformation\ndef get_graph_with_random_edges(graph: BELGraph, n_edges: int) -> BELGraph: ...\ndef _random_edge_iterator(graph: BELGraph, n_edges: int) -> Iterable[Tuple[BaseEntity, BaseEntity, int, Mapping]]: ...\ndef get_graph_with_random_edges(graph: BELGraph, n_edges: int) -> BELGraph: ...\ndef get_random_node(graph, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> Optional[BaseEntity]: ...\ndef _helper(result, graph, number_edges_remaining: int, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> None: ...\ndef get_random_subgraph(graph: BELGraph, number_edges: Optional[int]=None, number_seed_edges: Optional[int]=None, seed: Optional[int]=None, invert_degrees: Optional[bool]=None) -> BELGraph: ...\n", "repository": "pybel/pybel", "test_name": "test_random_edges", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002330.py"} {"focal_file": "src/pybel/struct/mutation/induction/random_subgraph.py", "focal_class": null, "focal_method": "get_random_node", "tests": "import unittest\n\nclass Test_get_random_node(unittest.TestCase):\n def test_random_nodes(self):\n \"\"\"Test getting random nodes.\"\"\"\n graph = nx.MultiDiGraph()\n graph.add_edge(1, 2)\n graph.add_edge(1, 3)\n graph.add_edge(1, 4)\n graph.add_edge(1, 5)\n n = 30000\n r = Counter((get_random_node(graph, set(), invert_degrees=False) for _ in range(n)))\n degree_sum = 4 + 1 + 1 + 1 + 1\n self.assertAlmostEqual(4 / degree_sum, r[1] / n, places=2)\n self.assertAlmostEqual(1 / degree_sum, r[2] / n, places=2)\n self.assertAlmostEqual(1 / degree_sum, r[3] / n, places=2)\n self.assertAlmostEqual(1 / degree_sum, r[4] / n, places=2)\n self.assertAlmostEqual(1 / degree_sum, r[5] / n, places=2)\n\n def test_random_nodes_inverted(self):\n \"\"\"Test getting random nodes.\"\"\"\n graph = nx.MultiDiGraph()\n graph.add_edge(1, 2)\n graph.add_edge(1, 3)\n graph.add_edge(1, 4)\n graph.add_edge(1, 5)\n n = 30000\n r = Counter((get_random_node(graph, set(), invert_degrees=True) for _ in range(n)))\n degree_sum = 1 / 4 + 1 / 1 + 1 / 1 + 1 / 1 + 1 / 1\n self.assertAlmostEqual(1 / 4 / degree_sum, r[1] / n, places=2)\n self.assertAlmostEqual(1 / 1 / degree_sum, r[2] / n, places=2)\n self.assertAlmostEqual(1 / 1 / degree_sum, r[3] / n, places=2)\n self.assertAlmostEqual(1 / 1 / degree_sum, r[4] / n, places=2)\n self.assertAlmostEqual(1 / 1 / degree_sum, r[5] / n, places=2)\n", "method_code": "def get_random_node(graph, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> Optional[BaseEntity]:\n \"\"\"Choose a node from the graph with probabilities based on their degrees.\n\n :type graph: networkx.Graph\n :param node_blacklist: Nodes to filter out\n :param invert_degrees: Should the degrees be inverted? Defaults to true.\n \"\"\"\n try:\n nodes, degrees = zip(*((node, degree) for node, degree in sorted(graph.degree(), key=itemgetter(1)) if node not in node_blacklist))\n except ValueError:\n return\n if invert_degrees is None or invert_degrees:\n degrees = [1 / degree for degree in degrees]\n wrg = WeightedRandomGenerator(nodes, degrees)\n return wrg.next()", "context": "def get_random_node(graph, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> Optional[BaseEntity]: ...\ndef _random_edge_iterator(graph: BELGraph, n_edges: int) -> Iterable[Tuple[BaseEntity, BaseEntity, int, Mapping]]: ...\ndef get_graph_with_random_edges(graph: BELGraph, n_edges: int) -> BELGraph: ...\ndef get_random_node(graph, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> Optional[BaseEntity]: ...\ndef _helper(result, graph, number_edges_remaining: int, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> None: ...\ndef get_random_subgraph(graph: BELGraph, number_edges: Optional[int]=None, number_seed_edges: Optional[int]=None, seed: Optional[int]=None, invert_degrees: Optional[bool]=None) -> BELGraph: ...\n", "repository": "pybel/pybel", "test_name": "test_random_nodes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002331.py"} {"focal_file": "src/pybel/struct/mutation/induction/random_subgraph.py", "focal_class": null, "focal_method": "get_random_subgraph", "tests": "import unittest\n\nclass Test_get_random_subgraph(unittest.TestCase):\n def test_random_sample(self):\n \"\"\"Test randomly sampling a graph.\"\"\"\n n_nodes, n_edges = (50, 500)\n graph = generate_random_graph(n_nodes=n_nodes, n_edges=n_edges)\n self.assertEqual(n_edges, graph.number_of_edges())\n sg_1 = get_random_subgraph(graph, number_edges=250, number_seed_edges=10, invert_degrees=False)\n self.assertEqual(250, sg_1.number_of_edges())\n sg_2 = get_random_subgraph(graph, number_edges=250, number_seed_edges=10, invert_degrees=True)\n self.assertEqual(250, sg_2.number_of_edges())\n\n def test_random_sample_small(self):\n \"\"\"Test a graph that is too small to sample.\"\"\"\n n_nodes, n_edges = (11, 25)\n graph = generate_random_graph(n_nodes, n_edges)\n self.assertEqual(n_edges, graph.number_of_edges())\n sg_1 = get_random_subgraph(graph, number_edges=250, number_seed_edges=5, invert_degrees=False)\n self.assertEqual(graph.number_of_edges(), sg_1.number_of_edges(), msg='since graph is too small, the subgraph should contain the whole thing')\n sg_2 = get_random_subgraph(graph, number_edges=250, number_seed_edges=5, invert_degrees=True)\n self.assertEqual(graph.number_of_edges(), sg_2.number_of_edges(), msg='since graph is too small, the subgraph should contain the whole thing')\n", "method_code": "def get_random_subgraph(graph: BELGraph, number_edges: Optional[int]=None, number_seed_edges: Optional[int]=None, seed: Optional[int]=None, invert_degrees: Optional[bool]=None) -> BELGraph:\n \"\"\"Generate a random subgraph based on weighted random walks from random seed edges.\n\n :type graph: pybel.BELGraph graph\n :param number_edges: Maximum number of edges. Defaults to\n :data:`pybel_tools.constants.SAMPLE_RANDOM_EDGE_COUNT` (250).\n :param number_seed_edges: Number of nodes to start with (which likely results in different components\n in large graphs). Defaults to :data:`SAMPLE_RANDOM_EDGE_SEED_COUNT` (5).\n :param seed: A seed for the random state\n :param invert_degrees: Should the degrees be inverted? Defaults to true.\n \"\"\"\n if number_edges is None:\n number_edges = SAMPLE_RANDOM_EDGE_COUNT\n if number_seed_edges is None:\n number_seed_edges = SAMPLE_RANDOM_EDGE_SEED_COUNT\n if seed is not None:\n random.seed(seed)\n if graph.number_of_edges() <= number_edges:\n logger.info('sampled full graph')\n return graph.copy()\n logger.debug('getting random sub-graph with %d seed edges, %d final edges, and seed=%s', number_seed_edges, number_edges, seed)\n result = get_graph_with_random_edges(graph, number_seed_edges)\n number_edges_remaining = number_edges - result.number_of_edges()\n _helper(result, graph, number_edges_remaining, node_blacklist=set(), invert_degrees=invert_degrees)\n logger.debug('removing isolated nodes')\n remove_isolated_nodes(result)\n return result", "context": "@transformation\ndef get_random_subgraph(graph: BELGraph, number_edges: Optional[int]=None, number_seed_edges: Optional[int]=None, seed: Optional[int]=None, invert_degrees: Optional[bool]=None) -> BELGraph: ...\ndef _random_edge_iterator(graph: BELGraph, n_edges: int) -> Iterable[Tuple[BaseEntity, BaseEntity, int, Mapping]]: ...\ndef get_graph_with_random_edges(graph: BELGraph, n_edges: int) -> BELGraph: ...\ndef get_random_node(graph, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> Optional[BaseEntity]: ...\ndef _helper(result, graph, number_edges_remaining: int, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> None: ...\ndef get_random_subgraph(graph: BELGraph, number_edges: Optional[int]=None, number_seed_edges: Optional[int]=None, seed: Optional[int]=None, invert_degrees: Optional[bool]=None) -> BELGraph: ...\n", "repository": "pybel/pybel", "test_name": "test_random_sample", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002332.py"} {"focal_file": "src/pybel/struct/mutation/induction/random_subgraph.py", "focal_class": null, "focal_method": "_helper", "tests": "import unittest\n\nclass Test_helper(unittest.TestCase):\n def test_helper_failure(self):\n graph = nx.MultiDiGraph()\n graph.add_edge(1, 2)\n graph.add_edge(2, 3)\n result = nx.MultiDiGraph()\n result.add_edge(1, 2)\n _helper(result, graph, number_edges_remaining=5, node_blacklist={1, 2, 3})\n self.assertNotIn(3, result)\n", "method_code": "def _helper(result, graph, number_edges_remaining: int, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> None:\n \"\"\"Help build a random graph.\n\n :type result: networkx.Graph\n :type graph: networkx.Graph\n \"\"\"\n original_node_count = graph.number_of_nodes()\n logger.debug('adding remaining %d edges', number_edges_remaining)\n for _ in range(number_edges_remaining):\n source, possible_step_nodes, c = (None, set(), 0)\n while not source or not possible_step_nodes:\n source = get_random_node(result, node_blacklist, invert_degrees=invert_degrees)\n c += 1\n if c >= original_node_count:\n logger.warning('infinite loop happening')\n logger.warning('source: %s', source)\n logger.warning('no grow: %s', node_blacklist)\n return\n if source is None:\n continue\n possible_step_nodes = set(graph[source]) - set(result[source])\n if not possible_step_nodes:\n node_blacklist.add(source)\n step_node = random.choice(list(possible_step_nodes))\n key, attr_dict = random.choice(list(graph[source][step_node].items()))\n result.add_edge(source, step_node, key=key, **attr_dict)", "context": "def _helper(result, graph, number_edges_remaining: int, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> None: ...\ndef _random_edge_iterator(graph: BELGraph, n_edges: int) -> Iterable[Tuple[BaseEntity, BaseEntity, int, Mapping]]: ...\ndef get_graph_with_random_edges(graph: BELGraph, n_edges: int) -> BELGraph: ...\ndef get_random_node(graph, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> Optional[BaseEntity]: ...\ndef _helper(result, graph, number_edges_remaining: int, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool]=None) -> None: ...\ndef get_random_subgraph(graph: BELGraph, number_edges: Optional[int]=None, number_seed_edges: Optional[int]=None, seed: Optional[int]=None, invert_degrees: Optional[bool]=None) -> BELGraph: ...\n", "repository": "pybel/pybel", "test_name": "test_helper_failure", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002333.py"} {"focal_file": "src/pybel/struct/mutation/inference/transfer.py", "focal_class": null, "focal_method": "iter_children", "tests": "import unittest\n\nclass Test_iter_children(unittest.TestCase):\n def test_get_children(self):\n \"\"\"Test iterating over the children of a node.\"\"\"\n children = list(iter_children(statin_graph, hmgcr_inhibitor))\n self.assertNotEqual(0, len(children), msg='no children found')\n self.assertIn(mevinolinic_acid, children, msg='direct child not found')\n", "method_code": "def iter_children(graph: BELGraph, node: BaseEntity) -> Iterable[BaseEntity]:\n \"\"\"Iterate over children of the node.\"\"\"\n return (node for node, _, d in graph.in_edges(node, data=True) if d[RELATION] == IS_A)", "context": "def iter_children(graph: BELGraph, node: BaseEntity) -> Iterable[BaseEntity]: ...\ndef iter_children(graph: BELGraph, node: BaseEntity) -> Iterable[BaseEntity]: ...\ndef transfer_causal_edges(graph: BELGraph, source: BaseEntity, target: BaseEntity) -> Iterable[str]: ...\ndef infer_child_relations(graph: BELGraph, node: BaseEntity) -> List[str]: ...\ndef _infer_child_relations_iter(graph: BELGraph, node: BaseEntity) -> Iterable[str]: ...\n", "repository": "pybel/pybel", "test_name": "test_get_children", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002334.py"} {"focal_file": "spacq/devices/config.py", "focal_class": null, "focal_method": "connect", "tests": "import unittest\n\nclass Test_connect(unittest.TestCase):\n def testMockConnect(self):\n \"\"\"\n Connect to a mock device.\n \"\"\"\n cfg = config.DeviceConfig(name='Test')\n cfg.address_mode = cfg.address_modes.ethernet\n cfg.ip_address = '127.0.0.1'\n tree = config.device_tree()\n cfg.manufacturer = tree.keys()[-1]\n cfg.model = tree[cfg.manufacturer].keys()[-1]\n cfg.mock = True\n cfg.connect()\n assert isinstance(cfg.device, MockAbstractDevice)\n", "method_code": " def connect(self):\n \"\"\"\n \t\tCreate an instance of the implementation and connect to it.\n \t\t\"\"\"\n if self.address_mode not in self.address_modes:\n raise ConnectionError('Invalid address mode specified.')\n if self.manufacturer is None or self.model is None:\n raise ConnectionError('No implementation specified.')\n address = {}\n if not self.mock:\n if self.address_mode == self.address_modes.ethernet:\n if self.ip_address is None:\n raise ConnectionError('No IP address specified.')\n address['ip_address'] = self.ip_address\n elif self.address_mode == self.address_modes.gpib:\n address['gpib_board'] = self.gpib_board\n address['gpib_pad'] = self.gpib_pad\n address['gpib_sad'] = self.gpib_sad\n elif self.address_mode == self.address_modes.usb:\n if self.usb_resource is None:\n raise ConnectionError('No USB resource specified.')\n address['usb_resource'] = self.usb_resource\n tree = device_tree()\n try:\n subtree = tree[self.manufacturer]\n except KeyError:\n raise ConnectionError('Unknown manufacturer: {0}'.format(self.manufacturer))\n try:\n subtree = subtree[self.model]\n except KeyError:\n raise ConnectionError('Unknown model: {0}'.format(self.model))\n kind = 'mock' if self.mock else 'real'\n try:\n implementation = subtree[kind]\n except KeyError:\n raise ConnectionError('Unknown kind: {0}'.format(kind))\n try:\n device = implementation(autoconnect=False, **address)\n except (ValueError, NotImplementedError) as e:\n raise ConnectionError('Unable to create device.', e)\n try:\n device.connect()\n except DeviceNotFoundError as e:\n raise ConnectionError('Unable to make connection to device.', e)\n self.device = device\n ", "context": "class DeviceConfig(object):\n def connect(self): ...\n def __init__(self, name): ...\n def __getstate__(self): ...\n def __setstate__(self, dict): ...\n def device(self): ...\n def device(self, value): ...\n def diff_resources(self, new): ...\n\n self.name = name\n self.address_mode = None\n self.ip_address = None\n self.gpib_board = 0\n self.gpib_pad = 0\n self.gpib_sad = 0\n self.usb_resource = None\n self.manufacturer = None\n self.model = None\n self.mock = False\n self.gui_setup = None\n self.resource_labels = {}\n self._device = None\n self.resources = {}\n\n address_modes = Enum(['ethernet', 'gpib', 'usb'])\n", "repository": "0/SpanishAcquisition", "test_name": "testMockConnect", "smells": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002335.py"} {"focal_file": "spacq/devices/config.py", "focal_class": null, "focal_method": "diff_resources", "tests": "import unittest\n\nclass Test_diff_resources(unittest.TestCase):\n def testDiffResources(self):\n \"\"\"\n Try changing up some resources.\n \"\"\"\n cfg1 = config.DeviceConfig(name='Test 1')\n cfg2 = config.DeviceConfig(name='Test 2')\n eq_(cfg1.diff_resources(cfg2), (set(), set(), set()))\n cfg2.resources['something'] = 'new'\n eq_(cfg1.diff_resources(cfg2), (set(['something']), set(), set()))\n cfg1.resources['for'] = 'now'\n eq_(cfg1.diff_resources(cfg2), (set(['something']), set(), set(['for'])))\n cfg1.resources['something'] = 'now'\n eq_(cfg1.diff_resources(cfg2), (set(), set(['something']), set(['for'])))\n", "method_code": " def diff_resources(self, new):\n \"\"\"\n \t\tCompare the resources belonging to 2 DeviceConfig objects.\n \n \t\tThe result is a tuple of:\n \t\t\tresources which appear\n \t\t\tresources which change\n \t\t\tresources which disappear\n \t\twhere all \"resources\" are resource labels.\n \t\t\"\"\"\n old_labels, new_labels = (set(self.resources), set(new.resources))\n appeared = new_labels - old_labels\n disappeared = old_labels - new_labels\n changed = set()\n possibly_changed = old_labels.intersection(new_labels)\n for p in possibly_changed:\n if self.resources[p] is not new.resources[p]:\n changed.add(p)\n return (appeared, changed, disappeared)\n ", "context": "class DeviceConfig(object):\n def diff_resources(self, new): ...\n def __init__(self, name): ...\n def __getstate__(self): ...\n def __setstate__(self, dict): ...\n def device(self): ...\n def device(self, value): ...\n def connect(self): ...\n\n self.name = name\n self.address_mode = None\n self.ip_address = None\n self.gpib_board = 0\n self.gpib_pad = 0\n self.gpib_sad = 0\n self.usb_resource = None\n self.manufacturer = None\n self.model = None\n self.mock = False\n self.gui_setup = None\n self.resource_labels = {}\n self._device = None\n self.resources = {}\n\n address_modes = Enum(['ethernet', 'gpib', 'usb'])\n", "repository": "0/SpanishAcquisition", "test_name": "testDiffResources", "smells": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002336.py"} {"focal_file": "spacq/devices/abstract_device.py", "focal_class": null, "focal_method": "multi_command_stop", "tests": "import unittest\n\nclass Test_multi_command_stop(unittest.TestCase):\n def testMultiCommand(self):\n \"\"\"\n Send a multi-command message.\n \"\"\"\n for name, device in tc['devices'].items():\n dev = self.obtain_device(device)\n if dev is None:\n continue\n id = dev.idn\n expected = ['1'] * 3 + [id]\n assert_raises(ValueError, dev.multi_command_stop)\n dev.multi_command_start()\n responses = dev.multi_command_stop()\n eq_(responses, [])\n dev.multi_command_start()\n dev.opc\n dev.opc\n dev.opc\n dev.idn\n responses = dev.multi_command_stop()\n eq_(responses, expected)\n return\n raise SkipTest('Could not connect to any device.')\n", "method_code": " def multi_command_stop(self):\n \"\"\"\n \t\tStop redirecting to a buffer, and send the buffered commands.\n \n \t\tReturns the results of queries if any were expected.\n \t\t\"\"\"\n log.debug('Stopping multi-command message for device \"{0}\"'.format(self.name))\n if self.multi_command is None:\n raise ValueError('Multi-command message not started.')\n elif not self.multi_command:\n return []\n commands = self.multi_command\n self.multi_command = None\n commands = [cmd if cmd[0] == '*' else ':' + cmd for cmd in commands]\n message = ';'.join(commands)\n if self.responses_expected:\n result = self.ask(message)\n return result.split(';', self.responses_expected - 1)\n else:\n self.write(message)\n return []\n ", "context": "class AbstractDevice(SuperDevice):\n @Synchronized()\n def multi_command_stop(self): ...\n def _setup(self): ...\n def __init__(self, ip_address=None, gpib_board=0, gpib_pad=None, gpib_sad=0, usb_resource=None, autoconnect=True): ...\n def __repr__(self): ...\n def connect(self): ...\n def multi_command_start(self): ...\n def write(self, message): ...\n def read_raw(self, chunk_size=512): ...\n def read(self): ...\n def ask_raw(self, message): ...\n def ask(self, message): ...\n def close(self): ...\n def find_resource(self, path): ...\n def idn(self): ...\n def opc(self): ...\n\n max_timeout = 15\n", "repository": "0/SpanishAcquisition", "test_name": "testMultiCommand", "smells": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002337.py"} {"focal_file": "spacq/devices/abstract_device.py", "focal_class": null, "focal_method": "close", "tests": "import unittest\n\nclass Test_close(unittest.TestCase):\n def testClose(self):\n \"\"\"\n Close the device.\n \"\"\"\n for name, device in tc['devices'].items():\n dev = self.obtain_device(device)\n if dev is None:\n continue\n dev.idn\n dev.opc\n dev.close()\n return\n raise SkipTest('Could not connect to any device.')\n", "method_code": " def close(self):\n \"\"\"\n \t\tClose the connection, if possible.\n \t\t\"\"\"\n log.debug('Closing device: {0}'.format(self.name))\n if self.driver in [drivers.pyvisa, drivers.pyvisa_usb]:\n self.device.close()\n ", "context": "class AbstractDevice(SuperDevice):\n def close(self): ...\n def _setup(self): ...\n def __init__(self, ip_address=None, gpib_board=0, gpib_pad=None, gpib_sad=0, usb_resource=None, autoconnect=True): ...\n def __repr__(self): ...\n def connect(self): ...\n def multi_command_start(self): ...\n def multi_command_stop(self): ...\n def write(self, message): ...\n def read_raw(self, chunk_size=512): ...\n def read(self): ...\n def ask_raw(self, message): ...\n def ask(self, message): ...\n def find_resource(self, path): ...\n def idn(self): ...\n def opc(self): ...\n\n max_timeout = 15\n", "repository": "0/SpanishAcquisition", "test_name": "testClose", "smells": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002338.py"} {"focal_file": "spacq/interface/pulse/program.py", "focal_class": null, "focal_method": "generate_waveforms", "tests": "import unittest\n\nclass Test_generate_waveforms(unittest.TestCase):\n def testGenerateWaveforms(self):\n \"\"\"\n Finally generate some waveforms.\n \"\"\"\n p = program.Program.from_file(path.join(resource_dir, '01.pulse'))\n assert_raises(ValueError, p.generate_waveforms)\n for name, value in self.missing:\n p.set_value(name, value)\n p.set_value(('wobble', 'shape'), 'non-square')\n p.frequency = Quantity(1, 'GHz')\n eq_(p.frequency, Quantity(1, 'GHz'))\n waveforms = p.generate_waveforms()\n eq_(set(waveforms.keys()), set(['f1', 'f2']))\n f1 = waveforms['f1']\n loop = [0.0] * 10 + [0.5] + [0.0] * 7 + [0.5] + [0.0] * 7\n assert_array_equal(f1.data, [0.0] * 10 + [0.5] * 1 + [0.0] * 7 + loop * 2 + [0.0] * 20 + [-0.5] * 5 + [0.0] * 49)\n eq_(f1.markers[1], [False] * 90 + [True] * 54)\n f2 = waveforms['f2']\n f2_gen = p._env.generators['f2']\n non_square = [0.1, 0.5, 0.7, 1.0] + [4.2] * 3 + [3.6, 9.9]\n wobble = f2_gen._scale_waveform(non_square, Quantity(-1, 'mV').value, Quantity(8, 'ns'))\n manipulator = f2_gen._scale_waveform(non_square, Quantity(1, 'V').value, Quantity(12, 'ns'))\n loop = [0.0] * 10 + wobble * 2\n end = manipulator + [0.0] * 15\n assert_array_almost_equal(f2.data, [0.0] * 10 + wobble + loop * 2 + [0.0] * 20 + end * 2, 2)\n\n def testWaveformsDryRun(self):\n \"\"\"\n Run through waveform generation, but don't actually generate anything.\n \"\"\"\n p = program.Program.from_file(path.join(resource_dir, '01.pulse'))\n assert_raises(ValueError, p.generate_waveforms, dry_run=True)\n for name, value in self.missing:\n p.set_value(name, value)\n p.set_value(('wobble', 'shape'), 'non-square')\n p.frequency = Quantity(1, 'YHz')\n assert_raises(ValueError, p.generate_waveforms, dry_run=True)\n p.frequency = Quantity(1, 'GHz')\n waveforms = p.generate_waveforms(dry_run=True)\n eq_(set(waveforms.keys()), set(['f1', 'f2']))\n eq_(list(waveforms['f1'].data), [])\n eq_(waveforms['f1'].markers, {})\n eq_(list(waveforms['f2'].data), [])\n eq_(waveforms['f2'].markers, {})\n", "method_code": " def generate_waveforms(self, dry_run=False):\n \"\"\"\n \t\tGenerate the waveforms, given that the values are all filled in.\n \t\t\"\"\"\n self._env.stage = self._env.stages.waveforms\n self._env.dry_run = dry_run\n self._env.missing_shapes = set()\n self._env.errors = []\n self._env.traverse_tree(self._ast)\n if self._env.errors:\n raise PulseError(self._env.format_errors())\n return self._env.waveforms\n ", "context": "class Program(object):\n def generate_waveforms(self, dry_run=False): ...\n def from_string(cls, s): ...\n def from_file(cls, path): ...\n def __init__(self, env, ast): ...\n def all_values(self): ...\n def frequency(self): ...\n def frequency(self, value): ...\n def missing_values(self): ...\n def values(self): ...\n def variables(self): ...\n def set_value(self, parameter, value): ...\n def with_resources(self): ...\n\n self._env = env\n self._ast = ast\n self.output_channels = dict(((name, None) for name, type in self._env.variables.items() if type == 'output'))\n self.awg = ''\n self.oscilloscope = ''\n self.resource_labels = {}\n self.resources = {}\n self.times_average = 1\n self.acq_delay = Quantity(0, 's')\n\n filename = ''\n", "repository": "0/SpanishAcquisition", "test_name": "testGenerateWaveforms", "smells": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002339.py"} {"focal_file": "spacq/interface/pulse/tree.py", "focal_class": null, "focal_method": "set_value", "tests": "import unittest\n\nclass Test_set_value(unittest.TestCase):\n def testValues(self):\n env = tree.Environment()\n env.stage = env.stages.declarations\n env.traverse_tree(self.prog)\n env.stage = env.stages.values\n env.traverse_tree(self.prog)\n expected = {('abc1',): Quantity('100 ns'), ('ghi1', 'amplitude'): Quantity(-1, 'mV'), ('ghi1', 'length'): Quantity(8, 'ns'), ('ghi1', 'shape'): path.join(resource_dir, 'non-square'), ('jkl2', 'shape'): 'square', ('repeat',): 2}\n missing = set([('_acq_marker', 'marker_num'), ('_acq_marker', 'output'), ('def2',), ('jkl2', 'amplitude'), ('jkl2', 'length')])\n eq_(env.errors, [])\n eq_(env.values, expected)\n eq_(env.missing_values, missing)\n updates = {('_acq_marker', 'marker_num'): 1, ('_acq_marker', 'output'): 'mno1', ('def2',): Quantity('7 ns'), ('jkl2', 'amplitude'): Quantity(1, 'V'), ('jkl2', 'length'): Quantity(50, 'ns')}\n for name, value in updates.items():\n env.set_value(name, value)\n expected.update(updates)\n eq_(env.errors, [])\n eq_(env.values, expected)\n", "method_code": " def set_value(self, target, value):\n \"\"\"\n \t\tSet a value if the types work out. TypeError otherwise.\n \t\t\"\"\"\n var_type = self.variables[target[0]]\n if var_type == 'acq_marker':\n if len(target) == 1:\n raise TypeError('Must assign dictionary to acq_marker')\n elif target[1] == 'marker_num':\n if not isinstance(value, int):\n raise TypeError('Must assign int to acq_marker num')\n elif target[1] == 'output':\n if not isinstance(value, basestring):\n raise TypeError('Must assign string to acq_marker num')\n elif var_type == 'delay':\n try:\n value.assert_dimensions('s')\n except (AttributeError, IncompatibleDimensions):\n raise TypeError('Must assign time quantity to delay')\n elif var_type == 'int':\n if not isinstance(value, int):\n raise TypeError('Must assign integer to int')\n elif var_type == 'pulse':\n if len(target) == 1:\n raise TypeError('Must assign dictionary to pulse')\n elif target[1] == 'amplitude':\n try:\n value.assert_dimensions('V')\n except (AttributeError, IncompatibleDimensions):\n raise TypeError('Must assign voltage quantity to pulse amplitude')\n elif target[1] == 'length':\n try:\n value.assert_dimensions('s')\n except (AttributeError, IncompatibleDimensions):\n raise TypeError('Must assign time quantity to pulse length')\n elif target[1] == 'shape':\n if not isinstance(value, basestring):\n raise TypeError('Must assign string to pulse shape')\n else:\n raise TypeError('Cannot assign to variable of type \"{0}\"'.format(var_type))\n if target in self.values and self.values[target] is not None:\n raise TypeError('Re-assignment of {0}'.format(target))\n else:\n self.values[target] = value\n ", "context": "class Environment(object):\n def set_value(self, target, value): ...\n def __init__(self): ...\n def missing_values(self): ...\n def add_error(self, msg, loc=None): ...\n def pre_stage(self): ...\n def post_stage(self): ...\n def traverse_tree(self, root): ...\n def format_errors(self): ...\n\n self.stage = None\n self.stack = []\n self.variables = {}\n self.values = {}\n self.acquisition = False\n self.errors = []\n self.dry_run = False\n self.generators = {}\n self.waveforms = {}\n self.cwd = None\n self.missing_shapes = set()\n self.frequency = Quantity(1, 'Hz')\n\n stages = Enum(['declarations', 'values', 'commands', 'waveforms'])\n prep_stages = [stages.declarations, stages.values, stages.commands]\n", "repository": "0/SpanishAcquisition", "test_name": "testValues", "smells": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002340.py"} {"focal_file": "spacq/interface/units.py", "focal_class": null, "focal_method": "assert_dimensions", "tests": "import unittest\n\nclass Test_assert_dimensions(unittest.TestCase):\n def testAssertDimensions(self):\n \"\"\"\n Ensure that dimensions are asserted correctly.\n \"\"\"\n q = units.Quantity(5, 's')\n assert q.assert_dimensions('s', exception=False)\n assert not q.assert_dimensions('N.m', exception=False)\n assert q.assert_dimensions(q, exception=False)\n assert q.assert_dimensions('s')\n assert_raises(units.IncompatibleDimensions, q.assert_dimensions, 'A')\n assert_raises(units.IncompatibleDimensions, eq_, units.Quantity(1, 's'), units.Quantity(1, 'm'))\n", "method_code": " def assert_dimensions(self, other, exception=True):\n \"\"\"\n \t\tWhether the dimensions match.\n \n \t\tIf exception is True and we would have returned False, raise an exception.\n \t\t\"\"\"\n if isinstance(other, basestring):\n other = Quantity(1, other).dimensions\n elif isinstance(other, Quantity):\n other = other.dimensions\n if self.dimensions == other:\n return True\n elif exception:\n raise IncompatibleDimensions(self.dimensions, other)\n else:\n return False\n ", "context": "class Quantity(object):\n def assert_dimensions(self, other, exception=True): ...\n def parse_units(string): ...\n def from_string(string): ...\n def __init__(self, value, units=None): ...\n def dimensions(self): ...\n def value(self): ...\n def original_value(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other): ...\n def __ne__(self, other): ...\n def __le__(self, other): ...\n def __ge__(self, other): ...\n def __gt__(self, other): ...\n def __abs__(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __mul__(self, other): ...\n def __rmul__(self, other): ...\n def __div__(self, other): ...\n def __repr__(self): ...\n def __str__(self): ...\n def __deepcopy__(self, memo): ...\n\n self._q = original_quantity.simplified\n self.original_units = units\n self.original_multiplier = multiplier\n", "repository": "0/SpanishAcquisition", "test_name": "testAssertDimensions", "smells": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002341.py"} {"focal_file": "jabber/label.py", "focal_class": null, "focal_method": "get_labels", "tests": "import unittest\n\nclass Test_get_labels(unittest.TestCase):\n def test_getLabels_GetsLabels(self):\n fname = 'foo.jpg'\n labels = ['bar', 'bar1']\n self.labeler._labels = {fname: labels}\n self.assertEqual(self.labeler.get_labels(fname), labels)\n", "method_code": " def get_labels(self, img_fname):\n \"\"\"\n Get labels associated with this image\n \n :param img_fname: The image filename\n :return: The list of labels associated with this image\n \"\"\"\n labels = list()\n try:\n labels = list(self._labels[img_fname])\n except KeyError:\n pass\n return labels\n ", "context": "class Labeler():\n def get_labels(self, img_fname): ...\n def __init__(self, fname): ...\n def get_classes(self): ...\n def get_keystrokes(self): ...\n def add_label(self, img_fname, label): ...\n def add_class(self, class_name): ...\n def match_class(self, key): ...\n def reset_matching(self): ...\n def delete_label(self, img_fname, label): ...\n def delete_class(self, class_name): ...\n def save(self): ...\n\n self._fname = fname\n self._labels = dict()\n self._classes = set()\n self._keystrokes = list()\n", "repository": "diffuse/jabber", "test_name": "test_getLabels_GetsLabels", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002342.py"} {"focal_file": "jabber/label.py", "focal_class": null, "focal_method": "delete_label", "tests": "import unittest\n\nclass Test_delete_label(unittest.TestCase):\n def test_deleteLabel_DeletesLabel(self):\n fname = 'foo.jpg'\n labels = {'bar', 'bar1'}\n self.labeler._labels = {fname: labels}\n self.labeler.delete_label(fname, 'bar')\n self.assertEqual(self.labeler._labels[fname], {'bar1'})\n", "method_code": " def delete_label(self, img_fname, label):\n \"\"\"\n Delete a label associated with an image filename\n \n :param img_fname: The image filename this label is associated with\n :param label: The label to delete\n \"\"\"\n try:\n self._labels[img_fname].remove(label)\n except (AttributeError, KeyError):\n logger.error(f'could not delete label {label} associated with img {img_fname}')\n ", "context": "class Labeler():\n def delete_label(self, img_fname, label): ...\n def __init__(self, fname): ...\n def get_labels(self, img_fname): ...\n def get_classes(self): ...\n def get_keystrokes(self): ...\n def add_label(self, img_fname, label): ...\n def add_class(self, class_name): ...\n def match_class(self, key): ...\n def reset_matching(self): ...\n def delete_class(self, class_name): ...\n def save(self): ...\n\n self._fname = fname\n self._labels = dict()\n self._classes = set()\n self._keystrokes = list()\n", "repository": "diffuse/jabber", "test_name": "test_deleteLabel_DeletesLabel", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002343.py"} {"focal_file": "jabber/label.py", "focal_class": null, "focal_method": "delete_class", "tests": "import unittest\n\nclass Test_delete_class(unittest.TestCase):\n def test_deleteClass_DeletesClass(self):\n classes = {'foo', 'bar'}\n self.labeler._classes = classes\n self.labeler.delete_class('foo')\n self.assertEqual(self.labeler._classes, {'bar'})\n", "method_code": " def delete_class(self, class_name):\n \"\"\"\n Delete a class\n \n :param class_name: The class to delete\n \"\"\"\n try:\n for labels in self._labels.values():\n if class_name in labels:\n logger.error(f'could not delete class {class_name}, it is still being used as a label')\n return\n self._classes.remove(class_name)\n except KeyError:\n logger.error(f'could not delete class {class_name}')\n ", "context": "class Labeler():\n def delete_class(self, class_name): ...\n def __init__(self, fname): ...\n def get_labels(self, img_fname): ...\n def get_classes(self): ...\n def get_keystrokes(self): ...\n def add_label(self, img_fname, label): ...\n def add_class(self, class_name): ...\n def match_class(self, key): ...\n def reset_matching(self): ...\n def delete_label(self, img_fname, label): ...\n def save(self): ...\n\n self._fname = fname\n self._labels = dict()\n self._classes = set()\n self._keystrokes = list()\n", "repository": "diffuse/jabber", "test_name": "test_deleteClass_DeletesClass", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002344.py"} {"focal_file": "sklearn/utils/testing.py", "focal_class": null, "focal_method": "_assert_less", "tests": "import unittest\n\nclass Test_assert_less(unittest.TestCase):\n def test_assert_less():\n assert_less(0, 1)\n _assert_less(0, 1)\n assert_raises(AssertionError, assert_less, 1, 0)\n assert_raises(AssertionError, _assert_less, 1, 0)\n", "method_code": "def _assert_less(a, b, msg=None):\n message = '%r is not lower than %r' % (a, b)\n if msg is not None:\n message += ': ' + msg\n assert a < b, message", "context": "def _assert_less(a, b, msg=None): ...\ndef _assert_less(a, b, msg=None): ...\ndef _assert_greater(a, b, msg=None): ...\ndef assert_less_equal(a, b, msg=None): ...\ndef assert_greater_equal(a, b, msg=None): ...\ndef assert_warns(warning_class, func, *args, **kw): ...\ndef assert_warns_message(warning_class, message, func, *args, **kw): ...\ndef assert_no_warnings(func, *args, **kw): ...\ndef ignore_warnings(obj=None): ...\ndef _ignore_warnings(fn): ...\ndef _assert_allclose(actual, desired, rtol=1e-07, atol=0, err_msg='', verbose=True): ...\ndef assert_raise_message(exceptions, message, function, *args, **kwargs): ...\ndef fake_mldata(columns_dict, dataname, matfile, ordering=None): ...\ndef install_mldata_mock(mock_datasets): ...\ndef uninstall_mldata_mock(): ...\ndef all_estimators(include_meta_estimators=False, include_other=False, type_filter=None, include_dont_test=False): ...\ndef set_random_state(estimator, random_state=0): ...\ndef if_matplotlib(func): ...\ndef skip_if_32bit(func): ...\ndef if_not_mac_os(versions=('10.7', '10.8', '10.9'), message='Multi-process bug in Mac OS X >= 10.7 (see issue #636)'): ...\ndef if_safe_multiprocessing_with_blas(func): ...\ndef clean_warning_registry(): ...\ndef check_skip_network(): ...\ndef check_skip_travis(): ...\ndef _delete_folder(folder_path, warn=False): ...\n", "repository": "matthewmazzuca/thesislearning", "test_name": "test_assert_less", "smells": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002345.py"} {"focal_file": "sklearn/utils/testing.py", "focal_class": null, "focal_method": "_assert_greater", "tests": "import unittest\n\nclass Test_assert_greater(unittest.TestCase):\n def test_assert_greater():\n assert_greater(1, 0)\n _assert_greater(1, 0)\n assert_raises(AssertionError, assert_greater, 0, 1)\n assert_raises(AssertionError, _assert_greater, 0, 1)\n", "method_code": "def _assert_greater(a, b, msg=None):\n message = '%r is not greater than %r' % (a, b)\n if msg is not None:\n message += ': ' + msg\n assert a > b, message", "context": "def _assert_greater(a, b, msg=None): ...\ndef _assert_less(a, b, msg=None): ...\ndef _assert_greater(a, b, msg=None): ...\ndef assert_less_equal(a, b, msg=None): ...\ndef assert_greater_equal(a, b, msg=None): ...\ndef assert_warns(warning_class, func, *args, **kw): ...\ndef assert_warns_message(warning_class, message, func, *args, **kw): ...\ndef assert_no_warnings(func, *args, **kw): ...\ndef ignore_warnings(obj=None): ...\ndef _ignore_warnings(fn): ...\ndef _assert_allclose(actual, desired, rtol=1e-07, atol=0, err_msg='', verbose=True): ...\ndef assert_raise_message(exceptions, message, function, *args, **kwargs): ...\ndef fake_mldata(columns_dict, dataname, matfile, ordering=None): ...\ndef install_mldata_mock(mock_datasets): ...\ndef uninstall_mldata_mock(): ...\ndef all_estimators(include_meta_estimators=False, include_other=False, type_filter=None, include_dont_test=False): ...\ndef set_random_state(estimator, random_state=0): ...\ndef if_matplotlib(func): ...\ndef skip_if_32bit(func): ...\ndef if_not_mac_os(versions=('10.7', '10.8', '10.9'), message='Multi-process bug in Mac OS X >= 10.7 (see issue #636)'): ...\ndef if_safe_multiprocessing_with_blas(func): ...\ndef clean_warning_registry(): ...\ndef check_skip_network(): ...\ndef check_skip_travis(): ...\ndef _delete_folder(folder_path, warn=False): ...\n", "repository": "matthewmazzuca/thesislearning", "test_name": "test_assert_greater", "smells": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002346.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_samples.py", "focal_class": null, "focal_method": "mann_whitney_test", "tests": "import unittest\n\nclass Test_mann_whitney_test(unittest.TestCase):\n @dense_sparse\n def test_mann_whitney_test(self, array):\n self.data.X = array(self.data.X)\n d = self.annotator.mann_whitney_test(self.data)\n self.assertEqual(type(d), Table)\n self.assertTupleEqual(self.data.X.shape, d.X.shape)\n", "method_code": " def mann_whitney_test(data):\n \"\"\"\n Compute z values with Mann-Whitney U test.\n \n Parameters\n ----------\n data : Orange.data.Table\n Tabular data with gene expressions\n \n Returns\n -------\n Orange.data.Table\n Z-value for each item.\n \"\"\"\n df, columns = AnnotateSamplesMeta._to_pandas(data, use_entrez_id=False)\n df_z_values = AnnotateSamples.mann_whitney_test(df)\n z_table = Table(data.domain, df_z_values.values, data.Y, metas=data.metas)\n return z_table\n ", "context": "class AnnotateSamplesMeta():\n @staticmethod\n def mann_whitney_test(data): ...\n def _to_pandas(data, use_entrez_id=False): ...\n def _prepare_annotations(ann): ...\n def assign_annotations(z_values, available_annotations, data, z_threshold=1, p_value_fun=PFUN_BINOMIAL, scoring=SCORING_EXP_RATIO): ...\n def filter_annotations(scores, p_values, return_nonzero_annotations=True, p_threshold=0.05): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002347.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_samples.py", "focal_class": null, "focal_method": "assign_annotations", "tests": "import unittest\n\nclass Test_assign_annotations(unittest.TestCase):\n @dense_sparse\n def test_assign_annotations(self, array):\n z = np.array([[1.1, 1.1, 1.1, 1.1, 0, 0, 0, 0], [1.1, 1.1, 0, 0, 1.1, 0, 0, 0], [1.1, 0, 0, 0, 1.1, 1.1, 0, 0], [0, 0, 0, 0, 1.1, 1.1, 1.1, 1.1]])\n z_table = Table(self.domain, z)\n attrs = [{'111', '112', '113', '114'}, {'111', '112', '211'}, {'211', '212', '111'}, {'211', '212', '213', '214'}]\n exp_ann = np.array([[1, 0], [1 / 2, 1 / 4], [1 / 4, 1 / 2], [0, 1]])\n self.data.X = array(self.data.X)\n annotations, fdrs = self.annotator.assign_annotations(z_table, self.markers, self.data[:4])\n self.assertEqual(len(attrs), len(annotations))\n self.assertEqual(len(attrs), len(fdrs))\n self.assertEqual(2, annotations.X.shape[1])\n self.assertEqual(2, fdrs.X.shape[1])\n np.testing.assert_array_almost_equal(exp_ann, annotations)\n exp_fdrs_smaller = np.array([[0.05, 2], [2, 2], [2, 2], [2, 0.05]])\n np.testing.assert_array_less(fdrs, exp_fdrs_smaller)\n", "method_code": " def assign_annotations(z_values, available_annotations, data, z_threshold=1, p_value_fun=PFUN_BINOMIAL, scoring=SCORING_EXP_RATIO):\n \"\"\"\n The function gets a set of attributes (e.g. genes) for each cell and\n attributes for each annotation. It returns the annotations significant\n for each cell.\n \n Parameters\n ----------\n z_values : Orange.data.Table\n Table which show z values for each item\n available_annotations : Orange.data.Table\n Available annotations (e.g. cell types)\n z_threshold : float\n The threshold for selecting the attribute. For each item the\n attributes with z-value above this value are selected.\n p_value_fun : str, optional (defaults: TEST_BINOMIAL)\n A function that calculates p-value. It can be either\n PFUN_BINOMIAL that uses statistics.Binomial().p_value or\n PFUN_HYPERGEOMETRIC that uses hypergeom.sf.\n data : Orange.data.Table\n Tabular data with gene expressions - we need that to compute scores.\n scoring : str, optional (default=SCORING_EXP_RATIO)\n Type of scoring\n \n Returns\n -------\n Orange.data.Table\n Annotation probabilities\n Orange.data.Table\n Annotation fdrs\n \"\"\"\n assert TAX_ID in data.attributes, 'The input table needs to have a tax_id attribute'\n assert any(('Entrez ID' in x.attributes for x in data.domain.attributes)), 'Input data do not contain gene expression data.'\n tax_id = data.attributes[TAX_ID]\n n = len(GeneInfo(tax_id))\n df_z_values, _ = AnnotateSamplesMeta._to_pandas(z_values, use_entrez_id=True)\n df_data, _ = AnnotateSamplesMeta._to_pandas(data, use_entrez_id=True)\n df_available_annotations = AnnotateSamplesMeta._prepare_annotations(available_annotations)\n df_available_annotations = df_available_annotations[df_available_annotations['Gene'] != '?']\n scores, fdrs = AnnotateSamples.assign_annotations(df_z_values, df_available_annotations, df_data, num_all_attributes=n, attributes_col='Gene', annotations_col='Cell Type', z_threshold=z_threshold, p_value_fun=p_value_fun, scoring=scoring)\n domain = Domain([ContinuousVariable(ct) for ct in scores.columns.values])\n scores_table = Table(domain, scores.values)\n fdrs_table = Table(domain, fdrs.values)\n return (scores_table, fdrs_table)\n ", "context": "class AnnotateSamplesMeta():\n @staticmethod\n def assign_annotations(z_values, available_annotations, data, z_threshold=1, p_value_fun=PFUN_BINOMIAL, scoring=SCORING_EXP_RATIO): ...\n def _to_pandas(data, use_entrez_id=False): ...\n def mann_whitney_test(data): ...\n def _prepare_annotations(ann): ...\n def filter_annotations(scores, p_values, return_nonzero_annotations=True, p_threshold=0.05): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002348.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_projection.py", "focal_class": null, "focal_method": "annotate_projection", "tests": "import unittest\n\nclass Test_annotate_projection(unittest.TestCase):\n def test_annotate_projection(self):\n clusters, clusters_meta, eps = annotate_projection(self.annotations, self.data, clustering_algorithm=DBSCAN, labels_per_cluster=2, eps=3.0)\n self.assertListEqual(list(map(clusters.domain.attributes[0].repr_val, clusters.X[:, 0])), ['C2'] * 5 + ['C1'] * 7)\n self.assertEqual(len(clusters_meta), 2)\n self.assertEqual(len(clusters_meta['C1']), 3)\n self.assertEqual(len(clusters_meta['C2']), 3)\n self.assertEqual(clusters_meta['C1'][0][0][0], 'b')\n self.assertAlmostEqual(clusters_meta['C1'][0][0][1], 4 / 7, 5)\n self.assertEqual(clusters_meta['C1'][0][1][0], 'c')\n self.assertAlmostEqual(clusters_meta['C1'][0][1][1], 3 / 7, 5)\n self.assertEqual(2, len(clusters_meta['C1'][1]))\n self.assertEqual(2, clusters_meta['C1'][2].shape[1])\n self.assertEqual(2, clusters_meta['C1'][2].shape[1])\n self.assertEqual(float, type(eps))\n", "method_code": "def annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs):\n \"\"\"\n Function cluster the data based on coordinates, and assigns a certain number\n of labels per cluster. Each cluster gets `labels_per_cluster` number of most\n common labels in cluster assigned.\n\n Parameters\n ----------\n annotations : Orange.data.Table\n Table with annotations and their probabilities.\n coordinates : Orange.data.Table\n Visualisation coordinates - embeddings\n clustering_algorithm : callable, optional (default = DBSCAN)\n Algorithm used in clustering.\n labels_per_cluster : int, optional (default = 3)\n Number of labels that need to be assigned to each cluster.\n\n Returns\n -------\n Orange.data.Table\n List of cluster indices.\n dict\n Dictionary with cluster index as a key and list of annotations as a\n value. Each list include tuples with the annotation name and their\n proportion in the cluster.\n dict\n The coordinates for locating the label. Dictionary with cluster index\n as a key and tuple (x, y) as a value.\n \"\"\"\n assert len(annotations) == len(coordinates), 'Number of coordinates does not match to number of annotations'\n assert len(coordinates) > 0, 'At least one data point need to be provided'\n assert len(coordinates.domain) > 0, 'Coordinates need to have at least one attribute'\n eps = kwargs.get('eps', get_epsilon(coordinates))\n if clustering_algorithm == DBSCAN:\n kwargs['eps'] = eps\n clusters = cluster_data(coordinates, clustering_algorithm, **kwargs)\n annotations_cl, item_annotations = assign_labels(clusters, annotations, labels_per_cluster)\n labels_loc = labels_locations(coordinates, clusters)\n concave_hull = compute_concave_hulls(coordinates, clusters, eps)\n clusters_meta = {}\n for cl in annotations_cl.keys():\n clusters_meta[cl] = (annotations_cl[cl], labels_loc[cl], concave_hull[cl])\n clusters, clusters_meta = _filter_clusters(clusters, clusters_meta)\n clusters_ann = Table(Domain(clusters.domain.attributes + item_annotations.domain.attributes), np.concatenate((clusters.X, item_annotations.X), axis=1))\n return (clusters_ann, clusters_meta, eps)", "context": "def annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs): ...\ndef cluster_data(coordinates, clustering_algorithm=DBSCAN, **kwargs): ...\ndef assign_labels(clusters, annotations, labels_per_cluster): ...\ndef labels_locations(coordinates, clusters): ...\ndef get_epsilon(coordinates, k=10, skip=0.1): ...\ndef _angle(v1, v2): ...\ndef _find_hull(edges_list, points_list, starting_edge): ...\ndef edges_to_polygon(edges_list, points_list): ...\ndef compute_concave_hulls(coordinates, clusters, epsilon): ...\ndef _filter_clusters(clusters, clusters_meta): ...\ndef annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs): ...\ndef cluster_additional_points(coordinates, hulls, cluster_attribute=None): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_annotate_projection", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002349.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_projection.py", "focal_class": null, "focal_method": "labels_locations", "tests": "import unittest\n\nclass Test_labels_locations(unittest.TestCase):\n def test_labels_location(self):\n clusters = Table.from_list(Domain([DiscreteVariable('cl', values=['1', '2'])]), [[0]] * 6 + [[1]] * 6)\n locs = labels_locations(self.data, clusters)\n self.assertEqual(dict, type(locs))\n self.assertEqual(tuple, type(locs['1']))\n self.assertEqual(tuple, type(locs['2']))\n", "method_code": "def labels_locations(coordinates, clusters):\n \"\"\"\n Function computes the location of the label for each cluster.\n The location is compute as a center point.\n\n Parameters\n ----------\n coordinates : Orange.data.Table\n Visualisation coordinates - embeddings\n clusters : Orange.data.Table\n Cluster indices for each item.\n\n Returns\n -------\n dict\n The coordinates for locating the label. Dictionary with cluster index\n as a key and tuple (x, y) as a value.\n \"\"\"\n clusters_unique = set(clusters.domain[0].values) - {'-1'}\n locations = {}\n for cl in clusters_unique:\n mask = np.array(list(map(clusters.domain.attributes[0].repr_val, clusters.X[:, 0]))).flatten() == cl\n cl_coordinates = coordinates.X[mask, :]\n x, y = 1 / 2 * (np.min(cl_coordinates, axis=0) + np.max(cl_coordinates, axis=0))\n locations[cl] = (x, y)\n return locations", "context": "def labels_locations(coordinates, clusters): ...\ndef cluster_data(coordinates, clustering_algorithm=DBSCAN, **kwargs): ...\ndef assign_labels(clusters, annotations, labels_per_cluster): ...\ndef labels_locations(coordinates, clusters): ...\ndef get_epsilon(coordinates, k=10, skip=0.1): ...\ndef _angle(v1, v2): ...\ndef _find_hull(edges_list, points_list, starting_edge): ...\ndef edges_to_polygon(edges_list, points_list): ...\ndef compute_concave_hulls(coordinates, clusters, epsilon): ...\ndef _filter_clusters(clusters, clusters_meta): ...\ndef annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs): ...\ndef cluster_additional_points(coordinates, hulls, cluster_attribute=None): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_labels_location", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002350.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_projection.py", "focal_class": null, "focal_method": "get_epsilon", "tests": "import unittest\n\nclass Test_get_epsilon(unittest.TestCase):\n def test_get_epsilon(self):\n data = Table.from_file('iris')\n eps = get_epsilon(data)\n self.assertGreaterEqual(eps, 0.9)\n", "method_code": "def get_epsilon(coordinates, k=10, skip=0.1):\n \"\"\"\n The function computes the epsilon parameter for DBSCAN through method\n proposed in the paper.\n\n Parameters\n ----------\n coordinates : Orange.data.Table\n Visualisation coordinates - embeddings\n k : int\n Number kth observed neighbour\n skip : float\n Percentage of skipped neighborus.\n\n Returns\n -------\n float\n Epsilon parameter for DBSCAN\n \"\"\"\n x = coordinates.X\n if len(x) > 1000:\n i = len(x) // 1000\n x = x[::i]\n d = distance.squareform(distance.pdist(x))\n k = min(k + 1, len(coordinates) - 1)\n kth_point = np.argpartition(d, k, axis=1)[:, k]\n kth_dist = np.sort(d[np.arange(0, len(kth_point)), kth_point])\n return kth_dist[-int(np.round(len(kth_dist) * skip))]", "context": "def get_epsilon(coordinates, k=10, skip=0.1): ...\ndef cluster_data(coordinates, clustering_algorithm=DBSCAN, **kwargs): ...\ndef assign_labels(clusters, annotations, labels_per_cluster): ...\ndef labels_locations(coordinates, clusters): ...\ndef get_epsilon(coordinates, k=10, skip=0.1): ...\ndef _angle(v1, v2): ...\ndef _find_hull(edges_list, points_list, starting_edge): ...\ndef edges_to_polygon(edges_list, points_list): ...\ndef compute_concave_hulls(coordinates, clusters, epsilon): ...\ndef _filter_clusters(clusters, clusters_meta): ...\ndef annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs): ...\ndef cluster_additional_points(coordinates, hulls, cluster_attribute=None): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_get_epsilon", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002351.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_projection.py", "focal_class": null, "focal_method": "compute_concave_hulls", "tests": "import unittest\n\nclass Test_compute_concave_hulls(unittest.TestCase):\n def test_compute_concave_hulls(self):\n data = Table.from_file('iris')[:, 2:4]\n clusters = Table.from_list(Domain([DiscreteVariable('cl', values=['1', '2', '3'])]), [[0]] * 50 + [[1]] * 50 + [[2]] * 50)\n hulls = compute_concave_hulls(data, clusters, epsilon=0.5)\n self.assertEqual(3, len(hulls))\n self.assertEqual(2, hulls['1'].shape[1])\n self.assertEqual(2, hulls['2'].shape[1])\n self.assertEqual(2, hulls['3'].shape[1])\n\n def test_compute_concave_hulls_subsampling(self):\n \"\"\"\n When more than 1000 points passed they are sub-sampled in order to\n compute a concave hull\n \"\"\"\n iris = Table.from_file('iris')\n data = Table.from_numpy(Domain(iris.domain.attributes[2:4]), np.repeat(iris.X[:, 2:4], 10, axis=0))\n clusters = Table.from_list(Domain([DiscreteVariable('cl', values=['1', '2', '3'])]), [[0]] * 50 * 10 + [[1]] * 50 * 10 + [[2]] * 50 * 10)\n hulls = compute_concave_hulls(data, clusters, epsilon=0.5)\n self.assertEqual(3, len(hulls))\n self.assertEqual(2, hulls['1'].shape[1])\n self.assertEqual(2, hulls['2'].shape[1])\n self.assertEqual(2, hulls['3'].shape[1])\n\n def test_compute_concave_hulls_triangle(self):\n \"\"\"\n Concave hull must also work for tree points - it is a special case\n \"\"\"\n data = Table.from_numpy(Domain([ContinuousVariable('x'), ContinuousVariable('y')]), np.array([[1, 1], [1, 2], [2, 1]]))\n clusters = Table.from_list(Domain([DiscreteVariable('cl', values=['1'])]), [[0]] * 3)\n hulls = compute_concave_hulls(data, clusters, epsilon=0.5)\n self.assertEqual(1, len(hulls))\n self.assertEqual(2, hulls['1'].shape[1])\n", "method_code": "def compute_concave_hulls(coordinates, clusters, epsilon):\n \"\"\"\n Function computes the points of the concave hull around points.\n\n Parameters\n ----------\n coordinates : Orange.data.Table\n Visualisation coordinates - embeddings\n clusters : Orange.data.Table\n Cluster indices for each item.\n epsilon : float\n Epsilon used by DBSCAN to cluster the data\n\n Returns\n -------\n dict\n The points of the concave hull. Dictionary with cluster index\n as a key and np.ndaray of points as a value -\n [[x1, y1], [x2, y2], [x3, y3], ...]\n \"\"\"\n\n def get_shape(pts, eps):\n \"\"\"\n Compute the shape (concave hull) of a set of a cluster.\n \"\"\"\n\n def add_edge(edges_list, i, j):\n \"\"\"\n Add a line between the i-th and j-th points,\n if not in the list already. Remove the lines that are not outer\n edges - when (j, i) already in list means that two triangles\n has same edge what means it is not an outer edge\n \"\"\"\n if (j, i) in edges_list:\n edges_list.remove((j, i))\n return\n edges_list.add((i, j))\n if len(pts) < 4:\n rng = list(range(3))\n return edges_to_polygon(zip(rng, rng[1:] + rng[:1]), pts)\n tri = Delaunay(pts)\n edges = set()\n for ia, ib, ic in tri.vertices:\n pa = pts[ia]\n pb = pts[ib]\n pc = pts[ic]\n a = sqrt((pa[0] - pb[0]) ** 2 + (pa[1] - pb[1]) ** 2)\n b = sqrt((pb[0] - pc[0]) ** 2 + (pb[1] - pc[1]) ** 2)\n c = sqrt((pc[0] - pa[0]) ** 2 + (pc[1] - pa[1]) ** 2)\n if max(a, b, c) <= eps:\n add_edge(edges, ia, ib)\n add_edge(edges, ib, ic)\n add_edge(edges, ic, ia)\n polygon = edges_to_polygon(edges, pts)\n return polygon\n hulls = {}\n clusters_array = np.array(list(map(clusters.domain.attributes[0].repr_val, clusters.X[:, 0])))\n for cl in set(clusters_array) - {'None', '?'}:\n points = coordinates.X[clusters_array == cl]\n if points.shape[0] > 1000:\n points = points[np.random.randint(points.shape[0], size=1000), :]\n hull = get_shape(points, eps=epsilon * 2)\n scaling_factor = 1000\n scaled_hull = pyclipper.scale_to_clipper(hull, scaling_factor)\n pco1 = pyclipper.PyclipperOffset()\n pco1.AddPath(scaled_hull, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)\n im_solution = pco1.Execute(epsilon * scaling_factor * 3)\n pco2 = pyclipper.PyclipperOffset()\n pco2.AddPath(im_solution[0], pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)\n solution = pyclipper.scale_from_clipper(pco2.Execute(epsilon * scaling_factor * -2), scaling_factor)\n hulls[cl] = np.array(solution).reshape(-1, 2)\n return hulls", "context": "def compute_concave_hulls(coordinates, clusters, epsilon): ...\ndef cluster_data(coordinates, clustering_algorithm=DBSCAN, **kwargs): ...\ndef assign_labels(clusters, annotations, labels_per_cluster): ...\ndef labels_locations(coordinates, clusters): ...\ndef get_epsilon(coordinates, k=10, skip=0.1): ...\ndef _angle(v1, v2): ...\ndef _find_hull(edges_list, points_list, starting_edge): ...\ndef edges_to_polygon(edges_list, points_list): ...\ndef compute_concave_hulls(coordinates, clusters, epsilon): ...\ndef _filter_clusters(clusters, clusters_meta): ...\ndef annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs): ...\ndef cluster_additional_points(coordinates, hulls, cluster_attribute=None): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_compute_concave_hulls", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002352.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_projection.py", "focal_class": null, "focal_method": "cluster_additional_points", "tests": "import unittest\n\nclass Test_cluster_additional_points(unittest.TestCase):\n def test_cluster_additional_points_simple(self):\n \"\"\"\n Test with the simple convex hull\n \"\"\"\n hull = {'C1': np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]])}\n x, y = np.meshgrid(np.arange(-1.0, 2.0, 0.2), np.arange(-1, 2.0, 0.2))\n points = Table.from_numpy(Domain([ContinuousVariable('x'), ContinuousVariable('y')]), np.concatenate((x.reshape(-1, 1), y.reshape(-1, 1)), axis=1))\n clusters = cluster_additional_points(points, hull)\n expected = [0.0 if 0 < x < 1 and 0 < y < 1 else np.nan for x, y in points.X]\n np.testing.assert_array_equal(clusters.X.flatten(), expected)\n\n def test_cluster_additional_points_concave(self):\n \"\"\"\n Test with the concave hull\n \"\"\"\n hull = {'C1': np.array([[0.0, 0.0], [0.3, 0.5], [0.0, 1.0], [1.0, 1.0], [0.7, 0.5], [1.0, 0.0]])}\n p = [[-1.0, -1], [0.2, 0.5], [0.8, 0.5], [0.5, 0.5], [0.5, 0.7], [0.5, 0.3], [0.2, 0.9], [0.2, 0.1]]\n points = Table.from_list(Domain([ContinuousVariable('x'), ContinuousVariable('y')]), p)\n clusters = cluster_additional_points(points, hull)\n expected = [np.nan] * 3 + [0.0] * 5\n np.testing.assert_array_equal(clusters.X.flatten(), expected)\n\n def test_cluster_additional_points_more_clusters(self):\n \"\"\"\n Test with more concave hulls\n \"\"\"\n points_table = Table.from_list(Domain([ContinuousVariable('x'), ContinuousVariable('y')]), self.points)\n clusters = cluster_additional_points(points_table, self.hull)\n clusters = list(map(clusters.domain.attributes[0].repr_val, clusters.X[:, 0]))\n expected = ['?'] * 3 + ['C1'] * 5 + ['C2'] * 2 + ['?'] * 2\n np.testing.assert_array_equal(clusters, expected)\n\n def test_cluster_additional_points_with_existing_domain(self):\n \"\"\"\n Test with the concave hull\n \"\"\"\n points = Table.from_list(Domain([ContinuousVariable('x'), ContinuousVariable('y')]), self.points)\n attr = DiscreteVariable('Clusters', values=['C2', 'C1'])\n clusters = cluster_additional_points(points, self.hull, cluster_attribute=attr)\n cluster_map = list(map(clusters.domain.attributes[0].repr_val, clusters.X[:, 0]))\n expected = ['?'] * 3 + ['C1'] * 5 + ['C2'] * 2 + ['?'] * 2\n np.testing.assert_array_equal(cluster_map, expected)\n self.assertEqual(attr, clusters.domain.attributes[0])\n self.assertSequenceEqual(attr.values, clusters.domain.attributes[0].values)\n", "method_code": "def cluster_additional_points(coordinates, hulls, cluster_attribute=None):\n \"\"\"\n This function receives additional points and assign them current existing\n clusters based on current concave hull.\n\n Parameters\n ----------\n coordinates : Orange.data.Table\n Visualisation coordinates - embeddings\n hulls : dict\n Concave hull for each cluster\n cluster_attribute : Orange.data.DiscreteVariable (optional)\n A variable for clusters. If cluster_attribute is provided it will be\n used in the creation of the resulting Table.\n\n Returns\n -------\n Orange.data.Table\n Cluster label for each point\n \"\"\"\n\n def point_in_polygon_test(test_point, polygon_points):\n \"\"\"\n This function uses the horizontal ray casting to find out if the point\n is in the hull/polygon. For each point, it tests how many times the\n horizontal ray from test_point to infinity crosses the polygon edge. If\n it happens odd many times the point is in the polygon.\n https://stackoverflow.com/a/2922778/3551700\n \"\"\"\n test_x = test_point[0]\n test_y = test_point[1]\n is_inside = False\n for (x1, y1), (x2, y2) in zip(polygon_points, np.concatenate((polygon_points[1:], polygon_points[:1]), axis=0)):\n if (y1 > test_y) != (y2 > test_y):\n intersection_x = (x2 - x1) * (test_y - y1) / (y2 - y1) + x1\n if test_x < intersection_x:\n is_inside = not is_inside\n return is_inside\n clusters = [None] * len(coordinates)\n for cluster, hull in hulls.items():\n for i, c in enumerate(coordinates.X):\n if point_in_polygon_test(c, hull):\n clusters[i] = cluster\n if cluster_attribute is not None:\n assert all((i in cluster_attribute.values for i in set(clusters) - {None})), 'cluster_attribute does not have all required values.'\n new_domain = Domain([DiscreteVariable('Clusters', values=sorted(list(hulls.keys()))) if cluster_attribute is None else cluster_attribute])\n return Table(new_domain, np.array(list(map(new_domain[0].to_val, clusters))).reshape(-1, 1))", "context": "def cluster_additional_points(coordinates, hulls, cluster_attribute=None): ...\ndef cluster_data(coordinates, clustering_algorithm=DBSCAN, **kwargs): ...\ndef assign_labels(clusters, annotations, labels_per_cluster): ...\ndef labels_locations(coordinates, clusters): ...\ndef get_epsilon(coordinates, k=10, skip=0.1): ...\ndef _angle(v1, v2): ...\ndef _find_hull(edges_list, points_list, starting_edge): ...\ndef edges_to_polygon(edges_list, points_list): ...\ndef compute_concave_hulls(coordinates, clusters, epsilon): ...\ndef _filter_clusters(clusters, clusters_meta): ...\ndef annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs): ...\ndef cluster_additional_points(coordinates, hulls, cluster_attribute=None): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_cluster_additional_points_simple", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002353.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_projection.py", "focal_class": null, "focal_method": "_angle", "tests": "import unittest\n\nclass Test_angle(unittest.TestCase):\n def test_angle(self):\n v1 = ([1, 0], [0, 0])\n v2_1 = [0, 0]\n test_cases = [[1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1]]\n real_angles = [np.pi * i / 4 for i in range(8)]\n computed_angles = [_angle(v1, (v2_1, x)) for x in test_cases]\n np.testing.assert_array_almost_equal(computed_angles, real_angles)\n v1 = ([2, 2], [1, 2])\n v2_1 = np.array([1, 2])\n test_cases = np.array([[1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1]]) + v2_1\n real_angles = [np.pi * i / 4 for i in range(8)]\n computed_angles = [_angle(v1, (v2_1, x)) for x in test_cases]\n np.testing.assert_array_almost_equal(computed_angles, real_angles)\n self.assertAlmostEqual(_angle(([-2, 1], [0, 0]), ([0, 0], [1, 2])), np.pi / 2)\n self.assertAlmostEqual(_angle(([-4, 1], [-2, 0]), ([-2, 0], [-1, 2])), np.pi / 2)\n self.assertAlmostEqual(_angle(([-4, 3], [-2, 2]), ([-2, 2], [-1, 4])), np.pi / 2)\n", "method_code": "def _angle(v1, v2):\n \"\"\"\n Compute clockwise angles between v1 and v2. Both vectors are\n given as a tuple with two points ([x1, y1], [x2, y2]) such that\n [x2, y2] of v1 == [x1, y1] of v2.\n The angle is given in degrees between 0 and 2 * pi\n \"\"\"\n v1, v2 = (np.array(v1), np.array(v2))\n x1, y1 = v1[0] - v1[1]\n x2, y2 = v2[1] - v2[0]\n dot = np.sum(x1 * x2 + y1 * y2)\n det = x1 * y2 - y1 * x1\n angle = np.arctan2(det, dot)\n return -angle if angle <= 0 else np.pi + np.pi - angle", "context": "def _angle(v1, v2): ...\ndef cluster_data(coordinates, clustering_algorithm=DBSCAN, **kwargs): ...\ndef assign_labels(clusters, annotations, labels_per_cluster): ...\ndef labels_locations(coordinates, clusters): ...\ndef get_epsilon(coordinates, k=10, skip=0.1): ...\ndef _angle(v1, v2): ...\ndef _find_hull(edges_list, points_list, starting_edge): ...\ndef edges_to_polygon(edges_list, points_list): ...\ndef compute_concave_hulls(coordinates, clusters, epsilon): ...\ndef _filter_clusters(clusters, clusters_meta): ...\ndef annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs): ...\ndef cluster_additional_points(coordinates, hulls, cluster_attribute=None): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_angle", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002354.py"} {"focal_file": "orangecontrib/bioinformatics/annotation/annotate_projection.py", "focal_class": null, "focal_method": "_filter_clusters", "tests": "import unittest\n\nclass Test_filter_clusters(unittest.TestCase):\n def test_cluster_filtering(self):\n \"\"\"\n Cluster filtering was introduced in order to remove clusters that\n does not have any labels.\n \"\"\"\n\n def assert_dict_same(d1, d2):\n self.assertTrue(len(d1) == len(d2) and sorted(d1) == sorted(d2))\n clusters = Table.from_list(Domain([DiscreteVariable('Clusters', values=['C1', 'C2'])]), [[0]] * 6 + [[1]] * 5)\n metas = {'C1': 'test1', 'C2': 'test 2'}\n new_clusters, new_metas = _filter_clusters(clusters, metas)\n self.assertEqual(11, len(clusters))\n self.assertSequenceEqual(['C1', 'C2'], clusters.domain['Clusters'].values)\n np.testing.assert_array_equal(np.array([[0]] * 6 + [[1]] * 5), clusters.X)\n assert_dict_same(metas, {'C1': 'test1', 'C2': 'test 2'})\n self.assertEqual(11, len(new_clusters))\n self.assertSequenceEqual(['C1', 'C2'], new_clusters.domain['Clusters'].values)\n np.testing.assert_array_equal(np.array([[0]] * 6 + [[1]] * 5), new_clusters.X)\n assert_dict_same(new_metas, {'C1': 'test1', 'C2': 'test 2'})\n clusters = Table.from_list(Domain([DiscreteVariable('Clusters', values=['C1', 'C2'])]), [[0]] * 6 + [[1]] * 5)\n metas = {'C1': 'test1'}\n new_clusters, new_metas = _filter_clusters(clusters, metas)\n self.assertEqual(11, len(clusters))\n self.assertSequenceEqual(['C1', 'C2'], clusters.domain['Clusters'].values)\n np.testing.assert_array_equal(np.array([[0]] * 6 + [[1]] * 5), clusters.X)\n assert_dict_same(metas, {'C1': 'test1'})\n self.assertEqual(11, len(new_clusters))\n self.assertSequenceEqual(['C1'], new_clusters.domain['Clusters'].values)\n np.testing.assert_array_equal(np.array([[0]] * 6 + [[np.nan]] * 5), new_clusters.X)\n assert_dict_same(new_metas, {'C1': 'test1'})\n", "method_code": "def _filter_clusters(clusters, clusters_meta):\n \"\"\"\n Function removes clusters that does not has any labels\n \"\"\"\n clust_map = {c: i for i, c in enumerate((c for c in clusters.domain['Clusters'].values if c in clusters_meta))}\n clust_idx = np.zeros(clusters.X.shape) * np.nan\n for i, cl in enumerate(map(clusters.domain.attributes[0].repr_val, clusters.X[:, 0])):\n clust_idx[i, 0] = clust_map.get(cl, np.nan)\n new_clusters = Table(Domain([DiscreteVariable('Clusters', values=clusters.domain['Clusters'].values[:len(clust_map)])]), clust_idx)\n new_clusters_meta = {'C{}'.format(clust_map[cl] + 1): v for cl, v in clusters_meta.items()}\n return (new_clusters, new_clusters_meta)", "context": "def _filter_clusters(clusters, clusters_meta): ...\ndef cluster_data(coordinates, clustering_algorithm=DBSCAN, **kwargs): ...\ndef assign_labels(clusters, annotations, labels_per_cluster): ...\ndef labels_locations(coordinates, clusters): ...\ndef get_epsilon(coordinates, k=10, skip=0.1): ...\ndef _angle(v1, v2): ...\ndef _find_hull(edges_list, points_list, starting_edge): ...\ndef edges_to_polygon(edges_list, points_list): ...\ndef compute_concave_hulls(coordinates, clusters, epsilon): ...\ndef _filter_clusters(clusters, clusters_meta): ...\ndef annotate_projection(annotations, coordinates, clustering_algorithm=DBSCAN, labels_per_cluster=3, **kwargs): ...\ndef cluster_additional_points(coordinates, hulls, cluster_attribute=None): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_cluster_filtering", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002355.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "change_parent", "tests": "import unittest\n\nclass Test_change_parent(unittest.TestCase):\n def test_change_parent(self):\n self.item1.change_parent(self.item2)\n self.assertEqual(self.item1.parentItem, self.item2)\n self.assertIn(self.item1, self.item2.childItems)\n\n def test_change_parent_none(self):\n self.item1.change_parent(None)\n self.assertEqual(self.item1.parentItem, None)\n self.assertListEqual([], self.item2.childItems)\n", "method_code": " def change_parent(self, parent: Optional['TreeItem']=None) -> None:\n \"\"\"\n Function replaces the item parent.\n \n Parameters\n ----------\n parent\n Parent which is set as an items parent\n \"\"\"\n self.parentItem = parent\n if parent is not None:\n parent.append_child(self)\n ", "context": "class TreeItem(object):\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def append_child(self, item: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def remove_children(self, position: int, count: int) -> bool: ...\n def children_count(self) -> int: ...\n def row(self) -> int: ...\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def get_data_rows(self) -> List[RowInstance]: ...\n def count_marker_genes(self) -> int: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_change_parent", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002356.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "append_child", "tests": "import unittest\n\nclass Test_append_child(unittest.TestCase):\n def test_append_child(self):\n self.item1.append_child(self.item3)\n self.assertIn(self.item3, self.item1.childItems)\n", "method_code": " def append_child(self, item: 'TreeItem') -> None:\n \"\"\"\n This function appends child to self. This function just append a child\n and do not set parent of child item (it is set by function calling this function.\n \n Parameters\n ----------\n item\n Child item.\n \"\"\"\n self.childItems.append(item)\n ", "context": "class TreeItem(object):\n def append_child(self, item: 'TreeItem') -> None: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def remove_children(self, position: int, count: int) -> bool: ...\n def children_count(self) -> int: ...\n def row(self) -> int: ...\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def get_data_rows(self) -> List[RowInstance]: ...\n def count_marker_genes(self) -> int: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_append_child", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002357.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "remove_children", "tests": "import unittest\n\nclass Test_remove_children(unittest.TestCase):\n def test_remove_children(self):\n TreeItem.change_parents([self.item1, self.item2], self.item3)\n self.assertListEqual([self.item1, self.item2], self.item3.childItems)\n s = self.item3.remove_children(-1, 1)\n self.assertFalse(s)\n self.assertListEqual([self.item1, self.item2], self.item3.childItems)\n s = self.item3.remove_children(2, 1)\n self.assertFalse(s)\n self.assertListEqual([self.item1, self.item2], self.item3.childItems)\n s = self.item3.remove_children(1, 2)\n self.assertFalse(s)\n self.assertListEqual([self.item1, self.item2], self.item3.childItems)\n s = self.item3.remove_children(0, 1)\n self.assertTrue(s)\n self.assertListEqual([self.item2], self.item3.childItems)\n s = self.item3.remove_children(0, 1)\n self.assertTrue(s)\n self.assertListEqual([], self.item3.childItems)\n s = self.item3.remove_children(0, 1)\n self.assertFalse(s)\n self.assertListEqual([], self.item3.childItems)\n TreeItem.change_parents([self.item1, self.item2], self.item3)\n s = self.item3.remove_children(0, 2)\n self.assertTrue(s)\n self.assertListEqual([], self.item3.childItems)\n", "method_code": " def remove_children(self, position: int, count: int) -> bool:\n \"\"\"\n This function removes children form position to position + count\n \n Parameters\n ----------\n position\n Position of the first removed child\n count\n Number of removed children\n Returns\n -------\n Success of removing\n \"\"\"\n if position < 0 or position + count > len(self.childItems):\n return False\n for i in range(position + count - 1, position - 1, -1):\n self.childItems.pop(i)\n return True\n ", "context": "class TreeItem(object):\n def remove_children(self, position: int, count: int) -> bool: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def append_child(self, item: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def children_count(self) -> int: ...\n def row(self) -> int: ...\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def get_data_rows(self) -> List[RowInstance]: ...\n def count_marker_genes(self) -> int: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_remove_children", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002358.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "children_count", "tests": "import unittest\n\nclass Test_children_count(unittest.TestCase):\n def test_children_count(self):\n self.assertEqual(0, self.item3.children_count())\n TreeItem.change_parents([self.item1, self.item2], self.item3)\n self.assertEqual(2, self.item3.children_count())\n self.item3.remove_children(0, 1)\n self.assertEqual(1, self.item3.children_count())\n self.item3.remove_children(0, 1)\n self.assertEqual(0, self.item3.children_count())\n", "method_code": " def children_count(self) -> int:\n \"\"\"\n Function return number fo children of an item.\n \n Returns\n -------\n Number of children.\n \"\"\"\n return len(self.childItems)\n ", "context": "class TreeItem(object):\n def children_count(self) -> int: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def append_child(self, item: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def remove_children(self, position: int, count: int) -> bool: ...\n def row(self) -> int: ...\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def get_data_rows(self) -> List[RowInstance]: ...\n def count_marker_genes(self) -> int: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_children_count", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002359.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "row", "tests": "import unittest\n\nclass Test_row(unittest.TestCase):\n def test_row(self):\n self.assertEqual(0, self.item1.row())\n self.assertEqual(0, self.item2.row())\n self.assertEqual(0, self.item3.row())\n TreeItem.change_parents([self.item1, self.item2], self.item3)\n self.assertEqual(0, self.item1.row())\n self.assertEqual(1, self.item2.row())\n self.assertEqual(0, self.item3.row())\n self.item3.remove_children(0, 2)\n TreeItem.change_parents([self.item2, self.item1], self.item3)\n self.assertEqual(1, self.item1.row())\n self.assertEqual(0, self.item2.row())\n self.assertEqual(0, self.item3.row())\n", "method_code": " def row(self) -> int:\n \"\"\"\n Function returns the index of the item in a parents list. If it does not have parent returns 0.\n \n Returns\n -------\n The index of an item.\n \"\"\"\n if self.parentItem:\n return self.parentItem.childItems.index(self)\n return 0\n ", "context": "class TreeItem(object):\n def row(self) -> int: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def append_child(self, item: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def remove_children(self, position: int, count: int) -> bool: ...\n def children_count(self) -> int: ...\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def get_data_rows(self) -> List[RowInstance]: ...\n def count_marker_genes(self) -> int: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_row", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002360.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "child_from_name_index", "tests": "import unittest\n\nclass Test_child_from_name_index(unittest.TestCase):\n def test_child_from_name_index(self):\n self.assertTupleEqual((None, None), self.item3.child_from_name_index('item 1'))\n TreeItem.change_parents([self.item1, self.item2], self.item3)\n self.assertTupleEqual((0, self.item1), self.item3.child_from_name_index('item 1'))\n self.assertTupleEqual((1, self.item2), self.item3.child_from_name_index('item 2'))\n self.item3.remove_children(0, 2)\n TreeItem.change_parents([self.item2, self.item1], self.item3)\n self.assertTupleEqual((1, self.item1), self.item3.child_from_name_index('item 1'))\n self.assertTupleEqual((0, self.item2), self.item3.child_from_name_index('item 2'))\n", "method_code": " def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]:\n \"\"\"\n This function returns the index (in the array of children) and item with the name specified.\n \n Parameters\n ----------\n name\n The name of requested item.\n \n Returns\n -------\n The index and the searched item. If it does not exist return None.\n \"\"\"\n for i, c in enumerate(self.childItems):\n if c.name == name:\n return (i, c)\n return (None, None)\n ", "context": "class TreeItem(object):\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def append_child(self, item: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def remove_children(self, position: int, count: int) -> bool: ...\n def children_count(self) -> int: ...\n def row(self) -> int: ...\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def get_data_rows(self) -> List[RowInstance]: ...\n def count_marker_genes(self) -> int: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_child_from_name_index", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002361.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "contains_text", "tests": "import unittest\n\nclass Test_contains_text(unittest.TestCase):\n def test_contains_text(self):\n self.item1.data_row = {'Name': 'item1', 'Cell Type': 'type1', 'Function': 'function1'}\n self.item2.data_row = {'Name': 'item2', 'Cell Type': 'type2', 'Function': 'function2'}\n filter_columns = ['Name', 'Cell Type', 'Function']\n TreeItem.change_parents([self.item2, self.item1], self.item3)\n self.assertTrue(self.item1.contains_text('item1', filter_columns))\n self.assertFalse(self.item2.contains_text('item1', filter_columns))\n self.assertFalse(self.item3.contains_text('item1', filter_columns))\n self.assertTrue(self.item1.contains_text('type1', filter_columns))\n self.assertFalse(self.item2.contains_text('type1', filter_columns))\n self.assertFalse(self.item3.contains_text('type1', filter_columns))\n self.assertTrue(self.item1.contains_text('function1', filter_columns))\n self.assertFalse(self.item2.contains_text('function1', filter_columns))\n self.assertFalse(self.item3.contains_text('function1', filter_columns))\n self.assertFalse(self.item1.contains_text('item2', filter_columns))\n self.assertTrue(self.item2.contains_text('item2', filter_columns))\n self.assertFalse(self.item3.contains_text('item2', filter_columns))\n self.assertFalse(self.item1.contains_text('type2', filter_columns))\n self.assertTrue(self.item2.contains_text('type2', filter_columns))\n self.assertFalse(self.item3.contains_text('type2', filter_columns))\n self.assertFalse(self.item1.contains_text('function2', filter_columns))\n self.assertTrue(self.item2.contains_text('function2', filter_columns))\n self.assertFalse(self.item3.contains_text('function2', filter_columns))\n self.assertTrue(self.item1.contains_text('Item1', filter_columns))\n self.assertFalse(self.item2.contains_text('Item1', filter_columns))\n self.assertTrue(self.item1.contains_text('Type1', filter_columns))\n self.assertFalse(self.item2.contains_text('Type1', filter_columns))\n self.assertFalse(self.item1.contains_text('Item2', filter_columns))\n self.assertTrue(self.item2.contains_text('Item2', filter_columns))\n self.assertFalse(self.item1.contains_text('Type2', filter_columns))\n self.assertTrue(self.item2.contains_text('Type2', filter_columns))\n", "method_code": " def contains_text(self, text: str, filter_columns: List[str]) -> bool:\n \"\"\"\n Function indicates whether the text is present in any of columns in FILTER_COLUMNS.\n \n Parameters\n ----------\n text\n Tested text.\n filter_columns\n Columns used in filtering\n \n Returns\n -------\n Boolean that indicates that text is present in the item.\n \"\"\"\n if self.data_row is not None:\n return any((text.lower() in str(self.data_row[col]).lower() for col in filter_columns))\n else:\n return False\n ", "context": "class TreeItem(object):\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def append_child(self, item: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def remove_children(self, position: int, count: int) -> bool: ...\n def children_count(self) -> int: ...\n def row(self) -> int: ...\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def get_data_rows(self) -> List[RowInstance]: ...\n def count_marker_genes(self) -> int: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_contains_text", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002362.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "get_data_rows", "tests": "import unittest\n\nclass Test_get_data_rows(unittest.TestCase):\n def test_get_data_rows(self):\n TreeItem.change_parents([self.item2, self.item1], self.item3)\n self.item1.data_row = 'dr1'\n self.item2.data_row = 'dr2'\n self.item3.data_row = 'dr3'\n self.assertListEqual(sorted(['dr1', 'dr2', 'dr3']), sorted(self.item3.get_data_rows()))\n self.assertListEqual(['dr1'], self.item1.get_data_rows())\n self.assertListEqual(['dr2'], self.item2.get_data_rows())\n self.item1.data_row = 'dr1'\n self.item2.data_row = 'dr2'\n self.item3.data_row = None\n self.assertListEqual(sorted(['dr1', 'dr2']), sorted(self.item3.get_data_rows()))\n self.assertListEqual(['dr1'], self.item1.get_data_rows())\n self.assertListEqual(['dr2'], self.item2.get_data_rows())\n self.item1.data_row = 'dr1'\n self.item2.data_row = None\n self.item3.data_row = None\n self.assertListEqual(['dr1'], self.item3.get_data_rows())\n self.assertListEqual(['dr1'], self.item1.get_data_rows())\n self.assertListEqual([], self.item2.get_data_rows())\n", "method_code": " def get_data_rows(self) -> List[RowInstance]:\n \"\"\"\n This function returns a list of rows present in self and any children node.\n \n Returns\n -------\n Rows with data items.\n \"\"\"\n rows = [self.data_row] if self.data_row is not None else []\n for c in self.childItems:\n rows += c.get_data_rows()\n return rows\n ", "context": "class TreeItem(object):\n def get_data_rows(self) -> List[RowInstance]: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def append_child(self, item: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def remove_children(self, position: int, count: int) -> bool: ...\n def children_count(self) -> int: ...\n def row(self) -> int: ...\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def count_marker_genes(self) -> int: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_get_data_rows", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002363.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "count_marker_genes", "tests": "import unittest\n\nclass Test_count_marker_genes(unittest.TestCase):\n def test_count_marker_genes(self):\n TreeItem.change_parents([self.item2, self.item1], self.item3)\n self.item1.data_row = 'dr1'\n self.item2.data_row = 'dr2'\n self.item3.data_row = 'dr3'\n self.assertEqual(3, self.item3.count_marker_genes())\n self.assertEqual(1, self.item1.count_marker_genes())\n self.assertEqual(1, self.item2.count_marker_genes())\n self.item1.data_row = 'dr1'\n self.item2.data_row = 'dr2'\n self.item3.data_row = None\n self.assertEqual(2, self.item3.count_marker_genes())\n self.assertEqual(1, self.item1.count_marker_genes())\n self.assertEqual(1, self.item2.count_marker_genes())\n self.item1.data_row = 'dr1'\n self.item2.data_row = None\n self.item3.data_row = None\n self.assertEqual(1, self.item3.count_marker_genes())\n self.assertEqual(1, self.item1.count_marker_genes())\n self.assertEqual(0, self.item2.count_marker_genes())\n", "method_code": " def count_marker_genes(self) -> int:\n \"\"\"\n This function counts number of marker genes in its tree\n \n Returns\n -------\n int\n Number of marker genes in the tree including itself.\n \"\"\"\n return sum((c.count_marker_genes() for c in self.childItems)) + (0 if self.data_row is None else 1)\n ", "context": "class TreeItem(object):\n def count_marker_genes(self) -> int: ...\n def __init__(self, name: str, is_type_item: bool, data_row: Optional[RowInstance], parent: Optional['TreeItem']=None): ...\n def change_parent(self, parent: Optional['TreeItem']=None) -> None: ...\n def change_parents(items: Iterable['TreeItem'], parent: 'TreeItem') -> None: ...\n def append_child(self, item: 'TreeItem') -> None: ...\n def child(self, row: int) -> 'TreeItem': ...\n def remove_children(self, position: int, count: int) -> bool: ...\n def children_count(self) -> int: ...\n def row(self) -> int: ...\n def child_from_name_index(self, name: str) -> Tuple[Optional[int], Optional['TreeItem']]: ...\n def contains_text(self, text: str, filter_columns: List[str]) -> bool: ...\n def get_data_rows(self) -> List[RowInstance]: ...\n\n self.expanded = False\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_count_marker_genes", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002364.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWMarkerGenes.py", "focal_class": null, "focal_method": "expand_in_other_view", "tests": "import unittest\n\nclass Test_expand_in_other_view(unittest.TestCase):\n def test_extend_collapse_both_views(self):\n \"\"\"\n Test whether the item extends in the other column when extended in one.\n \"\"\"\n src_view = self.widget.available_markers_view\n dest_view = self.widget.selected_markers_view\n index = src_view.model().index(0, 0)\n src_view.expand_in_other_view(index, is_expanded=True)\n tree_node = src_view.model().sourceModel().node_from_index(src_view.model().mapToSource(index))\n self.assertTrue(tree_node.expanded)\n self.move_first_child(src_view)\n index_left = src_view.model().index(0, 0)\n index_right = dest_view.model().index(0, 0)\n tree_node_left = src_view.model().sourceModel().node_from_index(src_view.model().mapToSource(index_left))\n tree_node_right = dest_view.model().sourceModel().node_from_index(dest_view.model().mapToSource(index_right))\n src_view.expand_in_other_view(index_left, is_expanded=True)\n self.assertTrue(tree_node_left.expanded)\n self.assertTrue(tree_node_right.expanded)\n self.assertTrue(dest_view.isExpanded(index_right))\n src_view.expand_in_other_view(index_left, is_expanded=False)\n self.assertFalse(tree_node_left.expanded)\n self.assertFalse(tree_node_right.expanded)\n self.assertFalse(dest_view.isExpanded(index_right))\n dest_view.expand_in_other_view(index_right, is_expanded=True)\n self.assertTrue(tree_node_left.expanded)\n self.assertTrue(tree_node_right.expanded)\n self.assertTrue(src_view.isExpanded(index_left))\n dest_view.expand_in_other_view(index_right, is_expanded=False)\n self.assertFalse(tree_node_left.expanded)\n self.assertFalse(tree_node_right.expanded)\n self.assertFalse(dest_view.isExpanded(index_left))\n", "method_code": " def expand_in_other_view(self, clicked_index: QModelIndex, is_expanded: bool) -> None:\n \"\"\"\n Expand/collapse item which is same to the clicked_index in the other view. The other view is one of the left\n if click happened on the right and vice versa.\n \n Parameters\n ----------\n clicked_index\n Index of the item that was expanded/collapsed\n is_expanded\n This flag is true if the item was expanded otherwise if false (collapsed).\n \"\"\"\n source_model_this = self.model().sourceModel()\n source_model_other = self.otherView.model().sourceModel()\n clicked_model_index = self.model().mapToSource(clicked_index)\n source_model_this.set_expanded(clicked_model_index, is_expanded)\n clicked_name = source_model_this.node_from_index(clicked_model_index).name\n index_other = source_model_other.index_from_name(clicked_name, source_model_other.rootItem)\n if index_other is not None:\n self.otherView.setExpanded(index_other, is_expanded)\n ", "context": "class TreeView(QTreeView):\n def expand_in_other_view(self, clicked_index: QModelIndex, is_expanded: bool) -> None: ...\n def __init__(self, *args, **kwargs) -> None: ...\n def mousePressEvent(self, e: QtGui.QMouseEvent) -> None: ...\n def mouseDoubleClickEvent(self, e: QtGui.QMouseEvent) -> None: ...\n def handle_expand(self, e: QtGui.QMouseEvent) -> None: ...\n def setModel(self, model: QtCore.QAbstractItemModel) -> None: ...\n def setExpanded(self, index: QModelIndex, expand: bool) -> None: ...\n\n self.otherView = None\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_extend_collapse_both_views", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002365.py"} {"focal_file": "orangecontrib/bioinformatics/widgets/OWDifferentialExpression.py", "focal_class": null, "focal_method": "f_oneway", "tests": "import unittest\n\nclass Test_f_oneway(unittest.TestCase):\n def test_f_oneway(self):\n g1 = np.array([0.1, -0.1, 0.2, -0.2])\n g2 = g1 + 1\n g3 = g1\n f1, p1 = scipy.stats.f_oneway(g1, g2)\n f, p = f_oneway(g1, g2)\n np.testing.assert_almost_equal([f, p], [f1, p1])\n f, p = f_oneway(np.c_[g1], np.c_[g2], axis=0)\n np.testing.assert_almost_equal([f[0], p[0]], [f1, p1])\n f1, p1 = scipy.stats.f_oneway(g1, g2, g3)\n f, p = f_oneway(g1, g2, g3)\n np.testing.assert_almost_equal([f, p], [f1, p1])\n g1 = np.random.normal(size=(10, 30))\n g2 = np.random.normal(loc=1, size=(10, 20))\n g3 = np.random.normal(loc=2, size=(10, 10))\n f, p = f_oneway(g1, g2, g3, axis=1)\n self.assertEqual(f.shape, (10,))\n self.assertEqual(p.shape, (10,))\n fp1 = [scipy.stats.f_oneway(g1, g2, g3) for g1, g2, g3 in zip(g1, g2, g3)]\n f1 = [f for f, _ in fp1]\n p1 = [p for _, p in fp1]\n np.testing.assert_almost_equal(f1, f)\n np.testing.assert_almost_equal(p1, p)\n f, p = f_oneway(g1.T, g2.T, g3.T, axis=0)\n np.testing.assert_almost_equal(f1, f)\n np.testing.assert_almost_equal(p1, p)\n", "method_code": "def f_oneway(*arrays, **kwargs):\n \"\"\"\n Perform a 1-way ANOVA\n\n Like `scipy.stats.f_oneway` but accept 2D arrays, with `axis`\n specifying over which axis to operate (in which axis the samples\n are stored).\n\n Parameters\n ----------\n A1, A2, ... : array_like\n The samples for each group.\n axis : int\n The axis which contain the samples.\n\n Returns\n -------\n F : array\n F scores\n P : array\n P values\n\n See also\n --------\n scipy.stats.f_oneway\n \"\"\"\n axis = kwargs.get('axis', 0)\n arrays = [np.asarray(a, dtype=float) for a in arrays]\n alldata = np.concatenate(arrays, axis)\n bign = alldata.shape[axis]\n sstot = np.sum(alldata ** 2, axis) - np.sum(alldata, axis) ** 2 / bign\n ssarrays = [np.sum(a, axis, keepdims=True) ** 2 / a.shape[axis] for a in arrays]\n ssbn = np.sum(np.concatenate(ssarrays, axis), axis)\n ssbn -= np.sum(alldata, axis) ** 2 / bign\n assert sstot.shape == ssbn.shape\n sswn = sstot - ssbn\n dfbn = len(arrays) - 1\n dfwn = bign - len(arrays)\n msb = ssbn / dfbn\n msw = sswn / dfwn\n f = msb / msw\n prob = scipy.special.fdtrc(dfbn, dfwn, f)\n return (f, prob)", "context": "def f_oneway(*arrays, **kwargs): ...\ndef score_fold_change(a, b, **kwargs): ...\ndef score_log_fold_change(a, b, **kwargs): ...\ndef score_ttest(a, b, **kwargs): ...\ndef score_ttest_t(a, b, **kwargs): ...\ndef score_ttest_p(a, b, **kwargs): ...\ndef score_anova(*arrays, **kwargs): ...\ndef score_anova_(*arrays, **kwargs): ...\ndef f_oneway(*arrays, **kwargs): ...\ndef score_anova_f(*arrays, **kwargs): ...\ndef score_anova_p(*arrays, **kwargs): ...\ndef score_signal_to_noise(a, b, **kwargs): ...\ndef score_mann_whitney(a, b, **kwargs): ...\ndef score_mann_whitney_u(a, b, **kwargs): ...\ndef hypergeometric_test_score(*args, **kwargs): ...\ndef histogram_cut(hist, bins, low, high): ...\ndef test_low(array, low, high): ...\ndef test_high(array, low, high): ...\ndef test_two_tail(array, low, high): ...\ndef test_middle(array, low, high): ...\ndef copy_variable(var): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_f_oneway", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002366.py"} {"focal_file": "orangecontrib/bioinformatics/kegg/entry/parser.py", "focal_class": "orangecontrib.bioinformatics.kegg.entry.parser.DBGETEntryParser", "focal_method": "parse", "tests": "import unittest\n\nclass Test_orangecontrib_bioinformatics_kegg_entry_parser_DBGETEntryParser_parse(unittest.TestCase):\n def test_parser(self):\n parse = parser.DBGETEntryParser()\n stream = StringIO(TEST_ENTRY)\n expected = [(parse.ENTRY_START, None, None), (parse.SECTION_START, 'ENTRY', 'test_id something else\\n'), (parse.SECTION_END, 'ENTRY', None), (parse.SECTION_START, 'NAME', 'test\\n'), (parse.SECTION_END, 'NAME', None), (parse.SECTION_START, 'DESCRIPTION', \"This is a test's description.\\n\"), (parse.TEXT, None, 'It spans\\n'), (parse.TEXT, None, 'multiple lines\\n'), (parse.SUBSECTION_START, 'SUB', \"This is a description's sub\\n\"), (parse.TEXT, None, 'section\\n'), (parse.SUBSECTION_END, 'SUB', None), (parse.SECTION_END, 'DESCRIPTION', None), (parse.ENTRY_END, None, None)]\n self.assertSequenceEqual(list(parse.parse(stream)), expected)\n", "method_code": " def parse(self, stream):\n entry_offset = None\n section_title = None\n subsection_title = None\n textline_start = None\n for line in stream:\n startswith = line.startswith\n if startswith('ENTRY'):\n yield (self.ENTRY_START, None, None)\n title, rest = self._partition_section_title(line)\n entry_offset = len(line) - len(rest)\n textline_start = ' ' * entry_offset\n yield (self.SECTION_START, title, rest)\n yield (self.SECTION_END, title, None)\n elif startswith('///'):\n if subsection_title is not None:\n yield (self.SUBSECTION_END, subsection_title, None)\n subsection_title = None\n if section_title is not None:\n yield (self.SECTION_END, section_title, None)\n section_title = None\n yield (self.ENTRY_END, None, None)\n entry_offset = None\n textline_start = None\n elif not startswith(' '):\n if subsection_title is not None:\n yield (self.SUBSECTION_END, subsection_title, None)\n subsection_title = None\n if section_title is not None:\n yield (self.SECTION_END, section_title, None)\n section_title = None\n title, rest = self._partition_section_title(line)\n section_title = title\n yield (self.SECTION_START, section_title, rest)\n elif startswith(textline_start):\n yield (self.TEXT, None, line[entry_offset:])\n elif startswith(' '):\n if subsection_title is not None:\n yield (self.SUBSECTION_END, subsection_title, None)\n title, rest = self._partition_subsection_title(line)\n subsection_title = title\n yield (self.SUBSECTION_START, subsection_title, rest)\n if subsection_title is not None:\n yield (self.SUBSECTION_END, subsection_title, None)\n if section_title is not None:\n yield (self.SECTION_END, section_title, None)\n if entry_offset is not None:\n yield (self.ENTRY_END, None, None)\n ", "context": "class DBGETEntryParser(object):\n def parse(self, stream): ...\n def __init__(self): ...\n def parse_string(self, string): ...\n def _partition_section_title(self, line): ...\n def _partition_subsection_title(self, line): ...\n\n ENTRY_START = 0\n ENTRY_END = 1\n SECTION_START = 2\n SECTION_END = 3\n SUBSECTION_START = 4\n SUBSECTION_END = 5\n TEXT = 6\n EVENTS = ['ENTRY_START', 'ENTRY_END', 'SECTION_START', 'SECTION_END', 'SUBSECTION_START', 'SUBSECTION_END', 'TEXT']\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_parser", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002367.py"} {"focal_file": "orangecontrib/bioinformatics/kegg/databases.py", "focal_class": "orangecontrib.bioinformatics.kegg.databases.Genome", "focal_method": "keys", "tests": "import unittest\n\nclass Test_orangecontrib_bioinformatics_kegg_databases_Genome_keys(unittest.TestCase):\n def test_genome(self):\n genome = databases.Genome()\n entry_keys = list(genome.keys())\n for key in entry_keys[:3] + entry_keys[-3:]:\n self.assertTrue(key in genome)\n self.assertTrue(key in genome)\n entry = genome[key]\n self.assertEqual(entry.entry_key, key)\n self.assertIsInstance(entry, genome.ENTRY_TYPE)\n self.assertIsInstance(entry.name, six.string_types)\n self.assertIsInstance(entry.taxid, six.string_types)\n self.assertTrue(genome.search('homo sapiens')[0] == 'hsa')\n entry = genome['hsa']\n self.assertEqual(entry.taxid, '9606')\n", "method_code": "def keys(self):\n \"\"\"\n Return an iterator over all database keys. These are unique\n KEGG identifiers that can be used to query the database.\n \"\"\"\n return iter(self._keys)", "context": "def keys(self): ...\ndef iter_take(source_iter, n): ...\ndef batch_iter(source_iter, n): ...\ndef chain_iter(chains_iter): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_genome", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002368.py"} {"focal_file": "orangecontrib/bioinformatics/kegg/databases.py", "focal_class": null, "focal_method": "batch_iter", "tests": "import unittest\n\nclass Test_batch_iter(unittest.TestCase):\n def test_batch_iter(self):\n iter = range(25)\n expected = [list(range(10)), list(range(10, 20)), list(range(20, 25))]\n for exp, batch in zip(expected, databases.batch_iter(iter, 10)):\n self.assertEqual(exp, batch)\n", "method_code": "def batch_iter(source_iter, n):\n \"\"\"\n Split the `source_iter` into batches of size `n`.\n \"\"\"\n source_iter = iter(source_iter)\n while True:\n batch = iter_take(source_iter, n)\n if batch:\n yield batch\n else:\n break", "context": "def batch_iter(source_iter, n): ...\ndef iter_take(source_iter, n): ...\ndef batch_iter(source_iter, n): ...\ndef chain_iter(chains_iter): ...\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_batch_iter", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002369.py"} {"focal_file": "orangecontrib/bioinformatics/ncbi/gene/__init__.py", "focal_class": "Gene", "focal_method": "load_attributes", "tests": "import unittest\n\nclass Test_Gene_load_attributes(unittest.TestCase):\n def test_load_attributes(self):\n g = Gene()\n g.load_attributes(('Human', '9606', '920', 'CD4'), attributes=('species', 'tax_id', 'gene_id', 'symbol'))\n self.assertEqual(g.species, 'Human')\n self.assertEqual(g.tax_id, '9606')\n self.assertEqual(g.gene_id, '920')\n self.assertEqual(g.symbol, 'CD4')\n self.assertEqual(str(g), '')\n self.assertIsNone(g.input_identifier)\n self.assertIsNone(g.synonyms)\n", "method_code": " def load_attributes(self, values: Tuple[str, ...], attributes: Tuple[str, ...]=gene_info_attributes):\n for attr, val in zip(attributes, values):\n setattr(self, attr, json.loads(val) if attr in ('synonyms', 'db_refs', 'homologs') else val)\n ", "context": "class Gene():\n def load_attributes(self, values: Tuple[str, ...], attributes: Tuple[str, ...]=gene_info_attributes): ...\n def __init__(self, input_identifier: Optional[str]=None): ...\n def __getattr__(self, attribute): ...\n def __repr__(self): ...\n def homolog_gene(self, taxonomy_id: str) -> Optional[str]: ...\n\n self.input_identifier = input_identifier\n\n __slots__ = gene_info_attributes + ('input_identifier',)\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_load_attributes", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002370.py"} {"focal_file": "orangecontrib/bioinformatics/ncbi/gene/__init__.py", "focal_class": "GeneMatcher", "focal_method": "homolog_gene", "tests": "import unittest\n\nclass Test_GeneMatcher_homolog_gene(unittest.TestCase):\n def test_homologs(self):\n gm = GeneMatcher('9606')\n gm.genes = ['920']\n g = gm.genes[0]\n self.assertIsNotNone(g.homologs)\n self.assertTrue(len(g.homologs))\n self.assertIn('10090', g.homologs)\n self.assertEqual(g.homology_group_id, '513')\n self.assertEqual(g.homolog_gene('10090'), '12504')\n self.assertIsNone(g.homolog_gene('Unknown_taxonomy'))\n", "method_code": " def homolog_gene(self, taxonomy_id: str) -> Optional[str]:\n \"\"\"Returns gene homolog for given organism.\n \n Parameters\n ----------\n taxonomy_id: str\n Taxonomy id of target organism.\n \n Returns\n -------\n str\n Entrez ID (if available).\n \"\"\"\n return self.homologs.get(taxonomy_id, None)\n ", "context": "class Gene():\n def homolog_gene(self, taxonomy_id: str) -> Optional[str]: ...\n def __init__(self, input_identifier: Optional[str]=None): ...\n def __getattr__(self, attribute): ...\n def __repr__(self): ...\n def load_attributes(self, values: Tuple[str, ...], attributes: Tuple[str, ...]=gene_info_attributes): ...\n\n self.input_identifier = input_identifier\n\n __slots__ = gene_info_attributes + ('input_identifier',)\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_homologs", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002371.py"} {"focal_file": "orangecontrib/bioinformatics/ncbi/gene/__init__.py", "focal_class": "GeneMatcher", "focal_method": "match_table_column", "tests": "import unittest\n\nclass Test_GeneMatcher_match_table_column(unittest.TestCase):\n def test_match_table_column(self):\n gm = GeneMatcher('4932')\n data = gm.match_table_column(Table('brown-selected.tab'), 'gene')\n self.assertTrue(ENTREZ_ID in data.domain)\n", "method_code": " def match_table_column(self, data_table: Table, column_name: str, target_column: Optional[StringVariable]=None) -> Table:\n \"\"\"Helper function for gene name matching with :class:`Orange.data.Table`.\n \n Give a column of genes, GeneMatcher will try to map genes to their\n corresponding Entrez Ids.\n \n \n Parameters\n ----------\n data_table: :class:`Orange.data.Table`\n Data table\n \n column_name: str\n Name of the column where gene symbols are located\n \n target_column: :class:`StringVariable`\n Column where we store Entrez Ids.\n Defaults to StringVariable(ncbi.gene.config.NCBI_ID)\n \n Returns\n -------\n :class:`Orange.data.Table`\n Data table with a column of Gene Ids\n \"\"\"\n if column_name in data_table.domain:\n self.genes = data_table.get_column_view(column_name)[0]\n if target_column is None:\n target_column = StringVariable(ENTREZ_ID)\n new_domain = Domain(data_table.domain.attributes, data_table.domain.class_vars, data_table.domain.metas + (target_column,))\n new_data = data_table.transform(new_domain)\n new_data[:, target_column] = [[str(gene.gene_id) if gene.gene_id else '?'] for gene in self.genes]\n return new_data\n ", "context": "class GeneMatcher():\n def match_table_column(self, data_table: Table, column_name: str, target_column: Optional[StringVariable]=None) -> Table: ...\n def __init__(self, tax_id: str, progress_callback=None, auto_start=True): ...\n def tax_id(self): ...\n def tax_id(self, tax_id: str) -> None: ...\n def genes(self) -> List[Gene]: ...\n def genes(self, genes: List[str]) -> None: ...\n def get_known_genes(self) -> List[Gene]: ...\n def to_data_table(self, selected_genes: Optional[List[str]]=None) -> Table: ...\n def match_table_attributes(self, data_table, run=True, rename=False, source_name='Source ID') -> Table: ...\n def match_genes(self): ...\n def _gene_db_path(self): ...\n def _match(self): ...\n\n self._progress_callback = progress_callback\n self._auto_start = auto_start\n self.gene_db_path = self._gene_db_path()\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_match_table_column", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002372.py"} {"focal_file": "orangecontrib/bioinformatics/ncbi/gene/__init__.py", "focal_class": "GeneMatcher", "focal_method": "match_table_attributes", "tests": "import unittest\n\nclass Test_GeneMatcher_match_table_attributes(unittest.TestCase):\n def test_match_table_attributes(self):\n gm = GeneMatcher('4932')\n data = Table('brown-selected.tab')\n data = Table.transpose(data, feature_names_column='gene')\n data = gm.match_table_attributes(data, rename=True, source_name='FooBar')\n for column in data.domain.attributes:\n self.assertTrue(ENTREZ_ID in column.attributes)\n self.assertTrue('FooBar' in column.attributes)\n", "method_code": " def match_table_attributes(self, data_table, run=True, rename=False, source_name='Source ID') -> Table:\n \"\"\"Helper function for gene name matching with :class:`Orange.data.Table`.\n \n Match table attributes and if a unique match is found create a new column attribute\n for Entrez Id. Attribute name is defined here: `orangecontrib.bioinformatics.ncbi.gene.config.NCBI_ID`\n \n \n Parameters\n ----------\n data_table: :class:`Orange.data.Table`\n Data table\n \n Returns\n -------\n \n :class:`Orange.data.Table`\n Data table column attributes are populated with Entrez Ids\n \n \"\"\"\n if run:\n self.genes = [var.name for var in data_table.domain.attributes]\n \n def helper(gene, attribute):\n if gene.gene_id:\n if rename:\n attribute = attribute.renamed(gene.symbol)\n attribute.attributes[source_name] = gene.input_identifier\n attribute.attributes[ENTREZ_ID] = gene.gene_id\n return attribute\n attributes = [helper(gene, attr) for gene, attr in zip(self.genes, data_table.domain.attributes)]\n metas = data_table.domain.metas\n (attr_deduplicated, _, metas_deduplicated), renamed = get_unique_names_domain([a.name for a in attributes], metas=[m.name for m in metas])\n if len(renamed):\n attributes = [attr.renamed(new_name) for attr, new_name in zip(attributes, attr_deduplicated)]\n metas = [meta.renamed(new_name) for meta, new_name in zip(metas, metas_deduplicated)]\n domain = Domain(attributes, data_table.domain.class_vars, metas)\n return data_table.transform(domain)\n ", "context": "class GeneMatcher():\n def match_table_attributes(self, data_table, run=True, rename=False, source_name='Source ID') -> Table: ...\n def __init__(self, tax_id: str, progress_callback=None, auto_start=True): ...\n def tax_id(self): ...\n def tax_id(self, tax_id: str) -> None: ...\n def genes(self) -> List[Gene]: ...\n def genes(self, genes: List[str]) -> None: ...\n def get_known_genes(self) -> List[Gene]: ...\n def to_data_table(self, selected_genes: Optional[List[str]]=None) -> Table: ...\n def match_table_column(self, data_table: Table, column_name: str, target_column: Optional[StringVariable]=None) -> Table: ...\n def match_genes(self): ...\n def _gene_db_path(self): ...\n def _match(self): ...\n\n self._progress_callback = progress_callback\n self._auto_start = auto_start\n self.gene_db_path = self._gene_db_path()\n", "repository": "biolab/orange3-bioinformatics", "test_name": "test_match_table_attributes", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002373.py"} {"focal_file": "dicetables_db/insertandretrieve.py", "focal_class": null, "focal_method": "has_required_index", "tests": "import unittest\n\nclass Test_has_required_index(unittest.TestCase):\n def test_has_required_index_true(self):\n self.assertTrue(self.interface.has_required_index())\n\n def test_has_required_index_false(self):\n self.connection.reset_collection()\n self.assertFalse(self.interface.has_required_index())\n\n def test_reset_creates_index(self):\n self.connection.reset_collection()\n self.interface.reset()\n self.assertTrue(self.interface.has_required_index())\n", "method_code": " def has_required_index(self) -> bool:\n return self._conn.has_index(('group', 'score'))\n ", "context": "class DiceTableInsertionAndRetrieval(object):\n def has_required_index(self) -> bool: ...\n def __init__(self, connection: BaseConnection) -> None: ...\n def connection_info(self) -> dict: ...\n def _create_required_index(self): ...\n def reset(self): ...\n def has_table(self, dice_table: DiceTable) -> bool: ...\n def add_table(self, dice_table: DiceTable) -> DocumentId: ...\n def find_nearest_table(self, dice_list: list) -> Optional[DocumentId]: ...\n def get_table(self, doc_id: DocumentId) -> DiceTable: ...\n\n self._conn = connection\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_has_required_index_true", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002374.py"} {"focal_file": "dicetables_db/insertandretrieve.py", "focal_class": null, "focal_method": "has_table", "tests": "import unittest\n\nclass Test_has_table(unittest.TestCase):\n def test_has_table_true(self):\n self.interface.add_table(dt.DiceTable.new().add_die(dt.Die(3)))\n self.assertTrue(self.interface.has_table(dt.DiceTable.new().add_die(dt.Die(3))))\n", "method_code": " def has_table(self, dice_table: DiceTable) -> bool:\n if dice_table.dice_data() == DiceRecord.new():\n return False\n finder = Finder(self._conn, dice_table.get_list())\n return finder.get_exact_match() is not None\n ", "context": "class DiceTableInsertionAndRetrieval(object):\n def has_table(self, dice_table: DiceTable) -> bool: ...\n def __init__(self, connection: BaseConnection) -> None: ...\n def connection_info(self) -> dict: ...\n def has_required_index(self) -> bool: ...\n def _create_required_index(self): ...\n def reset(self): ...\n def add_table(self, dice_table: DiceTable) -> DocumentId: ...\n def find_nearest_table(self, dice_list: list) -> Optional[DocumentId]: ...\n def get_table(self, doc_id: DocumentId) -> DiceTable: ...\n\n self._conn = connection\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_has_table_true", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002375.py"} {"focal_file": "dicetables_db/insertandretrieve.py", "focal_class": null, "focal_method": "find_nearest_table", "tests": "import unittest\n\nclass Test_find_nearest_table(unittest.TestCase):\n def test_find_nearest_table_no_match(self):\n dice_list = [(dt.Die(1), 1)]\n self.assertIsNone(self.interface.find_nearest_table(dice_list))\n\n def test_find_nearest_table_perfect_match_one_die(self):\n dice_table = dt.DiceTable.new().add_die(dt.Die(2))\n doc_id = self.interface.add_table(dice_table)\n self.assertEqual(self.interface.find_nearest_table(dice_table.get_list()), doc_id)\n\n def test_find_nearest_table_scores_same_group_same(self):\n dice_table0 = dt.DiceTable.new().add_die(dt.Die(2), 3).add_die(dt.Die(3)).add_die(dt.Die(4))\n dice_table1 = dt.DiceTable.new().add_die(dt.Die(2)).add_die(dt.Die(3)).add_die(dt.Die(4), 2)\n test_list1 = [(dt.Die(2), 1), (dt.Die(3), 2), (dt.Die(4), 10), (dt.Die(10), 100)]\n self.interface.add_table(dice_table0)\n dice_table1_id = self.interface.add_table(dice_table1)\n self.assertEqual(self.interface.find_nearest_table(test_list1), dice_table1_id)\n", "method_code": " def find_nearest_table(self, dice_list: list) -> Optional[DocumentId]:\n finder = Finder(self._conn, dice_list)\n doc_id = finder.get_exact_match()\n if doc_id is None:\n doc_id = finder.find_nearest_table()\n if doc_id is None:\n return None\n return doc_id\n ", "context": "class DiceTableInsertionAndRetrieval(object):\n def find_nearest_table(self, dice_list: list) -> Optional[DocumentId]: ...\n def __init__(self, connection: BaseConnection) -> None: ...\n def connection_info(self) -> dict: ...\n def has_required_index(self) -> bool: ...\n def _create_required_index(self): ...\n def reset(self): ...\n def has_table(self, dice_table: DiceTable) -> bool: ...\n def add_table(self, dice_table: DiceTable) -> DocumentId: ...\n def get_table(self, doc_id: DocumentId) -> DiceTable: ...\n\n self._conn = connection\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_find_nearest_table_no_match", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002376.py"} {"focal_file": "dicetables_db/insertandretrieve.py", "focal_class": null, "focal_method": "get_table", "tests": "import unittest\n\nclass Test_get_table(unittest.TestCase):\n def test_get_table(self):\n table = dt.DiceTable.new().add_die(dt.Die(2))\n doc_id = self.interface.add_table(table)\n new_table = self.interface.get_table(doc_id)\n self.assertEqual(new_table, table)\n", "method_code": " def get_table(self, doc_id: DocumentId) -> DiceTable:\n data = self._conn.find_one({'_id': doc_id}, {'serialized': True})\n return Serializer.deserialize(data['serialized'])\n ", "context": "class DiceTableInsertionAndRetrieval(object):\n def get_table(self, doc_id: DocumentId) -> DiceTable: ...\n def __init__(self, connection: BaseConnection) -> None: ...\n def connection_info(self) -> dict: ...\n def has_required_index(self) -> bool: ...\n def _create_required_index(self): ...\n def reset(self): ...\n def has_table(self, dice_table: DiceTable) -> bool: ...\n def add_table(self, dice_table: DiceTable) -> DocumentId: ...\n def find_nearest_table(self, dice_list: list) -> Optional[DocumentId]: ...\n\n self._conn = connection\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_get_table", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002377.py"} {"focal_file": "dicetables_db/insertandretrieve.py", "focal_class": "Finder", "focal_method": "get_exact_match", "tests": "import unittest\n\nclass Test_Finder_get_exact_match(unittest.TestCase):\n def test_Finder_get_exact_match_returns_None(self):\n finder = Finder(self.connection, [(dt.Die(2), 1)])\n self.assertIsNone(finder.get_exact_match())\n\n def test_Finder_get_exact_match_returns_correct_id(self):\n finder = Finder(self.connection, [(dt.Die(2), 1)])\n doc_id = self.interface.add_table(dt.DiceTable.new().add_die(dt.Die(2)))\n self.assertEqual(finder.get_exact_match(), doc_id)\n", "method_code": " def get_exact_match(self) -> Optional[DocumentId]:\n query_dict = self._get_query_dict_for_exact()\n doc_id_in_dict = self._conn.find_one(query_dict, {'_id': 1})\n if doc_id_in_dict is None:\n return None\n return doc_id_in_dict['_id']\n ", "context": "class Finder(object):\n def get_exact_match(self) -> Optional[DocumentId]: ...\n def __init__(self, connection: BaseConnection, dice_list: list) -> None: ...\n def _get_query_dict_for_exact(self): ...\n def find_nearest_table(self) -> Optional[DocumentId]: ...\n def _is_close_enough(self): ...\n def _get_list_of_candidates(self, group_dice_dict_list): ...\n def _get_query_dict_for_nearest(self, group, dice_dict): ...\n def _update_id_and_highest_score(self, score_id_dict): ...\n\n self._conn = connection\n self._param_maker = SearchParams(dice_list)\n self._param_score = self._param_maker.get_score()\n self._doc_id = None\n self._highest_found_score = 0\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_Finder_get_exact_match_returns_None", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002378.py"} {"focal_file": "dicetables_db/insertandretrieve.py", "focal_class": "Finder", "focal_method": "find_nearest_table", "tests": "import unittest\n\nclass Test_Finder_find_nearest_table(unittest.TestCase):\n def test_Finder_find_nearest_table_no_match(self):\n dice_list = [(dt.Die(1), 1)]\n finder = Finder(self.connection, dice_list)\n self.assertIsNone(finder.find_nearest_table())\n\n def test_Finder_find_nearest_table_perfect_match_one_die(self):\n dice_table = dt.DiceTable.new().add_die(dt.Die(2))\n doc_id = self.interface.add_table(dice_table)\n finder = Finder(self.connection, dice_table.get_list())\n self.assertEqual(finder.find_nearest_table(), doc_id)\n\n def test_Finder_find_nearest_table_perfect_match_multi_die(self):\n exact_match = dt.DiceTable.new().add_die(dt.Die(2)).add_die(dt.Die(3)).add_die(dt.Die(4))\n finder = Finder(self.connection, exact_match.get_list())\n same_score_not_it = dt.DiceTable.new().add_die(dt.Die(2), 2).add_die(dt.Die(3))\n self.interface.add_table(dt.DiceTable.new().add_die(dt.Die(2)))\n doc_id = self.interface.add_table(exact_match)\n self.interface.add_table(same_score_not_it)\n self.assertEqual(finder.find_nearest_table(), doc_id)\n\n def test_Finder_find_nearest_table_nearest_match_multi_die(self):\n dice_table0 = dt.DiceTable.new().add_die(dt.Die(2))\n dice_table1 = dt.DiceTable.new().add_die(dt.Die(2)).add_die(dt.Die(3)).add_die(dt.Die(4))\n test_list0 = dice_table0.add_die(dt.Die(10)).get_list()\n test_list1 = dice_table1.add_die(dt.Die(2)).get_list()\n finder0 = Finder(self.connection, test_list0)\n finder1 = Finder(self.connection, test_list1)\n dice_table0_id = self.interface.add_table(dice_table0)\n dice_table1_id = self.interface.add_table(dice_table1)\n self.assertEqual(finder0.find_nearest_table(), dice_table0_id)\n self.assertEqual(finder1.find_nearest_table(), dice_table1_id)\n\n def test_Finder_find_nearest_table_scores_same_group_same(self):\n dice_table0 = dt.DiceTable.new().add_die(dt.Die(2), 3).add_die(dt.Die(3)).add_die(dt.Die(4))\n dice_table1 = dt.DiceTable.new().add_die(dt.Die(2)).add_die(dt.Die(3)).add_die(dt.Die(4), 2)\n test_list1 = [(dt.Die(2), 1), (dt.Die(3), 2), (dt.Die(4), 10), (dt.Die(10), 100)]\n finder1 = Finder(self.connection, test_list1)\n self.interface.add_table(dice_table0)\n dice_table1_id = self.interface.add_table(dice_table1)\n self.assertEqual(finder1.find_nearest_table(), dice_table1_id)\n", "method_code": " def find_nearest_table(self, dice_list: list) -> Optional[DocumentId]:\n finder = Finder(self._conn, dice_list)\n doc_id = finder.get_exact_match()\n if doc_id is None:\n doc_id = finder.find_nearest_table()\n if doc_id is None:\n return None\n return doc_id\n ", "context": "class DiceTableInsertionAndRetrieval(object):\n def find_nearest_table(self, dice_list: list) -> Optional[DocumentId]: ...\n def __init__(self, connection: BaseConnection) -> None: ...\n def connection_info(self) -> dict: ...\n def has_required_index(self) -> bool: ...\n def _create_required_index(self): ...\n def reset(self): ...\n def has_table(self, dice_table: DiceTable) -> bool: ...\n def add_table(self, dice_table: DiceTable) -> DocumentId: ...\n def get_table(self, doc_id: DocumentId) -> DiceTable: ...\n\n self._conn = connection\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_Finder_find_nearest_table_no_match", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002379.py"} {"focal_file": "dicetables_db/requesthandler.py", "focal_class": null, "focal_method": "using_mongo_db", "tests": "import unittest\n\nclass Test_using_mongo_db(unittest.TestCase):\n def test_using_mongo_db(self):\n handler = RequestHandler.using_mongo_db('test_db', 'test', port=27017)\n self.assertIsInstance(handler, RequestHandler)\n conn = handler._conn\n self.assertIsInstance(conn, MongoDBConnection)\n self.assertEqual(conn.get_info()['current_collection'], 'test')\n self.assertEqual(conn.get_info()['db'], 'test_db')\n self.assertEqual(conn.get_info()['ip'], 'localhost')\n self.assertEqual(conn.get_info()['port'], '27017')\n", "method_code": " def using_mongo_db(cls, db_name, collection_name, ip='localhost', port=27017, max_dice_value=12000):\n return cls(MongoDBConnection(db_name, collection_name, ip, port), max_dice_value=max_dice_value)\n ", "context": "class RequestHandler(object):\n @classmethod\n def using_mongo_db(cls, db_name, collection_name, ip='localhost', port=27017, max_dice_value=12000): ...\n def __init__(self, connection: BaseConnection, max_dice_value=12000) -> None: ...\n def using_SQL(cls, db_path, collection_name, max_dice_value=12000): ...\n def request_dice_table_construction(self, instructions: str, update_queue: Queue=None, num_delimiter: str='*', pairs_delimiter: str='&') -> None: ...\n def _raise_error_for_bad_delimiter(num_delimiter, pairs_delimiter): ...\n def _check_record_against_max_dice_value(self, record): ...\n def get_table(self): ...\n def close_connection(self): ...\n def get_response(self, input_str, update_queue=None): ...\n\n self._conn = connection\n self._task_manager = TaskManager(DiceTableInsertionAndRetrieval(self._conn))\n self._table = DiceTable.new()\n self._parser = Parser(ignore_case=True)\n self._max_dice_value = max_dice_value\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_using_mongo_db", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002380.py"} {"focal_file": "dicetables_db/requesthandler.py", "focal_class": null, "focal_method": "get_table", "tests": "import unittest\n\nclass Test_get_table(unittest.TestCase):\n def test_get_table(self):\n self.assertEqual(self.handler.get_table(), DiceTable.new())\n self.handler._table = DiceTable.new().add_die(Die(6), 2).add_die(Die(5))\n self.assertEqual(self.handler.get_table(), DiceTable.new().add_die(Die(6), 2).add_die(Die(5)))\n", "method_code": " def get_table(self):\n return self._table\n ", "context": "class RequestHandler(object):\n def get_table(self): ...\n def __init__(self, connection: BaseConnection, max_dice_value=12000) -> None: ...\n def using_SQL(cls, db_path, collection_name, max_dice_value=12000): ...\n def using_mongo_db(cls, db_name, collection_name, ip='localhost', port=27017, max_dice_value=12000): ...\n def request_dice_table_construction(self, instructions: str, update_queue: Queue=None, num_delimiter: str='*', pairs_delimiter: str='&') -> None: ...\n def _raise_error_for_bad_delimiter(num_delimiter, pairs_delimiter): ...\n def _check_record_against_max_dice_value(self, record): ...\n def close_connection(self): ...\n def get_response(self, input_str, update_queue=None): ...\n\n self._conn = connection\n self._task_manager = TaskManager(DiceTableInsertionAndRetrieval(self._conn))\n self._table = DiceTable.new()\n self._parser = Parser(ignore_case=True)\n self._max_dice_value = max_dice_value\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_get_table", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002381.py"} {"focal_file": "dicetables_db/requesthandler.py", "focal_class": null, "focal_method": "request_dice_table_construction", "tests": "import unittest\n\nclass Test_request_dice_table_construction(unittest.TestCase):\n def test_request_dice_table_empty_string(self):\n self.handler.request_dice_table_construction('')\n self.assertEqual(self.handler.get_table(), DiceTable.new())\n\n def test_request_dice_table_empty_string_queue(self):\n q = Queue()\n self.handler.request_dice_table_construction('', q)\n self.assertEqual(q.get(), 'STOP')\n\n def test_request_dice_table_only_whitespace(self):\n self.handler.request_dice_table_construction(' ')\n self.assertEqual(self.handler.get_table(), DiceTable.new())\n\n def test_request_dice_table_construction_request_exceeds_max_dice_value(self):\n handler = RequestHandler.using_SQL(':memory:', 'test', max_dice_value=12)\n handler.request_dice_table_construction('2*Die(6)')\n handler.request_dice_table_construction('6*WeightedDie({1: 2, 2: 10})')\n with self.assertRaises(ValueError) as cm:\n handler.request_dice_table_construction('1*Die(6)&1*Die(7)')\n self.assertEqual(cm.exception.args[0], 'The sum of all max(die_size, len(die_dict))*die_number must be <= 12')\n\n def test_request_dice_table_construction(self):\n self.handler.request_dice_table_construction('2*Die(5) & 1*Die(4)')\n self.assertEqual(self.handler.get_table(), DiceTable.new().add_die(Die(5), 2).add_die(Die(4)))\n\n def test_request_dice_table_construction_leading_and_trailing_whitespace(self):\n self.handler.request_dice_table_construction(' 2 * Die( 5 ) & 1 * Die( 4 ) ')\n self.assertEqual(self.handler.get_table(), DiceTable.new().add_die(Die(5), 2).add_die(Die(4)))\n\n def test_request_dice_table_construction_single_dice_do_not_need_number(self):\n self.handler.request_dice_table_construction('2*Die(5) & Die(4)')\n self.assertEqual(self.handler.get_table(), DiceTable.new().add_die(Die(5), 2).add_die(Die(4)))\n\n def test_request_dice_table_construction_all_dice_singly(self):\n all_dice = [Die(die_size=2), ModDie(2, modifier=-1), WeightedDie(dictionary_input={3: 4, 5: 6, 7: 8, 9: 0}), ModWeightedDie({1: 2, 3: 4}, 0), StrongDie(input_die=Die(2), multiplier=2), Exploding(Die(2), explosions=1), ExplodingOn(Die(3), explodes_on=(1, 2)), Modifier(modifier=-100)]\n for die in all_dice:\n self.handler.request_dice_table_construction('2 * {!r}'.format(die))\n self.assertEqual(self.handler.get_table(), DiceTable.new().add_die(die, 2))\n\n def test_request_dice_table_construction_all_kwargs(self):\n all_dice = ['ModDie(die_size=2, modifier=-1)', 'WeightedDie(dictionary_input={3: 4, 5: 6, 7: 8, 9: 0})', 'ModWeightedDie(dictionary_input={3: 4, 5: 6, 7: 8, 9: 0}, modifier=-3)', 'StrongDie(input_die=Die(2), multiplier=2)', 'Modifier(modifier=-100)', 'Exploding(Die(2), explosions=1)', 'ExplodingOn(Die(3), explodes_on=(1, 2))']\n for die_str in all_dice:\n die = Parser().parse_die(die_str)\n self.handler.request_dice_table_construction('2 * {}'.format(die_str))\n self.assertEqual(self.handler.get_table(), DiceTable.new().add_die(die, 2))\n\n def test_request_dice_table_construction_mixed_case(self):\n request = 'dIe(DiE_sIzE=3)'\n self.handler.request_dice_table_construction(request)\n self.assertEqual(self.handler.get_table(), DiceTable.new().add_die(Die(3)))\n\n def test_request_dice_table_construction_with_update_queue(self):\n q = Queue()\n self.handler.request_dice_table_construction('20*Die(6)', q)\n expected = ['', '', '', '']\n for value in expected:\n self.assertEqual(value, q.get())\n self.assertEqual(q.get(), 'STOP')\n", "method_code": " def request_dice_table_construction(self, instructions: str, update_queue: Queue=None, num_delimiter: str='*', pairs_delimiter: str='&') -> None:\n self._raise_error_for_bad_delimiter(num_delimiter, pairs_delimiter)\n record = DiceRecord.new()\n if instructions.strip() == '':\n number_die_pairs = []\n else:\n number_die_pairs = instructions.split(pairs_delimiter)\n for pair in number_die_pairs:\n if num_delimiter not in pair:\n number = 1\n die = pair\n else:\n num, die = pair.split(num_delimiter)\n number = int(num)\n die = self._parser.parse_die_within_limits(die)\n record = record.add_die(die, number)\n self._check_record_against_max_dice_value(record)\n self._table = self._task_manager.process_request(record, update_queue=update_queue)\n ", "context": "class RequestHandler(object):\n def request_dice_table_construction(self, instructions: str, update_queue: Queue=None, num_delimiter: str='*', pairs_delimiter: str='&') -> None: ...\n def __init__(self, connection: BaseConnection, max_dice_value=12000) -> None: ...\n def using_SQL(cls, db_path, collection_name, max_dice_value=12000): ...\n def using_mongo_db(cls, db_name, collection_name, ip='localhost', port=27017, max_dice_value=12000): ...\n def _raise_error_for_bad_delimiter(num_delimiter, pairs_delimiter): ...\n def _check_record_against_max_dice_value(self, record): ...\n def get_table(self): ...\n def close_connection(self): ...\n def get_response(self, input_str, update_queue=None): ...\n\n self._conn = connection\n self._task_manager = TaskManager(DiceTableInsertionAndRetrieval(self._conn))\n self._table = DiceTable.new()\n self._parser = Parser(ignore_case=True)\n self._max_dice_value = max_dice_value\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_request_dice_table_empty_string", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002382.py"} {"focal_file": "dicetables_db/requesthandler.py", "focal_class": null, "focal_method": "close_connection", "tests": "import unittest\n\nclass Test_close_connection(unittest.TestCase):\n def test_close_connection(self):\n self.handler.close_connection()\n self.assertRaises(AttributeError, self.handler.request_dice_table_construction, '1*Die(6)')\n", "method_code": " def close_connection(self):\n self._conn.close()\n ", "context": "class RequestHandler(object):\n def close_connection(self): ...\n def __init__(self, connection: BaseConnection, max_dice_value=12000) -> None: ...\n def using_SQL(cls, db_path, collection_name, max_dice_value=12000): ...\n def using_mongo_db(cls, db_name, collection_name, ip='localhost', port=27017, max_dice_value=12000): ...\n def request_dice_table_construction(self, instructions: str, update_queue: Queue=None, num_delimiter: str='*', pairs_delimiter: str='&') -> None: ...\n def _raise_error_for_bad_delimiter(num_delimiter, pairs_delimiter): ...\n def _check_record_against_max_dice_value(self, record): ...\n def get_table(self): ...\n def get_response(self, input_str, update_queue=None): ...\n\n self._conn = connection\n self._task_manager = TaskManager(DiceTableInsertionAndRetrieval(self._conn))\n self._table = DiceTable.new()\n self._parser = Parser(ignore_case=True)\n self._max_dice_value = max_dice_value\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_close_connection", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002383.py"} {"focal_file": "dicetables_db/requesthandler.py", "focal_class": null, "focal_method": "get_response", "tests": "import unittest\n\nclass Test_get_response(unittest.TestCase):\n def test_get_response_no_error(self):\n table = DiceTable.new().add_die(Die(6), 10).add_die(Die(3), 12)\n expected = make_dict(table)\n instructions = '10*Die(6)&12*Die(3)'\n reverse_instructions = '12*Die(3)&10*Die(6)'\n self.assertEqual(self.handler.get_response(instructions), expected)\n self.assertEqual(self.handler.get_response(reverse_instructions), expected)\n", "method_code": " def get_response(self, input_str, update_queue=None):\n errors = (ValueError, SyntaxError, AttributeError, IndexError, ParseError, LimitsError, InvalidEventsError, DiceRecordError)\n try:\n self.request_dice_table_construction(input_str, update_queue)\n return make_dict(self._table)\n except errors as e:\n return {'error': e.args[0], 'type': e.__class__.__name__}\n ", "context": "class RequestHandler(object):\n def get_response(self, input_str, update_queue=None): ...\n def __init__(self, connection: BaseConnection, max_dice_value=12000) -> None: ...\n def using_SQL(cls, db_path, collection_name, max_dice_value=12000): ...\n def using_mongo_db(cls, db_name, collection_name, ip='localhost', port=27017, max_dice_value=12000): ...\n def request_dice_table_construction(self, instructions: str, update_queue: Queue=None, num_delimiter: str='*', pairs_delimiter: str='&') -> None: ...\n def _raise_error_for_bad_delimiter(num_delimiter, pairs_delimiter): ...\n def _check_record_against_max_dice_value(self, record): ...\n def get_table(self): ...\n def close_connection(self): ...\n\n self._conn = connection\n self._task_manager = TaskManager(DiceTableInsertionAndRetrieval(self._conn))\n self._table = DiceTable.new()\n self._parser = Parser(ignore_case=True)\n self._max_dice_value = max_dice_value\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_get_response_no_error", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002384.py"} {"focal_file": "dicetables_db/taskmanager.py", "focal_class": null, "focal_method": "get_closest_from_database", "tests": "import unittest\n\nclass Test_get_closest_from_database(unittest.TestCase):\n def test_get_closest_from_database_no_matches_in_database(self):\n table = DiceTable.new().add_die(Die(10))\n self.insert_retrieve.add_table(table)\n self.assertTrue(self.insert_retrieve.has_table(table))\n empty_table = self.task_manager.get_closest_from_database(DiceRecord({Die(5): 2}))\n self.assertEqual(empty_table, DiceTable.new())\n\n def test_get_closest_from_database_no_matches_database_table_too_big(self):\n table = DiceTable.new().add_die(Die(10), 2)\n self.insert_retrieve.add_table(table)\n target = DiceRecord({Die(10): 1})\n empty_table = self.task_manager.get_closest_from_database(target)\n self.assertEqual(empty_table, DiceTable.new())\n\n def test_get_closest_from_database_exact_match(self):\n one_d10 = DiceTable.new().add_die(Die(10), 1)\n two_d10 = DiceTable.new().add_die(Die(10), 2)\n self.insert_retrieve.add_table(one_d10)\n self.insert_retrieve.add_table(two_d10)\n target_1 = DiceRecord({Die(10): 1})\n target_2 = DiceRecord({Die(10): 2})\n answer_1 = self.task_manager.get_closest_from_database(target_1)\n answer_2 = self.task_manager.get_closest_from_database(target_2)\n self.assertEqual(answer_1, one_d10)\n self.assertEqual(answer_2, two_d10)\n\n def test_get_closest_from_database_partial_match(self):\n one_d5 = DiceTable.new().add_die(Die(5), 1)\n two_d5 = DiceTable.new().add_die(Die(5), 2)\n one_d10 = DiceTable.new().add_die(Die(10), 1)\n two_d10 = DiceTable.new().add_die(Die(10), 2)\n one_d5_one_d10 = DiceTable.new().add_die(Die(5)).add_die(Die(10))\n self.insert_retrieve.add_table(one_d5)\n self.insert_retrieve.add_table(two_d5)\n self.insert_retrieve.add_table(one_d10)\n self.insert_retrieve.add_table(two_d10)\n self.insert_retrieve.add_table(one_d5_one_d10)\n target_1 = DiceRecord({Die(10): 2, Die(5): 1})\n target_2 = DiceRecord({Die(10): 1, Die(5): 2})\n target_3 = DiceRecord({Die(10): 2, Die(5): 2})\n answer_1 = self.task_manager.get_closest_from_database(target_1)\n answer_2 = self.task_manager.get_closest_from_database(target_2)\n answer_3 = self.task_manager.get_closest_from_database(target_3)\n self.assertEqual(answer_1, two_d10)\n self.assertEqual(answer_2, one_d5_one_d10)\n self.assertEqual(answer_3, two_d10)\n", "method_code": " def get_closest_from_database(self, dice_record: DiceRecord) -> DiceTable:\n dice_list = sorted(dice_record.get_dict().items())\n id_ = self._insert_retrieve.find_nearest_table(dice_list)\n if id_ is None:\n return DiceTable.new()\n return self._insert_retrieve.get_table(id_)\n ", "context": "class TaskManager(object):\n def get_closest_from_database(self, dice_record: DiceRecord) -> DiceTable: ...\n def __init__(self, insert_retrieve: DiceTableInsertionAndRetrieval, step_size=30) -> None: ...\n def step_size(self): ...\n def save_table_list(self, table_list: list): ...\n def process_request(self, dice_record: DiceRecord, update_queue: Queue=None) -> DiceTable: ...\n\n self._insert_retrieve = insert_retrieve\n self._step_size = step_size\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_get_closest_from_database_no_matches_in_database", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002385.py"} {"focal_file": "dicetables_db/taskmanager.py", "focal_class": null, "focal_method": "process_request", "tests": "import unittest\n\nclass Test_process_request(unittest.TestCase):\n def test_process_request_empty_record(self):\n q = Queue()\n request = DiceRecord.new()\n answer = self.task_manager.process_request(request, q)\n self.assertEqual(answer, DiceTable.new())\n self.assertEqual(q.get(), 'STOP')\n\n def test_process_request_with_queue(self):\n q = Queue()\n request = DiceRecord({Die(6): 20})\n answer = self.task_manager.process_request(request, update_queue=q)\n self.assertEqual(answer, DiceTable.new().add_die(Die(6), 20))\n expected_reprs = ['', '', '', '']\n for table_repr in expected_reprs:\n self.assertEqual(q.get(), table_repr)\n self.assertEqual(q.get(), 'STOP')\n", "method_code": " def process_request(self, dice_record: DiceRecord, update_queue: Queue=None) -> DiceTable:\n modifier, new_record = extract_modifiers(dice_record)\n if new_record == DiceRecord.new():\n closest = DiceTable.new()\n else:\n closest = self.get_closest_from_database(new_record)\n table_generator = TableGenerator(new_record)\n tables_to_save = table_generator.create_save_list(closest, self.step_size, update_queue)\n if not tables_to_save:\n intermediate_table = closest\n else:\n intermediate_table = tables_to_save[-1]\n self.save_table_list(tables_to_save)\n raw_final_table = table_generator.create_target_table(intermediate_table)\n table_with_modifier = apply_modifier(raw_final_table, modifier)\n answer = DiceTable(table_with_modifier.get_dict(), dice_record)\n return answer\n ", "context": "class TaskManager(object):\n def process_request(self, dice_record: DiceRecord, update_queue: Queue=None) -> DiceTable: ...\n def __init__(self, insert_retrieve: DiceTableInsertionAndRetrieval, step_size=30) -> None: ...\n def step_size(self): ...\n def get_closest_from_database(self, dice_record: DiceRecord) -> DiceTable: ...\n def save_table_list(self, table_list: list): ...\n\n self._insert_retrieve = insert_retrieve\n self._step_size = step_size\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_process_request_empty_record", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002386.py"} {"focal_file": "dicetables_db/taskmanager.py", "focal_class": "TaskManager", "focal_method": "process_request", "tests": "import unittest\n\nclass Test_TaskManager_process_request(unittest.TestCase):\n def test_process_request_each_die_type(self):\n all_dice = [Modifier(3), Die(3), ModDie(3, -1), WeightedDie({1: 2, 2: 1}), ModWeightedDie({1: 2, 2: 1}, 4), StrongDie(Die(3), 3), Exploding(Die(3), explosions=1), ExplodingOn(Die(3), (1,), explosions=1)]\n add_times = 2\n one_step = TaskManager(self.insert_retrieve, step_size=1)\n for die in all_dice:\n request = DiceRecord.new().add_die(die, add_times)\n answer = one_step.process_request(request)\n expected = DiceTable.new().add_die(die, add_times)\n self.assertEqual(answer, expected)\n", "method_code": " def process_request(self, dice_record: DiceRecord, update_queue: Queue=None) -> DiceTable:\n modifier, new_record = extract_modifiers(dice_record)\n if new_record == DiceRecord.new():\n closest = DiceTable.new()\n else:\n closest = self.get_closest_from_database(new_record)\n table_generator = TableGenerator(new_record)\n tables_to_save = table_generator.create_save_list(closest, self.step_size, update_queue)\n if not tables_to_save:\n intermediate_table = closest\n else:\n intermediate_table = tables_to_save[-1]\n self.save_table_list(tables_to_save)\n raw_final_table = table_generator.create_target_table(intermediate_table)\n table_with_modifier = apply_modifier(raw_final_table, modifier)\n answer = DiceTable(table_with_modifier.get_dict(), dice_record)\n return answer\n ", "context": "class TaskManager(object):\n def process_request(self, dice_record: DiceRecord, update_queue: Queue=None) -> DiceTable: ...\n def __init__(self, insert_retrieve: DiceTableInsertionAndRetrieval, step_size=30) -> None: ...\n def step_size(self): ...\n def get_closest_from_database(self, dice_record: DiceRecord) -> DiceTable: ...\n def save_table_list(self, table_list: list): ...\n\n self._insert_retrieve = insert_retrieve\n self._step_size = step_size\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_process_request_each_die_type", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002387.py"} {"focal_file": "dicetables_db/connections/baseconnection.py", "focal_class": null, "focal_method": "get_info", "tests": "import unittest\n\nclass Test_get_info(unittest.TestCase):\n def test_1_get_info(self):\n expected = {'db': 'test_db', 'collections': ['test'], 'current_collection': 'test', 'indices': []}\n self.assertEqual(self.connection.get_info(), expected)\n\n def test_2_get_info_new_connection(self):\n expected = {'db': 'test_db', 'collections': ['bob', 'test'], 'current_collection': 'bob', 'indices': [('foo',), ('foo', 'bar')]}\n new_connection = self.new_connection('bob')\n new_connection.create_index(('foo',))\n new_connection.create_index(('foo', 'bar'))\n self.assertEqual(new_connection.get_info(), expected)\n", "method_code": " def get_info(self):\n \"\"\"\n \n :return: {'db': name_or_file_path,\n 'collections': [all collection/table names],\n 'current collection': name of collection in use,\n 'indices': [('col', 'col'), ('col',) ...]\n \"\"\"\n raise NotImplementedError\n ", "context": "class BaseConnection(object):\n def get_info(self): ...\n def id_class(cls): ...\n def is_collection_empty(self): ...\n def find(self, params_dict=None, restrictions=None): ...\n def find_one(self, params_dict=None, restrictions=None): ...\n def insert(self, document): ...\n def reset_collection(self): ...\n def drop_collection(self): ...\n def close(self): ...\n def create_index(self, columns_tuple): ...\n def has_index(self, columns_tuple): ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_1_get_info", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002388.py"} {"focal_file": "dicetables_db/connections/baseconnection.py", "focal_class": null, "focal_method": "is_collection_empty", "tests": "import unittest\n\nclass Test_is_collection_empty(unittest.TestCase):\n def test_3_is_collection_empty_true(self):\n self.assertTrue(self.connection.is_collection_empty())\n\n def test_4_is_collection_empty_false(self):\n self.populate_db()\n self.assertFalse(self.connection.is_collection_empty())\n\n def test_7_reset_collection_multiple_collections_only_empties_requested(self):\n document = {'a': 1}\n new_connection = self.new_connection('bob')\n self.connection.insert(document)\n new_connection.insert(document)\n self.assertFalse(self.connection.is_collection_empty())\n self.assertFalse(new_connection.is_collection_empty())\n self.connection.reset_collection()\n self.assertTrue(self.connection.is_collection_empty())\n self.assertFalse(new_connection.is_collection_empty())\n", "method_code": " def is_collection_empty(self):\n raise NotImplementedError\n ", "context": "class BaseConnection(object):\n def is_collection_empty(self): ...\n def id_class(cls): ...\n def get_info(self): ...\n def find(self, params_dict=None, restrictions=None): ...\n def find_one(self, params_dict=None, restrictions=None): ...\n def insert(self, document): ...\n def reset_collection(self): ...\n def drop_collection(self): ...\n def close(self): ...\n def create_index(self, columns_tuple): ...\n def has_index(self, columns_tuple): ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_3_is_collection_empty_true", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002389.py"} {"focal_file": "dicetables_db/connections/baseconnection.py", "focal_class": null, "focal_method": "reset_collection", "tests": "import unittest\n\nclass Test_reset_collection(unittest.TestCase):\n def test_5_reset_collection_still_in_db(self):\n self.connection.reset_collection()\n self.assertEqual(['test'], self.connection.get_info()['collections'])\n", "method_code": " def reset_collection(self):\n raise NotImplementedError\n ", "context": "class BaseConnection(object):\n def reset_collection(self): ...\n def id_class(cls): ...\n def get_info(self): ...\n def is_collection_empty(self): ...\n def find(self, params_dict=None, restrictions=None): ...\n def find_one(self, params_dict=None, restrictions=None): ...\n def insert(self, document): ...\n def drop_collection(self): ...\n def close(self): ...\n def create_index(self, columns_tuple): ...\n def has_index(self, columns_tuple): ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_5_reset_collection_still_in_db", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002390.py"} {"focal_file": "dicetables_db/connections/baseconnection.py", "focal_class": null, "focal_method": "insert", "tests": "import unittest\n\nclass Test_insert(unittest.TestCase):\n def test_13_insert(self):\n original = {'a': 1, 'b': 2}\n doc_id = self.connection.insert(original)\n original['_id'] = doc_id\n original_plus_id = self.connection.find_one()\n self.assertEqual(original, original_plus_id)\n self.assertIsNot(original, original_plus_id)\n", "method_code": " def insert(self, document):\n \"\"\"\n \n :return: instance of self.id_class()\n \"\"\"\n raise NotImplementedError\n ", "context": "class BaseConnection(object):\n def insert(self, document): ...\n def id_class(cls): ...\n def get_info(self): ...\n def is_collection_empty(self): ...\n def find(self, params_dict=None, restrictions=None): ...\n def find_one(self, params_dict=None, restrictions=None): ...\n def reset_collection(self): ...\n def drop_collection(self): ...\n def close(self): ...\n def create_index(self, columns_tuple): ...\n def has_index(self, columns_tuple): ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_13_insert", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002391.py"} {"focal_file": "dicetables_db/connections/baseconnection.py", "focal_class": null, "focal_method": "find", "tests": "import unittest\n\nclass Test_find(unittest.TestCase):\n def test_43_lt_syntax_with_find(self):\n self.populate_db()\n results = list(self.connection.find({'a': {'$lt': 1}}, {'a': 1, 'b': 1}))\n expected = [{'a': 0, 'b': 0}] * 4\n self.assertEqual(results, expected)\n\n def test_44_lte_syntax_with_find(self):\n self.populate_db()\n results = list(self.connection.find({'a': {'$lte': 1}}, {'a': 1}))\n results_zero = [element for element in results if element == {'a': 0}]\n results_one = [element for element in results if element == {'a': 1}]\n self.assertEqual(len(results_one), 3)\n self.assertEqual(len(results_zero), 4)\n self.assertEqual(len(results), 7)\n\n def test_45_gt_syntax_with_find(self):\n self.populate_db()\n results = list(self.connection.find({'a': {'$gt': 1}}, {'a': 1}))\n self.assertEqual(results, [{'a': 2}] * 3)\n\n def test_46_gte_syntax_with_find(self):\n self.populate_db()\n results = list(self.connection.find({'a': {'$gte': 2}}, {'a': 1}))\n self.assertEqual(results, [{'a': 2}] * 3)\n\n def test_47_ne_syntax_with_find(self):\n self.populate_db()\n results = list(self.connection.find({'a': {'$ne': 1}}, {'a': 1}))\n results_zero = [element for element in results if element == {'a': 0}]\n results_two = [element for element in results if element == {'a': 2}]\n self.assertEqual(len(results_two), 3)\n self.assertEqual(len(results_zero), 4)\n self.assertEqual(len(results), 7)\n", "method_code": " def find(self, params_dict=None, restrictions=None):\n \"\"\"\n \n :return: iterable of document dictionaries\n \"\"\"\n raise NotImplementedError\n ", "context": "class BaseConnection(object):\n def find(self, params_dict=None, restrictions=None): ...\n def id_class(cls): ...\n def get_info(self): ...\n def is_collection_empty(self): ...\n def find_one(self, params_dict=None, restrictions=None): ...\n def insert(self, document): ...\n def reset_collection(self): ...\n def drop_collection(self): ...\n def close(self): ...\n def create_index(self, columns_tuple): ...\n def has_index(self, columns_tuple): ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_43_lt_syntax_with_find", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002392.py"} {"focal_file": "dicetables_db/connections/mongodb_connection.py", "focal_class": null, "focal_method": "get_info", "tests": "import unittest\n\nclass Test_get_info(unittest.TestCase):\n def test_1_get_info(self):\n expected = {'db': 'test_db', 'collections': [], 'current_collection': 'test', 'indices': [], 'ip': 'localhost', 'port': '27017'}\n self.assertEqual(self.connection.get_info(), expected)\n\n def test_2_get_info_new_connection(self):\n expected = {'db': 'test_db', 'collections': ['bob'], 'current_collection': 'bob', 'indices': [('foo',), ('foo', 'bar')], 'ip': 'localhost', 'port': '27017'}\n new_connection = self.new_connection('bob')\n new_connection.create_index(('foo',))\n new_connection.create_index(('foo', 'bar'))\n self.assertEqual(new_connection.get_info(), expected)\n", "method_code": " def get_info(self):\n indices = self._get_indices()\n info = {'db': self._db.name, 'collections': self._db.collection_names(), 'current_collection': self._collection.name, 'indices': indices, 'ip': self._params_storage[2], 'port': self._params_storage[3]}\n return info\n ", "context": "class MongoDBConnection(BaseConnection):\n def get_info(self): ...\n def __init__(self, db_name: str, collection_name: str, ip='localhost', port=27017): ...\n def is_collection_empty(self): ...\n def _get_indices(self): ...\n def reset_collection(self): ...\n def drop_collection(self): ...\n def close(self): ...\n def find(self, params_dict=None, projection=None): ...\n def find_one(self, params_dict=None, projection=None): ...\n def _prep_find_inputs(self, params_dict, projection): ...\n def _params_with_new_id(self, params): ...\n def _result_with_new_id(self, result): ...\n def _dict_with_new_id(convert_method, input_dict): ...\n def _raise_error_for_bad_projection(projection): ...\n def _make_consistent_projection_api(projection): ...\n def insert(self, document): ...\n def create_index(self, column_tuple): ...\n def has_index(self, columns_tuple): ...\n\n self._client = MongoClient(ip, port)\n self._db = self._client[db_name]\n self._collection = self._db[collection_name]\n self._params_storage = (db_name, collection_name, ip, str(port))\n self._place_holder = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_1_get_info", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002393.py"} {"focal_file": "dicetables_db/connections/mongodb_connection.py", "focal_class": null, "focal_method": "reset_collection", "tests": "import unittest\n\nclass Test_reset_collection(unittest.TestCase):\n def test_5_reset_collection_still_in_db(self):\n self.connection.reset_collection()\n self.assertEqual([], self.connection.get_info()['collections'])\n", "method_code": " def reset_collection(self):\n self.drop_collection()\n ", "context": "class MongoDBConnection(BaseConnection):\n def reset_collection(self): ...\n def __init__(self, db_name: str, collection_name: str, ip='localhost', port=27017): ...\n def is_collection_empty(self): ...\n def get_info(self): ...\n def _get_indices(self): ...\n def drop_collection(self): ...\n def close(self): ...\n def find(self, params_dict=None, projection=None): ...\n def find_one(self, params_dict=None, projection=None): ...\n def _prep_find_inputs(self, params_dict, projection): ...\n def _params_with_new_id(self, params): ...\n def _result_with_new_id(self, result): ...\n def _dict_with_new_id(convert_method, input_dict): ...\n def _raise_error_for_bad_projection(projection): ...\n def _make_consistent_projection_api(projection): ...\n def insert(self, document): ...\n def create_index(self, column_tuple): ...\n def has_index(self, columns_tuple): ...\n\n self._client = MongoClient(ip, port)\n self._db = self._client[db_name]\n self._collection = self._db[collection_name]\n self._params_storage = (db_name, collection_name, ip, str(port))\n self._place_holder = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_5_reset_collection_still_in_db", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002394.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": null, "focal_method": "get_info", "tests": "import unittest\n\nclass Test_get_info(unittest.TestCase):\n def test_1_get_info(self):\n expected = {'db': ':memory:', 'collections': ['test'], 'current_collection': 'test', 'indices': []}\n self.assertIsInstance(self.connection, SQLConnection)\n self.assertEqual(self.connection.get_info(), expected)\n\n def test_2_get_info_new_connection(self):\n expected = {'db': 'test.db', 'collections': ['bob', 'test'], 'current_collection': 'bob', 'indices': [('foo',), ('foo', 'bar')]}\n self.new_persistent_connection('test')\n new_connection = self.new_persistent_connection('bob')\n new_connection.create_index(('foo',))\n new_connection.create_index(('foo', 'bar'))\n self.assertEqual(new_connection.get_info(), expected)\n", "method_code": " def get_info(self):\n out = {'db': self._path, 'collections': self._in_memory.collections, 'current_collection': self._collection, 'indices': self._in_memory.indices}\n return out\n ", "context": "class SQLConnection(BaseConnection):\n def get_info(self): ...\n def __init__(self, db_path, collection_name): ...\n def _set_up(self): ...\n def cursor(self): ...\n def collection(self): ...\n def is_collection_empty(self): ...\n def find(self, params_dict=None, projection=None): ...\n def find_one(self, params_dict=None, projection=None): ...\n def _get_columns_list(self, projection): ...\n def _does_projection_use_inclusion(projection): ...\n def _get_columns_by_inclusion(self, projection): ...\n def _get_columns_by_exlusion(self, projection): ...\n def _get_command_and_values(self, params_dict, columns_list): ...\n def _has_non_existent_columns(self, params_dict): ...\n def _get_select_statement(self, columns_list): ...\n def _get_statement_and_values_for_where(self, params_dict): ...\n def _get_inequality_data(inequality_info): ...\n def _make_dict(self, keys, values): ...\n def _change_id_key(self, answer): ...\n def insert(self, document): ...\n def _insert_command_and_values(self, document, id_to_return): ...\n def _update_columns(self, document): ...\n def _add_column(self, column, value): ...\n def drop_collection(self): ...\n def reset_collection(self): ...\n def _drop_indices(self): ...\n def close(self): ...\n def create_index(self, columns_tuple): ...\n def has_index(self, columns_tuple): ...\n def save_to_target(self, db_name): ...\n def load_from_target(self, db_name): ...\n\n self._path = db_path\n self._collection = collection_name\n self._connection = lite.connect(self._path, detect_types=lite.PARSE_DECLTYPES)\n self._cursor = self._connection.cursor()\n self._in_memory = InMemoryInformation(self)\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_1_get_info", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002395.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": null, "focal_method": "refresh_columns", "tests": "import unittest\n\nclass Test_refresh_columns(unittest.TestCase):\n def test_InMemoryInformation_refresh_columns(self):\n self.assertEqual(self.in_memory.columns, ['_id'])\n self.connection.insert({'a': 1})\n self.in_memory.refresh_columns()\n self.assertEqual(self.in_memory.columns, ['_id', 'a'])\n", "method_code": " def refresh_columns(self):\n self._cursor.execute('PRAGMA table_info([{}])'.format(self._collection))\n data = self._cursor.fetchall()\n self._col_names = [col_data[1] for col_data in data]\n ", "context": "class InMemoryInformation(object):\n def refresh_columns(self): ...\n def __init__(self, connection): ...\n def refresh_information(self): ...\n def refresh_collections(self): ...\n def refresh_indices(self): ...\n def has_column(self, col_name): ...\n def has_collection(self, table_name): ...\n def has_index(self, columns_tuple): ...\n def collections(self): ...\n def columns(self): ...\n def indices(self): ...\n def add_collection(self, table_name): ...\n def add_column(self, col_name): ...\n def add_index(self, columns_tuple): ...\n def drop_collection(self): ...\n\n self._cursor = connection.cursor\n self._collection = connection.collection\n self._collections = None\n self._col_names = None\n self._indices = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryInformation_refresh_columns", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002396.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": "SQLConnection", "focal_method": "refresh_collections", "tests": "import unittest\n\nclass Test_SQLConnection_refresh_collections(unittest.TestCase):\n def test_InMemoryInformation_refresh_collections(self):\n connection_1 = SQLConnection('test.db', 'foo')\n in_memory = InMemoryInformation(connection_1)\n connection_2 = SQLConnection('test.db', 'bar')\n self.assertEqual(in_memory.collections, ['foo'])\n in_memory.refresh_collections()\n self.assertEqual(in_memory.collections, ['bar', 'foo'])\n connection_1.drop_collection()\n connection_2.drop_collection()\n connection_1.close()\n connection_2.close()\n", "method_code": " def refresh_collections(self):\n self._cursor.execute(\"SELECT name FROM sqlite_master WHERE TYPE='table';\")\n self._collections = sorted([element[0] for element in self._cursor.fetchall()])\n ", "context": "class InMemoryInformation(object):\n def refresh_collections(self): ...\n def __init__(self, connection): ...\n def refresh_information(self): ...\n def refresh_columns(self): ...\n def refresh_indices(self): ...\n def has_column(self, col_name): ...\n def has_collection(self, table_name): ...\n def has_index(self, columns_tuple): ...\n def collections(self): ...\n def columns(self): ...\n def indices(self): ...\n def add_collection(self, table_name): ...\n def add_column(self, col_name): ...\n def add_index(self, columns_tuple): ...\n def drop_collection(self): ...\n\n self._cursor = connection.cursor\n self._collection = connection.collection\n self._collections = None\n self._col_names = None\n self._indices = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryInformation_refresh_collections", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002397.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": null, "focal_method": "refresh_indices", "tests": "import unittest\n\nclass Test_refresh_indices(unittest.TestCase):\n def test_InMemoryInformation_refresh_indices(self):\n self.assertEqual(self.in_memory.indices, [])\n self.connection.create_index(('a', 'b'))\n self.in_memory.refresh_indices()\n self.assertEqual(self.in_memory.indices, [('a', 'b')])\n", "method_code": " def refresh_indices(self):\n self._cursor.execute(\"SELECT * FROM sqlite_master WHERE TYPE='index';\")\n data = self._cursor.fetchall()\n indices = []\n for index_data in data:\n if index_data[2] == self._collection:\n index_name = index_data[1]\n if 'autoindex' in index_name:\n continue\n indices.append(tuple(index_name.split('&')))\n self._indices = sorted(indices)\n ", "context": "class InMemoryInformation(object):\n def refresh_indices(self): ...\n def __init__(self, connection): ...\n def refresh_information(self): ...\n def refresh_collections(self): ...\n def refresh_columns(self): ...\n def has_column(self, col_name): ...\n def has_collection(self, table_name): ...\n def has_index(self, columns_tuple): ...\n def collections(self): ...\n def columns(self): ...\n def indices(self): ...\n def add_collection(self, table_name): ...\n def add_column(self, col_name): ...\n def add_index(self, columns_tuple): ...\n def drop_collection(self): ...\n\n self._cursor = connection.cursor\n self._collection = connection.collection\n self._collections = None\n self._col_names = None\n self._indices = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryInformation_refresh_indices", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002398.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": "SQLConnection", "focal_method": "refresh_information", "tests": "import unittest\n\nclass Test_SQLConnection_refresh_information(unittest.TestCase):\n def test_InMemoryInformation_refresh_information(self):\n connection_1 = SQLConnection('test.db', 'foo')\n in_memory = InMemoryInformation(connection_1)\n self.assertEqual(in_memory.columns, ['_id'])\n self.assertEqual(in_memory.collections, ['foo'])\n self.assertEqual(in_memory.indices, [])\n connection_1.create_index(('a', 'b'))\n connection_2 = SQLConnection('test.db', 'bar')\n in_memory.refresh_information()\n self.assertEqual(in_memory.indices, [('a', 'b')])\n self.assertEqual(in_memory.collections, ['bar', 'foo'])\n self.assertEqual(in_memory.columns, ['_id', 'a', 'b'])\n connection_1.drop_collection()\n connection_2.drop_collection()\n connection_1.close()\n connection_2.close()\n", "method_code": " def refresh_information(self):\n self.refresh_collections()\n self.refresh_columns()\n self.refresh_indices()\n ", "context": "class InMemoryInformation(object):\n def refresh_information(self): ...\n def __init__(self, connection): ...\n def refresh_collections(self): ...\n def refresh_columns(self): ...\n def refresh_indices(self): ...\n def has_column(self, col_name): ...\n def has_collection(self, table_name): ...\n def has_index(self, columns_tuple): ...\n def collections(self): ...\n def columns(self): ...\n def indices(self): ...\n def add_collection(self, table_name): ...\n def add_column(self, col_name): ...\n def add_index(self, columns_tuple): ...\n def drop_collection(self): ...\n\n self._cursor = connection.cursor\n self._collection = connection.collection\n self._collections = None\n self._col_names = None\n self._indices = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryInformation_refresh_information", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002399.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": null, "focal_method": "add_column", "tests": "import unittest\n\nclass Test_add_column(unittest.TestCase):\n def test_InMemoryInformation_add_column(self):\n self.in_memory.add_column('a')\n self.assertEqual(self.in_memory.columns, ['_id', 'a'])\n", "method_code": " def add_column(self, col_name):\n if not self.has_column(col_name):\n self._col_names.append(col_name)\n ", "context": "class InMemoryInformation(object):\n def add_column(self, col_name): ...\n def __init__(self, connection): ...\n def refresh_information(self): ...\n def refresh_collections(self): ...\n def refresh_columns(self): ...\n def refresh_indices(self): ...\n def has_column(self, col_name): ...\n def has_collection(self, table_name): ...\n def has_index(self, columns_tuple): ...\n def collections(self): ...\n def columns(self): ...\n def indices(self): ...\n def add_collection(self, table_name): ...\n def add_index(self, columns_tuple): ...\n def drop_collection(self): ...\n\n self._cursor = connection.cursor\n self._collection = connection.collection\n self._collections = None\n self._col_names = None\n self._indices = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryInformation_add_column", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002400.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": null, "focal_method": "add_collection", "tests": "import unittest\n\nclass Test_add_collection(unittest.TestCase):\n def test_InMemoryInformation_add_collection(self):\n self.in_memory.add_collection('hello')\n self.assertEqual(self.in_memory.collections, ['hello', 'test'])\n", "method_code": " def add_collection(self, table_name):\n if not self.has_collection(table_name):\n self._collections.append(table_name)\n self._collections.sort()\n ", "context": "class InMemoryInformation(object):\n def add_collection(self, table_name): ...\n def __init__(self, connection): ...\n def refresh_information(self): ...\n def refresh_collections(self): ...\n def refresh_columns(self): ...\n def refresh_indices(self): ...\n def has_column(self, col_name): ...\n def has_collection(self, table_name): ...\n def has_index(self, columns_tuple): ...\n def collections(self): ...\n def columns(self): ...\n def indices(self): ...\n def add_column(self, col_name): ...\n def add_index(self, columns_tuple): ...\n def drop_collection(self): ...\n\n self._cursor = connection.cursor\n self._collection = connection.collection\n self._collections = None\n self._col_names = None\n self._indices = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryInformation_add_collection", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002401.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": null, "focal_method": "add_index", "tests": "import unittest\n\nclass Test_add_index(unittest.TestCase):\n def test_InMemoryInformation_add_index(self):\n self.in_memory.add_index(('hello',))\n self.assertEqual(self.in_memory.indices, [('hello',)])\n", "method_code": " def add_index(self, columns_tuple):\n if not self.has_index(columns_tuple):\n self._indices.append(columns_tuple)\n self._indices.sort()\n ", "context": "class InMemoryInformation(object):\n def add_index(self, columns_tuple): ...\n def __init__(self, connection): ...\n def refresh_information(self): ...\n def refresh_collections(self): ...\n def refresh_columns(self): ...\n def refresh_indices(self): ...\n def has_column(self, col_name): ...\n def has_collection(self, table_name): ...\n def has_index(self, columns_tuple): ...\n def collections(self): ...\n def columns(self): ...\n def indices(self): ...\n def add_collection(self, table_name): ...\n def add_column(self, col_name): ...\n def drop_collection(self): ...\n\n self._cursor = connection.cursor\n self._collection = connection.collection\n self._collections = None\n self._col_names = None\n self._indices = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryInformation_add_index", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002402.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": null, "focal_method": "has_collection", "tests": "import unittest\n\nclass Test_has_collection(unittest.TestCase):\n def test_InMemoryInformation_has_collection_t_and_f(self):\n self.assertTrue(self.in_memory.has_collection('test'))\n self.assertFalse(self.in_memory.has_collection('a'))\n", "method_code": " def has_collection(self, table_name):\n return table_name in self._collections\n ", "context": "class InMemoryInformation(object):\n def has_collection(self, table_name): ...\n def __init__(self, connection): ...\n def refresh_information(self): ...\n def refresh_collections(self): ...\n def refresh_columns(self): ...\n def refresh_indices(self): ...\n def has_column(self, col_name): ...\n def has_index(self, columns_tuple): ...\n def collections(self): ...\n def columns(self): ...\n def indices(self): ...\n def add_collection(self, table_name): ...\n def add_column(self, col_name): ...\n def add_index(self, columns_tuple): ...\n def drop_collection(self): ...\n\n self._cursor = connection.cursor\n self._collection = connection.collection\n self._collections = None\n self._col_names = None\n self._indices = None\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryInformation_has_collection_t_and_f", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002403.py"} {"focal_file": "dicetables_db/connections/sql_connection.py", "focal_class": null, "focal_method": "drop_collection", "tests": "import unittest\n\nclass Test_drop_collection(unittest.TestCase):\n def test_InMemoryDropCollection(self):\n self.in_memory.add_index(('a',))\n self.in_memory.add_column('b')\n self.in_memory.add_collection('will_still_exist')\n self.in_memory.drop_collection()\n self.assertEqual(self.in_memory.columns, [])\n self.assertEqual(self.in_memory.indices, [])\n self.assertEqual(self.in_memory.collections, ['will_still_exist'])\n", "method_code": " def drop_collection(self):\n self._drop_indices()\n self._cursor.execute('DROP TABLE IF EXISTS [{}]'.format(self._collection))\n self._in_memory.drop_collection()\n ", "context": "class SQLConnection(BaseConnection):\n def drop_collection(self): ...\n def __init__(self, db_path, collection_name): ...\n def _set_up(self): ...\n def get_info(self): ...\n def cursor(self): ...\n def collection(self): ...\n def is_collection_empty(self): ...\n def find(self, params_dict=None, projection=None): ...\n def find_one(self, params_dict=None, projection=None): ...\n def _get_columns_list(self, projection): ...\n def _does_projection_use_inclusion(projection): ...\n def _get_columns_by_inclusion(self, projection): ...\n def _get_columns_by_exlusion(self, projection): ...\n def _get_command_and_values(self, params_dict, columns_list): ...\n def _has_non_existent_columns(self, params_dict): ...\n def _get_select_statement(self, columns_list): ...\n def _get_statement_and_values_for_where(self, params_dict): ...\n def _get_inequality_data(inequality_info): ...\n def _make_dict(self, keys, values): ...\n def _change_id_key(self, answer): ...\n def insert(self, document): ...\n def _insert_command_and_values(self, document, id_to_return): ...\n def _update_columns(self, document): ...\n def _add_column(self, column, value): ...\n def reset_collection(self): ...\n def _drop_indices(self): ...\n def close(self): ...\n def create_index(self, columns_tuple): ...\n def has_index(self, columns_tuple): ...\n def save_to_target(self, db_name): ...\n def load_from_target(self, db_name): ...\n\n self._path = db_path\n self._collection = collection_name\n self._connection = lite.connect(self._path, detect_types=lite.PARSE_DECLTYPES)\n self._cursor = self._connection.cursor()\n self._in_memory = InMemoryInformation(self)\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_InMemoryDropCollection", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002404.py"} {"focal_file": "dicetables_db/tools/dbprep.py", "focal_class": null, "focal_method": "get_score", "tests": "import unittest\n\nclass Test_get_score(unittest.TestCase):\n def test_get_score_empty(self):\n self.assertEqual(prep.get_score([]), 0)\n\n def test_get_score_one(self):\n self.assertEqual(prep.get_score([(dt.ModDie(3, 10), 4)]), 12)\n\n def test_get_score_multiple(self):\n self.assertEqual(prep.get_score([(dt.WeightedDie({1: 1, 5: 6}), 4), (dt.ModDie(3, 10), 4)]), 36)\n", "method_code": "def get_score(dice_list: list) -> int:\n score = 0\n for die, num in dice_list:\n size = die.get_size()\n if die.get_weight() > size:\n size += 1\n score += size * num\n return score", "context": "def get_score(dice_list: list) -> int: ...\ndef get_score(dice_list: list) -> int: ...\ndef get_label_list(dice_list: list) -> List[Tuple[str, int]]: ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_get_score_empty", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002405.py"} {"focal_file": "dicetables_db/tools/dbprep.py", "focal_class": null, "focal_method": "get_label_list", "tests": "import unittest\n\nclass Test_get_label_list(unittest.TestCase):\n def test_get_label_list(self):\n self.assertEqual(prep.get_label_list([]), [])\n self.assertEqual(prep.get_label_list([(dt.Die(3), 2)]), [('Die(3)', 2)])\n self.assertEqual(prep.get_label_list([(dt.Die(3), 2), (dt.WeightedDie({2: 2}), 1)]), [('Die(3)', 2), ('WeightedDie({1: 0, 2: 2})', 1)])\n", "method_code": "def get_label_list(dice_list: list) -> List[Tuple[str, int]]:\n return [(repr(die), num) for die, num in dice_list]", "context": "def get_label_list(dice_list: list) -> List[Tuple[str, int]]: ...\ndef get_score(dice_list: list) -> int: ...\ndef get_label_list(dice_list: list) -> List[Tuple[str, int]]: ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_get_label_list", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002406.py"} {"focal_file": "dicetables_db/tools/dbprep.py", "focal_class": null, "focal_method": "get_group_list", "tests": "import unittest\n\nclass Test_get_group_list(unittest.TestCase):\n def test_PrepDiceTable_get_group_list(self):\n table = dt.DiceTable.new().add_die(dt.Die(2)).add_die(dt.Die(3))\n prepped = prep.PrepDiceTable(table)\n self.assertEqual(prepped.get_group_list(), ['Die(2)', 'Die(3)'])\n", "method_code": " def get_group_list(self) -> List[str]:\n return [repr_num[0] for repr_num in self._label_list]\n ", "context": "class PrepDiceTable(object):\n def get_group_list(self) -> List[str]: ...\n def __init__(self, dice_table: DiceTable) -> None: ...\n def get_score(self) -> int: ...\n def get_serialized(self): ...\n def get_label_list(self) -> List[Tuple[str, int]]: ...\n def get_group(self) -> str: ...\n def get_dict(self): ...\n\n self._serialized = Serializer.serialize(dice_table)\n self._score = get_score(input_list)\n self._label_list = get_label_list(input_list)\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_PrepDiceTable_get_group_list", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002407.py"} {"focal_file": "dicetables_db/tools/dbprep.py", "focal_class": null, "focal_method": "get_group", "tests": "import unittest\n\nclass Test_get_group(unittest.TestCase):\n def test_PrepDiceTable_get_group(self):\n table = dt.DiceTable.new().add_die(dt.Die(2)).add_die(dt.Die(3))\n prepped = prep.PrepDiceTable(table)\n self.assertEqual(prepped.get_group(), 'Die(2)&Die(3)')\n", "method_code": " def get_group(self) -> str:\n return '&'.join(self.get_group_list())\n ", "context": "class PrepDiceTable(object):\n def get_group(self) -> str: ...\n def __init__(self, dice_table: DiceTable) -> None: ...\n def get_score(self) -> int: ...\n def get_serialized(self): ...\n def get_label_list(self) -> List[Tuple[str, int]]: ...\n def get_group_list(self) -> List[str]: ...\n def get_dict(self): ...\n\n self._serialized = Serializer.serialize(dice_table)\n self._score = get_score(input_list)\n self._label_list = get_label_list(input_list)\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_PrepDiceTable_get_group", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002408.py"} {"focal_file": "dicetables_db/tools/dbprep.py", "focal_class": null, "focal_method": "get_dict", "tests": "import unittest\n\nclass Test_get_dict(unittest.TestCase):\n def test_PrepDiceTable_get_dict(self):\n table = dt.DiceTable.new().add_die(dt.Die(2)).add_die(dt.Die(3))\n prepped = prep.PrepDiceTable(table)\n expected = {'group': 'Die(2)&Die(3)', 'score': 5, 'serialized': Serializer.serialize(table), 'Die(2)': 1, 'Die(3)': 1}\n self.assertEqual(prepped.get_dict(), expected)\n", "method_code": " def get_dict(self):\n output = {'group': self.get_group(), 'score': self._score, 'serialized': self._serialized}\n for die_repr, num in self._label_list:\n output[die_repr] = num\n return output\n ", "context": "class PrepDiceTable(object):\n def get_dict(self): ...\n def __init__(self, dice_table: DiceTable) -> None: ...\n def get_score(self) -> int: ...\n def get_serialized(self): ...\n def get_label_list(self) -> List[Tuple[str, int]]: ...\n def get_group_list(self) -> List[str]: ...\n def get_group(self) -> str: ...\n\n self._serialized = Serializer.serialize(dice_table)\n self._score = get_score(input_list)\n self._label_list = get_label_list(input_list)\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_PrepDiceTable_get_dict", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002409.py"} {"focal_file": "dicetables_db/tools/dbprep.py", "focal_class": null, "focal_method": "get_search_params", "tests": "import unittest\n\nclass Test_get_search_params(unittest.TestCase):\n def test_SearchParams_get_search_params(self):\n table_list = [(dt.Die(1), 4), (dt.Die(2), 2), (dt.Die(3), 1)]\n retriever = prep.SearchParams(table_list)\n searcher = retriever.get_search_params()\n self.assertEqual(next(searcher), [('Die(1)&Die(2)&Die(3)', {'Die(1)': 4, 'Die(2)': 2, 'Die(3)': 1})])\n self.assertEqual(next(searcher), [('Die(1)&Die(2)', {'Die(1)': 4, 'Die(2)': 2}), ('Die(1)&Die(3)', {'Die(1)': 4, 'Die(3)': 1}), ('Die(2)&Die(3)', {'Die(2)': 2, 'Die(3)': 1})])\n self.assertEqual(next(searcher), [('Die(1)', {'Die(1)': 4}), ('Die(2)', {'Die(2)': 2}), ('Die(3)', {'Die(3)': 1})])\n self.assertRaises(StopIteration, next, searcher)\n\n def test_SearchParams_get_search_params_stop_iteration(self):\n table_list = [(dt.Die(1), 4), (dt.Die(2), 2), (dt.Die(3), 1)]\n retriever = prep.SearchParams(table_list)\n result = [lst for lst in retriever.get_search_params()]\n self.assertEqual(len(result), 3)\n self.assertEqual(result[0], [('Die(1)&Die(2)&Die(3)', {'Die(1)': 4, 'Die(2)': 2, 'Die(3)': 1})])\n self.assertEqual(result[1], [('Die(1)&Die(2)', {'Die(1)': 4, 'Die(2)': 2}), ('Die(1)&Die(3)', {'Die(1)': 4, 'Die(3)': 1}), ('Die(2)&Die(3)', {'Die(2)': 2, 'Die(3)': 1})])\n self.assertEqual(result[2], [('Die(1)', {'Die(1)': 4}), ('Die(2)', {'Die(2)': 2}), ('Die(3)', {'Die(3)': 1})])\n", "method_code": " def get_search_params(self):\n return self._search_generator()\n ", "context": "class SearchParams(object):\n def get_search_params(self): ...\n def __init__(self, dice_list: list) -> None: ...\n def _search_generator(self): ...\n def get_score(self) -> int: ...\n\n self._score = get_score(dice_list)\n self._labels = get_label_list(dice_list)\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_SearchParams_get_search_params", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002410.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "to_string", "tests": "import unittest\n\nclass Test_to_string(unittest.TestCase):\n def test_to_string(self):\n self.assertIsInstance(DocumentId.new().to_string(), str)\n\n def test_from_string_constructor(self):\n to_test = DocumentId.new()\n expected_equal = DocumentId.from_string(to_test.to_string())\n self.assertEqual(to_test, expected_equal)\n", "method_code": " def to_string(self) -> str:\n return str(self)\n ", "context": "class DocumentId(object):\n def to_string(self) -> str: ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __le__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_to_string", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002411.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "to_bson_id", "tests": "import unittest\n\nclass Test_to_bson_id(unittest.TestCase):\n def test_to_bson_id(self):\n self.assertIsInstance(DocumentId.new().to_bson_id(), ObjectId)\n\n def test_from_bson_id_constructor(self):\n to_test = DocumentId.new()\n expected_equal = DocumentId.from_bson_id(to_test.to_bson_id())\n self.assertEqual(to_test, expected_equal)\n", "method_code": " def to_bson_id(self) -> ObjectId:\n return self._id\n ", "context": "class DocumentId(object):\n def to_bson_id(self) -> ObjectId: ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_string(self) -> str: ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __le__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_to_bson_id", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002412.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "__eq__", "tests": "import unittest\n\nclass Test_eq(unittest.TestCase):\n def test__eq__false(self):\n ne_1 = DocumentId.new()\n ne_2 = DocumentId.new()\n ne_3 = 'hello'\n self.assertFalse(ne_1.__eq__(ne_2))\n self.assertFalse(ne_1.__eq__(ne_3))\n", "method_code": " def __eq__(self, other):\n if not isinstance(other, DocumentId):\n return False\n return self._id == other.to_bson_id()\n ", "context": "class DocumentId(object):\n def __eq__(self, other): ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def to_string(self) -> str: ...\n def __str__(self): ...\n def __repr__(self): ...\n def __ne__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __le__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test__eq__false", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002413.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "__ne__", "tests": "import unittest\n\nclass Test_ne(unittest.TestCase):\n def test__ne__true(self):\n ne_1 = DocumentId.new()\n ne_2 = DocumentId.new()\n ne_3 = 'hello'\n self.assertTrue(ne_1.__ne__(ne_2))\n self.assertTrue(ne_1.__ne__(ne_3))\n\n def test__ne__false(self):\n eq_1 = DocumentId.new()\n eq_2 = DocumentId.from_bson_id(eq_1.to_bson_id())\n self.assertFalse(eq_1.__ne__(eq_2))\n", "method_code": " def __ne__(self, other):\n return not self.__eq__(other)\n ", "context": "class DocumentId(object):\n def __ne__(self, other): ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def to_string(self) -> str: ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __le__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test__ne__true", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002414.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "__lt__", "tests": "import unittest\n\nclass Test_lt(unittest.TestCase):\n def test__lt__true(self):\n small = DocumentId.new()\n large = DocumentId.new()\n self.assertTrue(small.__lt__(large))\n\n def test__lt__false(self):\n small = DocumentId.new()\n small_2 = DocumentId.from_bson_id(small.to_bson_id())\n large = DocumentId.new()\n self.assertFalse(large.__lt__(small))\n self.assertFalse(small.__lt__(small_2))\n", "method_code": " def __lt__(self, other: 'DocumentId'):\n return self._id < other.to_bson_id()\n ", "context": "class DocumentId(object):\n def __lt__(self, other: 'DocumentId'): ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def to_string(self) -> str: ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __le__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test__lt__true", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002415.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "__le__", "tests": "import unittest\n\nclass Test_le(unittest.TestCase):\n def test__le__true(self):\n small = DocumentId.new()\n small_2 = DocumentId.from_bson_id(small.to_bson_id())\n large = DocumentId.new()\n self.assertTrue(small.__le__(large))\n self.assertTrue(small.__le__(small_2))\n\n def test__le__false(self):\n small = DocumentId.new()\n large = DocumentId.new()\n self.assertFalse(large.__le__(small))\n", "method_code": " def __le__(self, other: 'DocumentId'):\n return self._id <= other.to_bson_id()\n ", "context": "class DocumentId(object):\n def __le__(self, other: 'DocumentId'): ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def to_string(self) -> str: ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test__le__true", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002416.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "__gt__", "tests": "import unittest\n\nclass Test_gt(unittest.TestCase):\n def test__gt__true(self):\n small = DocumentId.new()\n large = DocumentId.new()\n self.assertTrue(large.__gt__(small))\n\n def test__gt__false(self):\n small = DocumentId.new()\n small_2 = DocumentId.from_bson_id(small.to_bson_id())\n large = DocumentId.new()\n self.assertFalse(small.__gt__(large))\n self.assertFalse(small.__gt__(small_2))\n", "method_code": " def __gt__(self, other: 'DocumentId'):\n return self._id > other.to_bson_id()\n ", "context": "class DocumentId(object):\n def __gt__(self, other: 'DocumentId'): ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def to_string(self) -> str: ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __le__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test__gt__true", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002417.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "__ge__", "tests": "import unittest\n\nclass Test_ge(unittest.TestCase):\n def test__ge__true(self):\n small = DocumentId.new()\n small_2 = DocumentId.from_bson_id(small.to_bson_id())\n large = DocumentId.new()\n self.assertTrue(large.__ge__(small))\n self.assertTrue(small.__ge__(small_2))\n\n def test__ge__false(self):\n small = DocumentId.new()\n large = DocumentId.new()\n self.assertFalse(small.__ge__(large))\n", "method_code": " def __ge__(self, other: 'DocumentId'):\n return self._id >= other.to_bson_id()\n ", "context": "class DocumentId(object):\n def __ge__(self, other: 'DocumentId'): ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def to_string(self) -> str: ...\n def __str__(self): ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __le__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test__ge__true", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002418.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "__repr__", "tests": "import unittest\n\nclass Test_repr(unittest.TestCase):\n def test__repr__(self):\n new = DocumentId.new()\n new_str = new.to_string()\n self.assertEqual('ObjectId.from_string({})'.format(new_str), new.__repr__())\n", "method_code": " def __repr__(self):\n return 'ObjectId.from_string({})'.format(self)\n ", "context": "class DocumentId(object):\n def __repr__(self): ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def to_string(self) -> str: ...\n def __str__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __le__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test__repr__", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002419.py"} {"focal_file": "dicetables_db/tools/documentid.py", "focal_class": null, "focal_method": "__str__", "tests": "import unittest\n\nclass Test_str(unittest.TestCase):\n def test__str__(self):\n new = DocumentId.new()\n new_str = new.to_string()\n self.assertEqual(new_str, new.__str__())\n", "method_code": " def __str__(self):\n return str(self._id)\n ", "context": "class DocumentId(object):\n def __str__(self): ...\n def __init__(self, obj_id: ObjectId): ...\n def new(cls) -> 'DocumentId': ...\n def from_string(cls, input_string: str) -> 'DocumentId': ...\n def from_bson_id(cls, bson_id: ObjectId) -> 'DocumentId': ...\n def to_bson_id(self) -> ObjectId: ...\n def to_string(self) -> str: ...\n def __repr__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __lt__(self, other: 'DocumentId'): ...\n def __le__(self, other: 'DocumentId'): ...\n def __gt__(self, other: 'DocumentId'): ...\n def __ge__(self, other: 'DocumentId'): ...\n\n self._id = obj_id\n", "repository": "eric-s-s/dicetables_db", "test_name": "test__str__", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002420.py"} {"focal_file": "dicetables_db/tools/serializer.py", "focal_class": null, "focal_method": "serialize", "tests": "import unittest\n\nclass Test_serialize(unittest.TestCase):\n def test_Serializer_serialize(self):\n self.assertEqual(Serializer.serialize(12), pickle.dumps(12))\n", "method_code": " def serialize(thing) -> bytes:\n return pickle.dumps(thing)\n ", "context": "class Serializer(object):\n @staticmethod\n def serialize(thing) -> bytes: ...\n def deserialize(data: bytes): ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_Serializer_serialize", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002421.py"} {"focal_file": "dicetables_db/tools/serializer.py", "focal_class": null, "focal_method": "deserialize", "tests": "import unittest\n\nclass Test_deserialize(unittest.TestCase):\n def test_Serializer_deserialize(self):\n data = Serializer.serialize(12)\n self.assertNotEqual(data, 12)\n self.assertEqual(Serializer.deserialize(data), 12)\n", "method_code": " def deserialize(data: bytes):\n return pickle.loads(data)\n ", "context": "class Serializer(object):\n @staticmethod\n def deserialize(data: bytes): ...\n def serialize(thing) -> bytes: ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_Serializer_deserialize", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002422.py"} {"focal_file": "dicetables_db/tools/tasktools.py", "focal_class": null, "focal_method": "get_die_step", "tests": "import unittest\n\nclass Test_get_die_step(unittest.TestCase):\n def test_get_die_step_perfect_fit(self):\n self.assertEqual(get_die_step(Die(6), 24), 4)\n also_six = StrongDie(ModDie(6, -1), 5)\n self.assertEqual(get_die_step(also_six, 24), 4)\n\n def test_get_die_step_imperfect_fit(self):\n self.assertEqual(get_die_step(Die(7), 24), 3)\n also_seven = StrongDie(WeightedDie({roll: roll for roll in range(1, 8)}), 3)\n self.assertEqual(get_die_step(also_seven, 24), 3)\n", "method_code": "def get_die_step(die: ProtoDie, step_size: int) -> int:\n dict_len = len(die.get_dict())\n return max(1, step_size // dict_len)", "context": "def get_die_step(die: ProtoDie, step_size: int) -> int: ...\ndef extract_modifiers(dice_record: DiceRecord) -> Tuple[int, DiceRecord]: ...\ndef apply_modifier(initial_table: DiceTable, modifier: int) -> DiceTable: ...\ndef is_new_table(table: DiceTable) -> bool: ...\ndef get_die_step(die: ProtoDie, step_size: int) -> int: ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_get_die_step_perfect_fit", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002423.py"} {"focal_file": "dicetables_db/tools/tasktools.py", "focal_class": null, "focal_method": "is_new_table", "tests": "import unittest\n\nclass Test_is_new_table(unittest.TestCase):\n def test_is_new_table(self):\n new = DiceTable.new()\n not_new = new.add_die(Die(3))\n self.assertTrue(is_new_table(new))\n self.assertFalse(is_new_table(not_new))\n", "method_code": "def is_new_table(table: DiceTable) -> bool:\n return table == DiceTable.new()", "context": "def is_new_table(table: DiceTable) -> bool: ...\ndef extract_modifiers(dice_record: DiceRecord) -> Tuple[int, DiceRecord]: ...\ndef apply_modifier(initial_table: DiceTable, modifier: int) -> DiceTable: ...\ndef is_new_table(table: DiceTable) -> bool: ...\ndef get_die_step(die: ProtoDie, step_size: int) -> int: ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_is_new_table", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002424.py"} {"focal_file": "dicetables_db/tools/tasktools.py", "focal_class": "TableGenerator", "focal_method": "create_save_list", "tests": "import unittest\n\nclass Test_TableGenerator_create_save_list(unittest.TestCase):\n def test_TableGenerator_create_save_list_hits_target(self):\n initial = DiceTable.new()\n target = DiceRecord({Die(5): 6})\n step_size = 10\n save_list = TableGenerator(target).create_save_list(initial, step_size)\n expected = [initial.add_die(Die(5), 2), initial.add_die(Die(5), 4), initial.add_die(Die(5), 6)]\n self.assertEqual(save_list, expected)\n self.assertEqual(save_list[-1].dice_data(), target)\n\n def test_TableGenerator_create_save_list_does_not_hit_target(self):\n new = DiceTable.new()\n initial = new.add_die(Die(5))\n self.assertEqual(initial.number_of_dice(Die(5)), 1)\n target = DiceRecord({Die(5): 6})\n step_size = 10\n save_list = TableGenerator(target).create_save_list(initial, step_size)\n expected = [new.add_die(Die(5), 3), new.add_die(Die(5), 5)]\n self.assertEqual(save_list, expected)\n self.assertEqual(save_list[-1].dice_data(), DiceRecord({Die(5): 5}))\n\n def test_TableGenerator_create_save_list_one_type_of_dice_already_at_target(self):\n target = DiceRecord({Die(2): 4, Die(4): 2})\n step_size = 4\n initial = DiceTable.new().add_die(Die(2), 4)\n four_d2_one_d4 = initial.add_die(Die(4))\n four_d2_two_d4 = four_d2_one_d4.add_die(Die(4))\n save_list = TableGenerator(target).create_save_list(initial, step_size)\n expected = [four_d2_one_d4, four_d2_two_d4]\n self.assertEqual(save_list, expected)\n self.assertEqual(save_list[-1].dice_data(), target)\n\n def test_TableGenerator_create_save_list_empty_return(self):\n target = DiceRecord({Die(2): 4, Die(4): 2})\n step_size = 4\n initial = DiceTable.new().add_die(Die(2), 3).add_die(Die(4), 2)\n self.assertEqual(TableGenerator(target).create_save_list(initial, step_size), [])\n\n def test_TableGenerator_create_save_list_die_much_larger_than_step_size(self):\n target = DiceRecord({Die(2): 4, Die(40): 2})\n step_size = 4\n initial = DiceTable.new().add_die(Die(2), 3)\n expected = [initial.add_die(Die(40)), initial.add_die(Die(40), 2)]\n save_list = TableGenerator(target).create_save_list(initial, step_size)\n self.assertEqual(expected, save_list)\n self.assertEqual(save_list[-1].dice_data(), DiceRecord({Die(2): 3, Die(40): 2}))\n\n def test_TableGenerator_create_save_list_with_queue_empty_return(self):\n q = Queue()\n target = DiceRecord({Die(6): 11})\n initial = DiceTable.new().add_die(Die(6), 10)\n TableGenerator(target).create_save_list(initial, 30, q)\n self.assertEqual(q.get(), 'STOP')\n\n def test_TableGenerator_create_save_list_with_queue(self):\n q = Queue()\n target = DiceRecord({Die(6): 8})\n initial = DiceTable.new().add_die(Die(6), 5)\n TableGenerator(target).create_save_list(initial, 1, q)\n expected = ['', '', '']\n for repr_str in expected:\n value = q.get()\n self.assertEqual(value, repr_str)\n self.assertEqual(q.get(), 'STOP')\n", "method_code": " def create_save_list(self, initial_table: DiceTable, step_size: int, update_queue: Queue=None) -> List[DiceTable]:\n saves = []\n newest_table = initial_table\n ordered_list = sorted(self._target.get_dict().items())\n for die, target_num in ordered_list:\n die_step = get_die_step(die, step_size)\n current_die_number = newest_table.number_of_dice(die)\n add_times = (target_num - current_die_number) // die_step\n for _ in range(add_times):\n newest_table = newest_table.add_die(die, die_step)\n saves.append(newest_table)\n if update_queue is not None:\n update_queue.put(repr(newest_table))\n if update_queue is not None:\n update_queue.put('STOP')\n return saves\n ", "context": "class TableGenerator(object):\n def create_save_list(self, initial_table: DiceTable, step_size: int, update_queue: Queue=None) -> List[DiceTable]: ...\n def __init__(self, target_record: DiceRecord) -> None: ...\n def create_target_table(self, initial_table: DiceTable) -> DiceTable: ...\n\n self._target = target_record\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_TableGenerator_create_save_list_hits_target", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002425.py"} {"focal_file": "dicetables_db/tools/tasktools.py", "focal_class": "TableGenerator", "focal_method": "create_target_table", "tests": "import unittest\n\nclass Test_TableGenerator_create_target_table(unittest.TestCase):\n def test_TableGenerator_create_target_table_initial_is_target(self):\n target = DiceRecord({Die(2): 4, Die(4): 3})\n initial = DiceTable.new().add_die(Die(2), 4).add_die(Die(4), 3)\n self.assertEqual(initial, TableGenerator(target).create_target_table(initial))\n\n def test_TableGenerator_create_target_table_initial_is_intermediary(self):\n target = DiceRecord({Die(2): 4, Die(4): 3})\n initial = DiceTable.new().add_die(Die(2)).add_die(Die(4))\n self.assertEqual(initial.dice_data(), DiceRecord({Die(2): 1, Die(4): 1}))\n expected = DiceTable.new().add_die(Die(2), 4).add_die(Die(4), 3)\n self.assertEqual(expected, TableGenerator(target).create_target_table(initial))\n\n def test_TableGenerator_create_target_table_LIMITATION_initial_contains_dice_not_in_target(self):\n target = DiceRecord({Die(2): 4, Die(4): 3})\n initial = DiceTable.new().add_die(Die(2)).add_die(Die(5))\n self.assertEqual(initial.dice_data(), DiceRecord({Die(2): 1, Die(5): 1}))\n expected = DiceTable.new().add_die(Die(2), 4).add_die(Die(4), 3)\n self.assertNotEqual(expected, TableGenerator(target).create_target_table(initial))\n", "method_code": " def create_target_table(self, initial_table: DiceTable) -> DiceTable:\n new_table = initial_table\n for die, number in self._target.get_dict().items():\n to_add = number - new_table.number_of_dice(die)\n new_table = new_table.add_die(die, to_add)\n return new_table\n ", "context": "class TableGenerator(object):\n def create_target_table(self, initial_table: DiceTable) -> DiceTable: ...\n def __init__(self, target_record: DiceRecord) -> None: ...\n def create_save_list(self, initial_table: DiceTable, step_size: int, update_queue: Queue=None) -> List[DiceTable]: ...\n\n self._target = target_record\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_TableGenerator_create_target_table_initial_is_target", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002426.py"} {"focal_file": "dicetables_db/tools/tasktools.py", "focal_class": null, "focal_method": "extract_modifiers", "tests": "import unittest\n\nclass Test_extract_modifiers(unittest.TestCase):\n def test_extract_modifiers_no_modifiers(self):\n die = Die(6)\n weighted = WeightedDie({1: 2, 3: 4})\n dice = DiceRecord({die: 3, weighted: 4, StrongDie(die, 3): 5, ExplodingOn(die, (1,)): 6, Exploding(weighted): 10})\n self.assertEqual(extract_modifiers(dice), (0, dice))\n\n def test_extract_modifiers_on_Modifier(self):\n dice = DiceRecord({Modifier(5): 3})\n self.assertEqual(extract_modifiers(dice), (15, DiceRecord.new()))\n dice = DiceRecord({Modifier(-5): 3})\n self.assertEqual(extract_modifiers(dice), (-15, DiceRecord.new()))\n\n def test_extract_modifiers_on_ModDie(self):\n dice = DiceRecord({ModDie(6, 5): 4})\n self.assertEqual(extract_modifiers(dice), (20, DiceRecord({Die(6): 4})))\n dice = DiceRecord({ModDie(6, -5): 4})\n self.assertEqual(extract_modifiers(dice), (-20, DiceRecord({Die(6): 4})))\n\n def test_extract_modifiers_on_ModWeightedDie(self):\n die_dict = {roll: roll % 3 for roll in range(1, 10)}\n dice = DiceRecord({ModWeightedDie(die_dict, 6): 5})\n self.assertEqual(extract_modifiers(dice), (30, DiceRecord({WeightedDie(die_dict): 5})))\n dice = DiceRecord({ModWeightedDie(die_dict, -6): 5})\n self.assertEqual(extract_modifiers(dice), (-30, DiceRecord({WeightedDie(die_dict): 5})))\n\n def test_extract_modifiers_many_modifier_dice(self):\n die_dict = {roll: roll % 3 for roll in range(1, 10)}\n dice = DiceRecord({ModDie(6, -5): 4, ModWeightedDie(die_dict, 6): 5, Modifier(-5): 3})\n new_dice = DiceRecord({Die(6): 4, WeightedDie(die_dict): 5})\n self.assertEqual(extract_modifiers(dice), (-20 + 30 + -15, new_dice))\n\n def test_extract_modifiers_many_dice(self):\n die_dict = {roll: roll % 3 for roll in range(1, 10)}\n dice = DiceRecord({ModDie(6, -5): 4, Die(7): 3, ModWeightedDie(die_dict, 6): 5, WeightedDie({1: 2}): 10, Modifier(-5): 3, StrongDie(Die(6), 2): 11})\n dice_no_mods = DiceRecord({Die(6): 4, Die(7): 3, WeightedDie(die_dict): 5, WeightedDie({1: 2}): 10, StrongDie(Die(6), 2): 11})\n self.assertEqual(extract_modifiers(dice), (-20 + 30 + -15, dice_no_mods))\n", "method_code": "def extract_modifiers(dice_record: DiceRecord) -> Tuple[int, DiceRecord]:\n new_record = dice_record\n modifier = 0\n for die, num in dice_record.get_dict().items():\n if isinstance(die, (Modifier, ModDie, ModWeightedDie)):\n new_record = new_record.remove_die(die, num)\n modifier += die.get_modifier() * num\n if isinstance(die, ModDie):\n new_die = Die(die.get_size())\n new_record = new_record.add_die(new_die, num)\n if isinstance(die, ModWeightedDie):\n new_die = WeightedDie(die.get_raw_dict())\n new_record = new_record.add_die(new_die, num)\n return (modifier, new_record)", "context": "def extract_modifiers(dice_record: DiceRecord) -> Tuple[int, DiceRecord]: ...\ndef extract_modifiers(dice_record: DiceRecord) -> Tuple[int, DiceRecord]: ...\ndef apply_modifier(initial_table: DiceTable, modifier: int) -> DiceTable: ...\ndef is_new_table(table: DiceTable) -> bool: ...\ndef get_die_step(die: ProtoDie, step_size: int) -> int: ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_extract_modifiers_no_modifiers", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002427.py"} {"focal_file": "dicetables_db/tools/tasktools.py", "focal_class": null, "focal_method": "apply_modifier", "tests": "import unittest\n\nclass Test_apply_modifier(unittest.TestCase):\n def test_apply_modifier_zero_mod(self):\n table = DiceTable.new().add_die(Die(2)).add_die(Die(3))\n self.assertEqual(table.get_dict(), {2: 1, 3: 2, 4: 2, 5: 1})\n no_mod = apply_modifier(table, 0)\n self.assertEqual(no_mod.get_dict(), table.get_dict())\n self.assertNotEqual(no_mod, table)\n self.assertEqual(no_mod.dice_data(), DiceRecord({Die(2): 1, Die(3): 1, Modifier(0): 1}))\n\n def test_apply_modifier_positive_mod(self):\n table = DiceTable.new().add_die(Die(2)).add_die(Die(3))\n self.assertEqual(table.get_dict(), {2: 1, 3: 2, 4: 2, 5: 1})\n pos_mod = apply_modifier(table, 2)\n expected_dict = {4: 1, 5: 2, 6: 2, 7: 1}\n self.assertEqual(pos_mod.get_dict(), expected_dict)\n self.assertEqual(pos_mod.dice_data(), DiceRecord({Die(2): 1, Die(3): 1, Modifier(2): 1}))\n\n def test_apply_modifier_negative_mod(self):\n table = DiceTable.new().add_die(Die(2)).add_die(Die(3))\n self.assertEqual(table.get_dict(), {2: 1, 3: 2, 4: 2, 5: 1})\n pos_mod = apply_modifier(table, -3)\n expected_dict = {-1: 1, 0: 2, 1: 2, 2: 1}\n self.assertEqual(pos_mod.get_dict(), expected_dict)\n self.assertEqual(pos_mod.dice_data(), DiceRecord({Die(2): 1, Die(3): 1, Modifier(-3): 1}))\n", "method_code": "def apply_modifier(initial_table: DiceTable, modifier: int) -> DiceTable:\n return initial_table.add_die(Modifier(modifier))", "context": "def apply_modifier(initial_table: DiceTable, modifier: int) -> DiceTable: ...\ndef extract_modifiers(dice_record: DiceRecord) -> Tuple[int, DiceRecord]: ...\ndef apply_modifier(initial_table: DiceTable, modifier: int) -> DiceTable: ...\ndef is_new_table(table: DiceTable) -> bool: ...\ndef get_die_step(die: ProtoDie, step_size: int) -> int: ...\n", "repository": "eric-s-s/dicetables_db", "test_name": "test_apply_modifier_zero_mod", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002428.py"} {"focal_file": "src/penomazefiles/maze.py", "focal_class": null, "focal_method": "get_boundingbox", "tests": "import unittest\n\nclass Test_get_boundingbox(unittest.TestCase):\n def test_get_boundingbox(self):\n maze1 = Maze()\n maze1.add_tile((0, 0), tiles.Straight(0))\n maze1.add_tile((1, 0), tiles.Corner(1))\n maze1.add_tile((0, 1), tiles.T(2))\n maze1.add_tile((1, 1), tiles.Closed())\n self.assertEqual(maze1.get_boundingbox(), ((0, 0), (2, 2)))\n", "method_code": " def get_boundingbox(self):\n \"\"\"\n compute a bounding box of the current maze.\n \n Returns a tuple of coordinates (lu, rl). lu is the coordinate of the\n left upper point of the bounding box while rl is the coordinate of the\n right lower point of the bounding box\n \"\"\"\n tile_iterator = iter(self)\n coordinate, tile = next(tile_iterator)\n assert tile is not None\n min_x = coordinate[0]\n max_x = min_x + 1\n min_y = coordinate[1]\n max_y = min_y + 1\n for coordinate, tile in tile_iterator:\n if coordinate[0] < min_x:\n min_x = coordinate[0]\n if coordinate[0] + 1 > max_x:\n max_x = coordinate[0] + 1\n if coordinate[1] < min_y:\n min_y = coordinate[1]\n if coordinate[1] + 1 > max_y:\n max_y = coordinate[1] + 1\n return ((min_x, min_y), (max_x, max_y))\n ", "context": "class Maze(object):\n def get_boundingbox(self): ...\n def __init__(self): ...\n def add_tile(self, coordinate, tile): ...\n def get_tile(self, coordinate): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __iter__(self): ...\n\n self._maze = {}\n", "repository": "jeroendv/PenOMazefiles", "test_name": "test_get_boundingbox", "smells": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002429.py"} {"focal_file": "src/penomazefiles/mazefileparser.py", "focal_class": null, "focal_method": "start", "tests": "import unittest\n\nclass Test_start(unittest.TestCase):\n def test_withTokenizer(self):\n \"\"\"docstring for # string list corresponding the lines of apossible m\"\"\"\n tokenizer = MazeFileTokenizer(self.input_linelist)\n parser = MazeFileParser()\n tokenizer.addTokenConsumer(parser.consumeToken)\n outputlist = []\n parser.add_token_parser(outputlist.append)\n tokenizer.start()\n self.assertListEqual(outputlist, self.true_outputlist)\n", "method_code": " def start(self):\n \"\"\"\n Process the stream of text lines producing a sequence of tokens that \n are to be processed by the consumer.\n \"\"\"\n if self.token_consumer is None:\n return\n lineNb = 0\n for line in self.stream:\n lineNb += 1\n comment_start_index = line.find('#')\n if comment_start_index != -1:\n line = line[0:comment_start_index]\n line = line.strip()\n if len(line) == 0:\n continue\n tokens = line.split()\n tokenNb = 0\n for token in tokens:\n tokenNb += 1\n try:\n self.token_consumer(token)\n except SpecificationViolationError as e:\n e.line_nb = lineNb\n e.token_nb = tokenNb\n e.token_value = token\n print('line number: {:d}'.format(lineNb))\n print('line value: {!r}'.format(line))\n print('token number: {:d}'.format(tokenNb))\n print('{!s}'.format(e.args))\n raise\n ", "context": "class MazeFileTokenizer(object):\n def start(self): ...\n def __init__(self, stream): ...\n def addTokenConsumer(self, token_consumer): ...\n\n self.stream = stream\n\n token_consumer = None\n stream = None\n", "repository": "jeroendv/PenOMazefiles", "test_name": "test_withTokenizer", "smells": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002430.py"} {"focal_file": "src/penomazefiles/mazefileparser.py", "focal_class": null, "focal_method": "MazeFileBuilder", "tests": "import unittest\n\nclass Test_MazeFileBuilder(unittest.TestCase):\n def test_mazebuilder(self):\n maze = MazeFileBuilder(self.input_linelist)\n self.assertEqual(maze, self.true_maze)\n", "method_code": "def MazeFileBuilder(stream):\n \"\"\"\n Parse a stream of lines to build a Maze object\n\n Return a Maze \n \"\"\"\n token_stream = MazeFileTokenizer(stream)\n mazefile_parser = MazeFileParser()\n token_stream.addTokenConsumer(mazefile_parser.consumeToken)\n mazetoken_parser = MazeTokenParser()\n mazefile_parser.add_token_parser(mazetoken_parser.consume)\n token_stream.start()\n return mazetoken_parser.getMaze()", "context": "def MazeFileBuilder(stream): ...\ndef MazeFileBuilder(stream): ...\n", "repository": "jeroendv/PenOMazefiles", "test_name": "test_mazebuilder", "smells": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002431.py"} {"focal_file": "enumerable/__init__.py", "focal_class": null, "focal_method": "empty", "tests": "import unittest\n\nclass Test_empty(unittest.TestCase):\n def test_take_empty(self):\n e = Enumerable.empty()\n result = list(e.take(3))\n expected_result = []\n self.assertListEqual(result, expected_result)\n\n def test_select_empty(self):\n e = Enumerable.empty()\n result = e.select(lambda x: x / 3).to_list()\n self.assertListEqual(result, [])\n\n def test_any_empty(self):\n e = Enumerable.empty()\n result = e.any(lambda x: False)\n self.assertFalse(result)\n\n def test_select_many_empty(self):\n e = Enumerable.empty()\n result = e.select_many().to_list()\n self.assertListEqual(result, [])\n\n def test_all_empty(self):\n e = Enumerable.empty()\n result = e.all(lambda x: False)\n self.assertTrue(result)\n", "method_code": " def empty():\n \n def gen():\n return\n yield\n return Enumerable(gen())\n ", "context": "class Enumerable():\n @staticmethod\n def empty(): ...\n def __init__(self, iterable): ...\n def __iter__(self): ...\n def __next__(self): ...\n def count(self, predicate=lambda x: True): ...\n def first(self, predicate=lambda x: True, default=None): ...\n def last(self, predicate=lambda x: True, default=None): ...\n def single(self, predicate=lambda x: True): ...\n def any(self, predicate=lambda x: True): ...\n def all(self, predicate): ...\n def sum(self, selector=lambda x: x): ...\n def avg(self, selector=lambda x: x): ...\n def max(self, selector=lambda x: x): ...\n def min(self, selector=lambda x: x): ...\n def select_many(self, selector=lambda x: x): ...\n def where(self, predicate=None): ...\n def select(self, projector): ...\n def take(self, count): ...\n def skip(self, count): ...\n def take_while(self, predicate): ...\n def skip_while(self, predicate): ...\n def group_by(self, key_selector): ...\n def to_list(self): ...\n def to_dict(self, key_func, value_func): ...\n\n self._iter = iter(iterable)\n", "repository": "omri85/enumerable", "test_name": "test_take_empty", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002432.py"} {"focal_file": "enumerable/__init__.py", "focal_class": "Enumerable", "focal_method": "to_list", "tests": "import unittest\n\nclass Test_Enumerable_to_list(unittest.TestCase):\n def test_select_to_list(self):\n e = Enumerable(range(5))\n result = e.select(lambda x: x * 2).to_list()\n self.assertListEqual(result, [0, 2, 4, 6, 8])\n\n def test_select_many_deafult_selector(self):\n e = Enumerable([range(3) for i in range(3)])\n result = e.select_many().to_list()\n self.assertListEqual(result, [0, 1, 2, 0, 1, 2, 0, 1, 2])\n\n def test_select_many_empty_sub_collections(self):\n e = Enumerable([[], [], {}, (), range(0)])\n result = e.select_many().to_list()\n self.assertListEqual(result, [])\n\n def test_select_many_empty_list(self):\n e = Enumerable([])\n result = e.select_many().to_list()\n self.assertListEqual(result, [])\n", "method_code": " def to_list(self):\n \"\"\"Enumerates the collection to a list\"\"\"\n return list(self)\n ", "context": "class Enumerable():\n def to_list(self): ...\n def __init__(self, iterable): ...\n def __iter__(self): ...\n def __next__(self): ...\n def count(self, predicate=lambda x: True): ...\n def first(self, predicate=lambda x: True, default=None): ...\n def last(self, predicate=lambda x: True, default=None): ...\n def single(self, predicate=lambda x: True): ...\n def any(self, predicate=lambda x: True): ...\n def all(self, predicate): ...\n def sum(self, selector=lambda x: x): ...\n def avg(self, selector=lambda x: x): ...\n def max(self, selector=lambda x: x): ...\n def min(self, selector=lambda x: x): ...\n def select_many(self, selector=lambda x: x): ...\n def where(self, predicate=None): ...\n def select(self, projector): ...\n def take(self, count): ...\n def skip(self, count): ...\n def take_while(self, predicate): ...\n def skip_while(self, predicate): ...\n def group_by(self, key_selector): ...\n def to_dict(self, key_func, value_func): ...\n def empty(): ...\n\n self._iter = iter(iterable)\n", "repository": "omri85/enumerable", "test_name": "test_select_to_list", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002433.py"} {"focal_file": "enumerable/__init__.py", "focal_class": "Enumerable", "focal_method": "to_dict", "tests": "import unittest\n\nclass Test_Enumerable_to_dict(unittest.TestCase):\n def test_select_to_dict(self):\n e = Enumerable(range(1, 4))\n result = e.select(lambda x: 'a' * x).to_dict(lambda x: x, lambda x: len(x))\n self.assertDictEqual(result, {'a': 1, 'aa': 2, 'aaa': 3})\n", "method_code": " def to_dict(self, key_func, value_func):\n \"\"\"Enumerates to collection to a dictionary according to the key and\n value functions\"\"\"\n return {key_func(item): value_func(item) for item in self}\n ", "context": "class Enumerable():\n def to_dict(self, key_func, value_func): ...\n def __init__(self, iterable): ...\n def __iter__(self): ...\n def __next__(self): ...\n def count(self, predicate=lambda x: True): ...\n def first(self, predicate=lambda x: True, default=None): ...\n def last(self, predicate=lambda x: True, default=None): ...\n def single(self, predicate=lambda x: True): ...\n def any(self, predicate=lambda x: True): ...\n def all(self, predicate): ...\n def sum(self, selector=lambda x: x): ...\n def avg(self, selector=lambda x: x): ...\n def max(self, selector=lambda x: x): ...\n def min(self, selector=lambda x: x): ...\n def select_many(self, selector=lambda x: x): ...\n def where(self, predicate=None): ...\n def select(self, projector): ...\n def take(self, count): ...\n def skip(self, count): ...\n def take_while(self, predicate): ...\n def skip_while(self, predicate): ...\n def group_by(self, key_selector): ...\n def to_list(self): ...\n def empty(): ...\n\n self._iter = iter(iterable)\n", "repository": "omri85/enumerable", "test_name": "test_select_to_dict", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002434.py"} {"focal_file": "enumerable/__init__.py", "focal_class": "Enumerable", "focal_method": "select_many", "tests": "import unittest\n\nclass Test_Enumerable_select_many(unittest.TestCase):\n def test_select_many_with_selector(self):\n e = Enumerable([('a', [1, 2]), ('b', [3, 4])])\n result = e.select_many(lambda x: x[1]).to_list()\n self.assertListEqual(result, [1, 2, 3, 4])\n", "method_code": " def select_many(self, selector=lambda x: x):\n \"\"\"Flattens the collection of collection to on collections\"\"\"\n \n def gen():\n for sub_collection in self:\n yield from selector(sub_collection)\n return Enumerable(gen())\n ", "context": "class Enumerable():\n def select_many(self, selector=lambda x: x): ...\n def __init__(self, iterable): ...\n def __iter__(self): ...\n def __next__(self): ...\n def count(self, predicate=lambda x: True): ...\n def first(self, predicate=lambda x: True, default=None): ...\n def last(self, predicate=lambda x: True, default=None): ...\n def single(self, predicate=lambda x: True): ...\n def any(self, predicate=lambda x: True): ...\n def all(self, predicate): ...\n def sum(self, selector=lambda x: x): ...\n def avg(self, selector=lambda x: x): ...\n def max(self, selector=lambda x: x): ...\n def min(self, selector=lambda x: x): ...\n def where(self, predicate=None): ...\n def select(self, projector): ...\n def take(self, count): ...\n def skip(self, count): ...\n def take_while(self, predicate): ...\n def skip_while(self, predicate): ...\n def group_by(self, key_selector): ...\n def to_list(self): ...\n def to_dict(self, key_func, value_func): ...\n def empty(): ...\n\n self._iter = iter(iterable)\n", "repository": "omri85/enumerable", "test_name": "test_select_many_with_selector", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002435.py"} {"focal_file": "trading_system/api/bitfinex/accounts.py", "focal_class": null, "focal_method": "get_balance", "tests": "import unittest\n\nclass Test_get_balance(unittest.TestCase):\n @mock.patch('bitfinex.client.TradeClient.balances', return_value=[{'type': 'deposit', 'currency': 'btc', 'amount': '1.0', 'available': '1.0'}, {'type': 'deposit', 'currency': 'usd', 'amount': '100.0', 'available': '100.0'}, {'type': 'exchange', 'currency': 'btc', 'amount': '2', 'available': '1'}, {'type': 'exchange', 'currency': 'usd', 'amount': '200', 'available': '200'}, {'type': 'trading', 'currency': 'btc', 'amount': '3', 'available': '3'}, {'type': 'trading', 'currency': 'usd', 'amount': '300', 'available': '300'}])\n def test_it_get_balance(self, _):\n my_current_balance = self.accounts.get_balance()\n self.assertIsInstance(my_current_balance, Balance)\n self.assertEqual(my_current_balance.currency, 200.0)\n self.assertEqual(my_current_balance.currency_locked, 0.0)\n self.assertEqual(my_current_balance.btc, 1.0)\n self.assertEqual(my_current_balance.btc_locked, 1.0)\n", "method_code": " def get_balance(self):\n balance = self.client.auth_api.balances()\n return self._make_balance(balance)\n ", "context": "class BitfinexAccountApi(IAccountApi):\n def get_balance(self): ...\n def __init__(self, client): ...\n def _make_balance(self, balance_list): ...\n def _get_currency_balance(balance_list, currency): ...\n def _get_available_amount(balance): ...\n def _get_locked_amount(balance): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002436.py"} {"focal_file": "trading_system/api/bitfinex/markets.py", "focal_class": null, "focal_method": "get_ticker", "tests": "import unittest\n\nclass Test_get_ticker(unittest.TestCase):\n def test_it_get_ticker(self):\n self.market_api.client.open_api.ticker = mock.Mock(return_value={'mid': '245.0', 'bid': '245.0', 'timestamp': '1444253422', 'last_price': '250.0', 'ask': '246.0'})\n self.market_api.client.open_api.today = mock.Mock(return_value={'low': '240.0', 'high': '250.0', 'volume': '1000.0'})\n ticker = self.market_api.get_ticker()\n self.assertIsInstance(ticker, beans.Ticker)\n self.assertEqual(ticker.highest_value, 250.0)\n self.assertEqual(ticker.volume_btc, 1000.0)\n self.assertEqual(ticker.best_buy_order, 245.0)\n self.assertEqual(ticker.last_value, 250.0)\n self.assertEqual(ticker.lowest_value, 240.0)\n self.assertEqual(ticker.best_sell_order, 246.0)\n self.assertEqual(ticker.volume_currency, 250000.0)\n", "method_code": " def get_ticker(self):\n ticker = self.client.open_api.ticker(self.client.symbol)\n today = self.client.open_api.today(self.client.symbol)\n return beans.Ticker(currency_pair=self.client.symbol, last_value=float(ticker.get('last_price')), highest_value=float(today.get('high')), lowest_value=float(today.get('low')), best_sell_order=float(ticker.get('ask')), best_buy_order=float(ticker.get('bid')), volume_btc=float(today.get('volume')), volume_currency=float(today.get('volume', 0)) * float(ticker.get('last_price', 0)))\n ", "context": "class BitfinexMarketApi(IMarketApi):\n def get_ticker(self): ...\n def __init__(self, client): ...\n def get_order_book(self): ...\n def get_trade_list(self, offset=3600): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_get_ticker", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002437.py"} {"focal_file": "trading_system/api/bitfinex/markets.py", "focal_class": null, "focal_method": "get_order_book", "tests": "import unittest\n\nclass Test_get_order_book(unittest.TestCase):\n def test_it_get_order_book(self):\n self.market_api.client.open_api.order_book = mock.Mock(return_value={'bids': [{'price': '500.0', 'amount': '1.5', 'timestamp': '1395557729.0'}], 'asks': [{'price': '600.0', 'amount': '2.5', 'timestamp': '1395557711.0'}]})\n order_book = self.market_api.get_order_book()\n self.assertIsInstance(order_book, beans.OrderBook)\n self.assertIsInstance(order_book.bids, list)\n self.assertIsInstance(order_book.bids[0], beans.OrderInBook)\n self.assertEqual(order_book.bids[0].price, 500.0)\n self.assertEqual(order_book.bids[0].amount, 1.5)\n self.assertIsNone(order_book.bids[0].user_id)\n self.assertIsInstance(order_book.asks, list)\n self.assertIsInstance(order_book.asks[0], beans.OrderInBook)\n self.assertEqual(order_book.asks[0].price, 600.0)\n self.assertEqual(order_book.asks[0].amount, 2.5)\n self.assertIsNone(order_book.asks[0].user_id)\n", "method_code": " def get_order_book(self):\n response = self.client.open_api.order_book(self.client.symbol, parameters={'limit_bids': 2, 'limit_asks': 2})\n return beans.OrderBook(currency_pair=self.client.symbol, bids=[beans.OrderInBook(price=float(bid['price']), amount=float(bid['amount']), user_id=None) for bid in response.get('bids')], asks=[beans.OrderInBook(price=float(ask['price']), amount=float(ask['amount']), user_id=None) for ask in response.get('asks')])\n ", "context": "class BitfinexMarketApi(IMarketApi):\n def get_order_book(self): ...\n def __init__(self, client): ...\n def get_ticker(self): ...\n def get_trade_list(self, offset=3600): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_get_order_book", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002438.py"} {"focal_file": "trading_system/api/bitfinex/markets.py", "focal_class": null, "focal_method": "get_trade_list", "tests": "import unittest\n\nclass Test_get_trade_list(unittest.TestCase):\n def test_it_get_trades(self):\n self.market_api.client.open_api._get = mock.Mock(return_value=[{'timestamp': 1444266681, 'tid': 1000, 'price': '500.0', 'amount': '1.5', 'exchange': 'bitfinex', 'type': 'sell'}])\n trade_list = self.market_api.get_trade_list()\n self.assertIsInstance(trade_list, list)\n self.assertIsInstance(trade_list[0], beans.Trade)\n self.assertEqual(trade_list[0].transaction_id, 1000)\n self.assertEqual(trade_list[0].date, 1444266681)\n self.assertEqual(trade_list[0].price, 500.0)\n self.assertEqual(trade_list[0].amount, 1.5)\n self.assertEqual(trade_list[0].side, consts.OrderSide.SELL)\n", "method_code": " def get_trade_list(self, offset=3600):\n trades = self.client.open_api._get(self.client.open_api.url_for('trades/%s', path_arg=self.client.symbol, parameters={'timestamp': int(time()) - offset}))\n return [beans.Trade(transaction_id=int(trade.get('tid')), date=int(trade.get('timestamp')), price=float(trade.get('price')), amount=float(trade.get('amount')), side=trade.get('type')) for trade in trades]\n ", "context": "class BitfinexMarketApi(IMarketApi):\n def get_trade_list(self, offset=3600): ...\n def __init__(self, client): ...\n def get_ticker(self): ...\n def get_order_book(self): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_get_trades", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002439.py"} {"focal_file": "trading_system/api/bitfinex/orders.py", "focal_class": null, "focal_method": "buy_bitcoins_with_limited_order", "tests": "import unittest\n\nclass Test_buy_bitcoins_with_limited_order(unittest.TestCase):\n def test_it_places_a_limited_buy_order(self):\n self.orders_api.client.auth_api.place_order = mock.Mock(return_value={'id': 448364249, 'symbol': 'btcusd', 'exchange': 'bitfinex', 'price': '2175.0', 'avg_execution_price': '0.0', 'side': 'buy', 'type': 'exchange limit', 'timestamp': '1444272165.252370982', 'is_live': True, 'is_cancelled': False, 'is_hidden': False, 'was_forced': False, 'original_amount': '0.0313', 'remaining_amount': '0.0313', 'executed_amount': '0.0', 'order_id': 448364249})\n order_response = self.orders_api.buy_bitcoins_with_limited_order(price=2175, quantity=0.0313)\n self.assertIsInstance(order_response, beans.PlacedOrder)\n self.assertEqual(order_response.order_id, '448364249')\n self.assertEqual(order_response.exec_id, '448364249')\n self.assertEqual(order_response.exec_type, self.orders_api.ORDER_TYPE_LIMIT)\n self.assertEqual(order_response.order_status, self.orders_api.ORDER_STATUS_NEW)\n self.assertEqual(order_response.price, 2175.0)\n self.assertEqual(order_response.symbol, consts.Symbol.BTCUSD)\n self.assertEqual(order_response.amount, 0.0313)\n self.assertEqual(order_response.side, consts.OrderSide.BUY)\n self.assertEqual(order_response.client_order_id, '448364249')\n self.assertIsNone(order_response.message_type)\n self.assertIsNone(order_response.order_rejection_reason)\n", "method_code": " def buy_bitcoins_with_limited_order(self, price, quantity):\n side = consts.OrderSide.BUY\n response = self.client.auth_api.place_order(str(quantity), str(price), side, self.ORDER_TYPE_LIMIT)\n return self._make_placed_order_from_response(response)\n ", "context": "class BitfinexOrdersApi(IOrdersApi):\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def cancel_order(self, order_id): ...\n def get_pending_orders(self, page, page_size): ...\n def _make_placed_order_from_response(self, response): ...\n def _get_str_value_or_none(source, key): ...\n def _get_order_status(self, order): ...\n\n self.client = client\n\n ORDER_STATUS_CANCELLED = '4'\n ORDER_STATUS_NEW = '0'\n ORDER_TYPE_LIMIT = 'exchange limit'\n ORDER_TYPE_MARKET = 'exchange market'\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_places_a_limited_buy_order", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002440.py"} {"focal_file": "trading_system/api/bitfinex/orders.py", "focal_class": null, "focal_method": "buy_bitcoins_with_market_order", "tests": "import unittest\n\nclass Test_buy_bitcoins_with_market_order(unittest.TestCase):\n def test_it_places_a_market_buy_order(self):\n self.orders_api.client.auth_api.place_order = mock.Mock(return_value={'order_id': 1026178983, 'id': 1026178983, 'avg_execution_price': '0.0', 'is_cancelled': False, 'remaining_amount': '0.0313', 'exchange': 'bitfinex', 'symbol': 'btcusd', 'was_forced': False, 'is_hidden': False, 'type': 'exchange market', 'oco_order': None, 'price': '0.01', 'executed_amount': '0.0', 'timestamp': '1471637931.800969379', 'is_live': True, 'side': 'buy', 'original_amount': '0.0313'})\n order_response = self.orders_api.buy_bitcoins_with_market_order(quantity=0.0313)\n self.assertIsInstance(order_response, beans.PlacedOrder)\n self.assertEqual(order_response.order_id, '1026178983')\n self.assertEqual(order_response.exec_id, '1026178983')\n self.assertEqual(order_response.exec_type, self.orders_api.ORDER_TYPE_MARKET)\n self.assertEqual(order_response.order_status, self.orders_api.ORDER_STATUS_NEW)\n self.assertEqual(order_response.symbol, consts.Symbol.BTCUSD)\n self.assertEqual(order_response.amount, 0.0313)\n self.assertEqual(order_response.side, consts.OrderSide.BUY)\n self.assertEqual(order_response.client_order_id, '1026178983')\n self.assertIsNone(order_response.message_type)\n self.assertIsNone(order_response.order_rejection_reason)\n", "method_code": " def buy_bitcoins_with_market_order(self, quantity):\n side = consts.OrderSide.BUY\n response = self.client.auth_api.place_order(str(quantity), price='0.01', side=side, ord_type=self.ORDER_TYPE_MARKET)\n return self._make_placed_order_from_response(response)\n ", "context": "class BitfinexOrdersApi(IOrdersApi):\n def buy_bitcoins_with_market_order(self, quantity): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def cancel_order(self, order_id): ...\n def get_pending_orders(self, page, page_size): ...\n def _make_placed_order_from_response(self, response): ...\n def _get_str_value_or_none(source, key): ...\n def _get_order_status(self, order): ...\n\n self.client = client\n\n ORDER_STATUS_CANCELLED = '4'\n ORDER_STATUS_NEW = '0'\n ORDER_TYPE_LIMIT = 'exchange limit'\n ORDER_TYPE_MARKET = 'exchange market'\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_places_a_market_buy_order", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002441.py"} {"focal_file": "trading_system/api/bitfinex/orders.py", "focal_class": null, "focal_method": "sell_bitcoins_with_limited_order", "tests": "import unittest\n\nclass Test_sell_bitcoins_with_limited_order(unittest.TestCase):\n def test_it_places_a_limited_sell_order(self):\n self.orders_api.client.auth_api.place_order = mock.Mock(return_value={'id': 448364249, 'symbol': 'btcusd', 'exchange': 'bitfinex', 'price': '2175.0', 'avg_execution_price': '0.0', 'side': 'sell', 'type': 'exchange limit', 'timestamp': '1444272165.252370982', 'is_live': True, 'is_cancelled': False, 'is_hidden': False, 'was_forced': False, 'original_amount': '0.0313', 'remaining_amount': '0.0313', 'executed_amount': '0.0', 'order_id': 448364249})\n order_response = self.orders_api.sell_bitcoins_with_limited_order(price=2175, quantity=0.0313)\n self.assertIsInstance(order_response, beans.PlacedOrder)\n self.assertEqual(order_response.order_id, '448364249')\n self.assertEqual(order_response.exec_id, '448364249')\n self.assertEqual(order_response.exec_type, self.orders_api.ORDER_TYPE_LIMIT)\n self.assertEqual(order_response.order_status, self.orders_api.ORDER_STATUS_NEW)\n self.assertEqual(order_response.price, 2175.0)\n self.assertEqual(order_response.symbol, consts.Symbol.BTCUSD)\n self.assertEqual(order_response.amount, 0.0313)\n self.assertEqual(order_response.side, consts.OrderSide.SELL)\n self.assertEqual(order_response.client_order_id, '448364249')\n self.assertIsNone(order_response.message_type)\n self.assertIsNone(order_response.order_rejection_reason)\n", "method_code": " def sell_bitcoins_with_limited_order(self, price, quantity):\n side = consts.OrderSide.SELL\n response = self.client.auth_api.place_order(str(quantity), str(price), side, self.ORDER_TYPE_LIMIT)\n return self._make_placed_order_from_response(response)\n ", "context": "class BitfinexOrdersApi(IOrdersApi):\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def cancel_order(self, order_id): ...\n def get_pending_orders(self, page, page_size): ...\n def _make_placed_order_from_response(self, response): ...\n def _get_str_value_or_none(source, key): ...\n def _get_order_status(self, order): ...\n\n self.client = client\n\n ORDER_STATUS_CANCELLED = '4'\n ORDER_STATUS_NEW = '0'\n ORDER_TYPE_LIMIT = 'exchange limit'\n ORDER_TYPE_MARKET = 'exchange market'\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_places_a_limited_sell_order", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002442.py"} {"focal_file": "trading_system/api/bitfinex/orders.py", "focal_class": null, "focal_method": "sell_bitcoins_with_market_order", "tests": "import unittest\n\nclass Test_sell_bitcoins_with_market_order(unittest.TestCase):\n def test_it_places_a_market_sell_order(self):\n self.orders_api.client.auth_api.place_order = mock.Mock(return_value={'order_id': 1026166073, 'executed_amount': '0.0', 'avg_execution_price': '0.0', 'type': 'exchange market', 'is_hidden': False, 'timestamp': '1471637737.143232426', 'price': '600.0', 'side': 'sell', 'exchange': 'bitfinex', 'symbol': 'btcusd', 'is_live': True, 'id': 1026166073, 'is_cancelled': False, 'oco_order': None, 'original_amount': '0.0313', 'remaining_amount': '0.0313', 'was_forced': False})\n order_response = self.orders_api.sell_bitcoins_with_market_order(quantity=0.0313)\n self.assertIsInstance(order_response, beans.PlacedOrder)\n self.assertEqual(order_response.order_id, '1026166073')\n self.assertEqual(order_response.exec_id, '1026166073')\n self.assertEqual(order_response.exec_type, self.orders_api.ORDER_TYPE_MARKET)\n self.assertEqual(order_response.order_status, self.orders_api.ORDER_STATUS_NEW)\n self.assertEqual(order_response.symbol, consts.Symbol.BTCUSD)\n self.assertEqual(order_response.amount, 0.0313)\n self.assertEqual(order_response.side, consts.OrderSide.SELL)\n self.assertEqual(order_response.client_order_id, '1026166073')\n self.assertIsNone(order_response.message_type)\n self.assertIsNone(order_response.order_rejection_reason)\n", "method_code": " def sell_bitcoins_with_market_order(self, quantity):\n side = consts.OrderSide.SELL\n response = self.client.auth_api.place_order(str(quantity), price='0.01', side=side, ord_type=self.ORDER_TYPE_MARKET)\n return self._make_placed_order_from_response(response)\n ", "context": "class BitfinexOrdersApi(IOrdersApi):\n def sell_bitcoins_with_market_order(self, quantity): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def cancel_order(self, order_id): ...\n def get_pending_orders(self, page, page_size): ...\n def _make_placed_order_from_response(self, response): ...\n def _get_str_value_or_none(source, key): ...\n def _get_order_status(self, order): ...\n\n self.client = client\n\n ORDER_STATUS_CANCELLED = '4'\n ORDER_STATUS_NEW = '0'\n ORDER_TYPE_LIMIT = 'exchange limit'\n ORDER_TYPE_MARKET = 'exchange market'\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_places_a_market_sell_order", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002443.py"} {"focal_file": "trading_system/api/bitfinex/orders.py", "focal_class": null, "focal_method": "cancel_order", "tests": "import unittest\n\nclass Test_cancel_order(unittest.TestCase):\n def test_it_cancels_an_order(self):\n self.orders_api.client.auth_api.delete_order = mock.Mock(return_value={'id': 446915287, 'symbol': 'btcusd', 'exchange': None, 'price': '2175.0', 'avg_execution_price': '0.0', 'side': 'sell', 'type': 'exchange limit', 'timestamp': '1444141982.0', 'is_live': False, 'is_cancelled': True, 'is_hidden': False, 'was_forced': False, 'original_amount': '0.0313', 'remaining_amount': '0.0313', 'executed_amount': '0.0'})\n order_response = self.orders_api.cancel_order(1)\n self.assertIsInstance(order_response, beans.PlacedOrder)\n self.assertEqual(order_response.exec_id, '446915287')\n self.assertEqual(order_response.exec_type, self.orders_api.ORDER_TYPE_LIMIT)\n self.assertEqual(order_response.order_status, self.orders_api.ORDER_STATUS_CANCELLED)\n self.assertEqual(order_response.price, 2175.0)\n self.assertEqual(order_response.symbol, consts.Symbol.BTCUSD)\n self.assertEqual(order_response.amount, 0.0313)\n self.assertEqual(order_response.side, consts.OrderSide.SELL)\n self.assertIsNone(order_response.order_id)\n self.assertIsNone(order_response.message_type)\n self.assertIsNone(order_response.order_rejection_reason)\n self.assertIsNone(order_response.client_order_id)\n", "method_code": " def cancel_order(self, order_id):\n response = self.client.auth_api.delete_order(order_id)\n return self._make_placed_order_from_response(response)\n ", "context": "class BitfinexOrdersApi(IOrdersApi):\n def cancel_order(self, order_id): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def get_pending_orders(self, page, page_size): ...\n def _make_placed_order_from_response(self, response): ...\n def _get_str_value_or_none(source, key): ...\n def _get_order_status(self, order): ...\n\n self.client = client\n\n ORDER_STATUS_CANCELLED = '4'\n ORDER_STATUS_NEW = '0'\n ORDER_TYPE_LIMIT = 'exchange limit'\n ORDER_TYPE_MARKET = 'exchange market'\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_cancels_an_order", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002444.py"} {"focal_file": "trading_system/api/bitfinex/orders.py", "focal_class": null, "focal_method": "get_pending_orders", "tests": "import unittest\n\nclass Test_get_pending_orders(unittest.TestCase):\n def test_it_gets_pending_orders(self):\n self.orders_api.client.auth_api.active_orders = mock.Mock(return_value=[{'id': 448411365, 'symbol': 'btcusd', 'exchange': 'bitfinex', 'price': '2175.0', 'avg_execution_price': '0.0', 'side': 'buy', 'type': 'exchange limit', 'timestamp': '1444276597.0', 'is_live': True, 'is_cancelled': False, 'is_hidden': False, 'was_forced': False, 'original_amount': '0.0313', 'remaining_amount': '0.0313', 'executed_amount': '0.0'}])\n orders = self.orders_api.get_pending_orders(page=0, page_size=10)\n self.assertIsInstance(orders, list)\n order_response = orders[0]\n self.assertIsInstance(order_response, beans.PlacedOrder)\n self.assertEqual(order_response.exec_id, '448411365')\n self.assertEqual(order_response.exec_type, self.orders_api.ORDER_TYPE_LIMIT)\n self.assertEqual(order_response.order_status, self.orders_api.ORDER_STATUS_NEW)\n self.assertEqual(order_response.price, 2175.0)\n self.assertEqual(order_response.symbol, consts.Symbol.BTCUSD)\n self.assertEqual(order_response.amount, 0.0313)\n self.assertEqual(order_response.side, consts.OrderSide.BUY)\n self.assertIsNone(order_response.order_id)\n self.assertIsNone(order_response.message_type)\n self.assertIsNone(order_response.order_rejection_reason)\n self.assertIsNone(order_response.client_order_id)\n", "method_code": " def get_pending_orders(self, page, page_size):\n orders = self.client.auth_api.active_orders()\n orders = [self._make_placed_order_from_response(order) for order in orders]\n return orders[page * page_size:(page + 1) * page_size - 1]\n ", "context": "class BitfinexOrdersApi(IOrdersApi):\n def get_pending_orders(self, page, page_size): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def cancel_order(self, order_id): ...\n def _make_placed_order_from_response(self, response): ...\n def _get_str_value_or_none(source, key): ...\n def _get_order_status(self, order): ...\n\n self.client = client\n\n ORDER_STATUS_CANCELLED = '4'\n ORDER_STATUS_NEW = '0'\n ORDER_TYPE_LIMIT = 'exchange limit'\n ORDER_TYPE_MARKET = 'exchange market'\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "test_it_gets_pending_orders", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002445.py"} {"focal_file": "trading_system/api/blinktrade/accounts.py", "focal_class": null, "focal_method": "get_balance", "tests": "import unittest\n\nclass Test_get_balance(unittest.TestCase):\n @mock.patch('blinktrade.clients.AuthClient.get_balance', return_value={u'BRL': 1.0, u'BRL_locked': 2.0, u'BTC': 3.0, u'BTC_locked': 4.0})\n def test_it_get_balance(self, _):\n my_current_balance = self.accounts_api.get_balance()\n self.assertIsInstance(my_current_balance, beans.Balance)\n self.assertEqual(my_current_balance.currency, 1.0)\n self.assertEqual(my_current_balance.currency_locked, 2.0)\n self.assertEqual(my_current_balance.btc, 3.0)\n self.assertEqual(my_current_balance.btc_locked, 4.0)\n\n @mock.patch('blinktrade.clients.AuthClient.get_balance', return_value={})\n def test_it_get_no_balance(self, _):\n my_current_balance = self.accounts_api.get_balance()\n self.assertIsInstance(my_current_balance, beans.Balance)\n self.assertEqual(my_current_balance.currency, 0.0)\n self.assertEqual(my_current_balance.currency_locked, 0.0)\n self.assertEqual(my_current_balance.btc, 0.0)\n self.assertEqual(my_current_balance.btc_locked, 0.0)\n", "method_code": " def get_balance(self):\n balance = self.client.auth_api.get_balance()\n return self._make_balance_from_broker_dict(balance)\n ", "context": "class BlinkTradeAccountApi(IAccountApi):\n def get_balance(self): ...\n def __init__(self, client): ...\n def _make_balance_from_broker_dict(self, balance): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002446.py"} {"focal_file": "trading_system/api/blinktrade/markets.py", "focal_class": null, "focal_method": "get_ticker", "tests": "import unittest\n\nclass Test_get_ticker(unittest.TestCase):\n @mock.patch('blinktrade.clients.OpenClient.get_ticker', mock.Mock(return_value={'high': 2299.9, 'vol': 305.5, 'buy': 2279.8, 'last': 2295.98, 'low': 2202.76, 'pair': 'BTCBRL', 'sell': 2295.98, 'vol_brl': 691963.42}))\n def test_it_get_ticker(self):\n ticker = self.market_api.get_ticker()\n self.assertIsInstance(ticker, beans.Ticker)\n self.assertEqual(ticker.highest_value, 2299.9)\n self.assertEqual(ticker.volume_btc, 305.5)\n self.assertEqual(ticker.best_buy_order, 2279.8)\n self.assertEqual(ticker.last_value, 2295.98)\n self.assertEqual(ticker.lowest_value, 2202.76)\n self.assertEqual(ticker.best_sell_order, 2295.98)\n self.assertEqual(ticker.volume_currency, 691963.42)\n", "method_code": " def get_ticker(self):\n response = self.client.open_api.get_ticker()\n return beans.Ticker(currency_pair=str(response.get('pair')), last_value=float(response.get('last')), highest_value=float(response.get('high')), lowest_value=float(response.get('low')), best_sell_order=float(response.get('sell')), best_buy_order=float(response.get('buy')), volume_btc=float(response.get('vol')), volume_currency=float(response.get('vol_{currency}'.format(currency=self.client.currency.lower()))))\n ", "context": "class BlinkTradeMarketApi(IMarketApi):\n def get_ticker(self): ...\n def __init__(self, client): ...\n def get_order_book(self): ...\n def get_trade_list(self, since_ts=0): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002447.py"} {"focal_file": "trading_system/api/blinktrade/markets.py", "focal_class": null, "focal_method": "get_order_book", "tests": "import unittest\n\nclass Test_get_order_book(unittest.TestCase):\n @mock.patch('blinktrade.clients.OpenClient.get_order_book', mock.Mock(return_value={'pair': 'BTCBRL', 'bids': [[2279.9, 0.0421, 1000]], 'asks': [[2295.9, 0.2445, 2000]]}))\n def test_it_get_order_book(self):\n order_book = self.market_api.get_order_book()\n self.assertIsInstance(order_book, beans.OrderBook)\n self.assertIsInstance(order_book.bids, list)\n self.assertIsInstance(order_book.bids[0], beans.OrderInBook)\n self.assertEqual(order_book.bids[0].price, 2279.9)\n self.assertEqual(order_book.bids[0].amount, 0.0421)\n self.assertEqual(order_book.bids[0].user_id, 1000)\n self.assertIsInstance(order_book.asks, list)\n self.assertIsInstance(order_book.asks[0], beans.OrderInBook)\n self.assertEqual(order_book.asks[0].price, 2295.9)\n self.assertEqual(order_book.asks[0].amount, 0.2445)\n self.assertEqual(order_book.asks[0].user_id, 2000)\n", "method_code": " def get_order_book(self):\n response = self.client.open_api.get_order_book()\n return beans.OrderBook(currency_pair=str(response.get('pair')), bids=[beans.OrderInBook(price=bid[0], amount=bid[1], user_id=bid[2]) for bid in response.get('bids')], asks=[beans.OrderInBook(price=bid[0], amount=bid[1], user_id=bid[2]) for bid in response.get('asks')])\n ", "context": "class BlinkTradeMarketApi(IMarketApi):\n def get_order_book(self): ...\n def __init__(self, client): ...\n def get_ticker(self): ...\n def get_trade_list(self, since_ts=0): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002448.py"} {"focal_file": "trading_system/api/blinktrade/markets.py", "focal_class": null, "focal_method": "get_trade_list", "tests": "import unittest\n\nclass Test_get_trade_list(unittest.TestCase):\n @mock.patch('blinktrade.clients.OpenClient.get_trade_list', mock.Mock(return_value=[{'tid': 1000, 'date': 1467037014, 'price': 2300.0, 'amount': 0.02, 'side': 'sell'}]))\n def test_it_get_trades(self):\n trade_list = self.market_api.get_trade_list()\n self.assertIsInstance(trade_list, list)\n self.assertIsInstance(trade_list[0], beans.Trade)\n self.assertEqual(trade_list[0].transaction_id, 1000)\n self.assertEqual(trade_list[0].date, 1467037014)\n self.assertEqual(trade_list[0].price, 2300.0)\n self.assertEqual(trade_list[0].amount, 0.02)\n self.assertEqual(trade_list[0].side, consts.OrderSide.SELL)\n", "method_code": " def get_trade_list(self, since_ts=0):\n response = self.client.open_api.get_trade_list(since_ts)\n return [beans.Trade(transaction_id=int(item.get('tid')), date=int(item.get('date')), price=float(item.get('price')), amount=float(item.get('amount')), side=str(item.get('side'))) for item in response]\n ", "context": "class BlinkTradeMarketApi(IMarketApi):\n def get_trade_list(self, since_ts=0): ...\n def __init__(self, client): ...\n def get_ticker(self): ...\n def get_order_book(self): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002449.py"} {"focal_file": "trading_system/api/blinktrade/orders.py", "focal_class": null, "focal_method": "buy_bitcoins_with_limited_order", "tests": "import unittest\n\nclass Test_buy_bitcoins_with_limited_order(unittest.TestCase):\n @mock.patch('blinktrade.clients.AuthClient.buy_bitcoins_with_limited_order', mock.Mock(return_value=[{u'OrderID': 1459144180001, u'ExecID': 202294, u'ExecType': u'0', u'OrdStatus': u'0', u'CumQty': 0, u'Symbol': u'BTCBRL', u'OrderQty': 0.0313, u'LastShares': 0, u'LastPx': 0, u'CxlQty': 0, u'TimeInForce': u'1', u'LeavesQty': 0.0313, u'MsgType': u'8', u'ExecSide': u'1', u'OrdType': u'2', u'Price': 2175.0, u'Side': u'1', u'ClOrdID': 1467403664, u'AvgPx': 0}, {u'BRL': 1.0, u'BRL_locked': 2.0, u'BTC': 3.0, u'BTC_locked': 4.0}]))\n def test_it_places_a_limited_buy_order(self):\n order_response = self.orders_api.buy_bitcoins_with_limited_order(price=2175, quantity=0.0313)\n self.assertIsInstance(order_response, list)\n self.assertIsInstance(order_response[0], beans.PlacedOrder)\n self.assertEqual(order_response[0].order_id, '1459144180001')\n self.assertEqual(order_response[0].exec_id, '202294')\n self.assertEqual(order_response[0].exec_type, '0')\n self.assertEqual(order_response[0].order_status, '0')\n self.assertEqual(order_response[0].price, 2175.0)\n self.assertEqual(order_response[0].symbol, 'BTCBRL')\n self.assertEqual(order_response[0].amount, 0.0313)\n self.assertEqual(order_response[0].message_type, '8')\n self.assertEqual(order_response[0].side, '1')\n self.assertEqual(order_response[0].client_order_id, '1467403664')\n self.assertIsNone(order_response[0].order_rejection_reason)\n self.assertIsInstance(order_response[1], beans.Balance)\n self.assertEqual(order_response[1].currency_locked, 2.0)\n", "method_code": " def buy_bitcoins_with_limited_order(self, price, quantity):\n response = self.client.auth_api.buy_bitcoins_with_limited_order(price, quantity)\n return self._parse_order_response(response)\n ", "context": "class BlinkTradeOrdersApi(IOrdersApi):\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def _parse_order_response(self, response): ...\n def _make_placed_order_from_dict(self, order): ...\n def _get_str_value_or_none(source, key): ...\n def _make_balance(self, balance): ...\n def cancel_order(self, order_id): ...\n def get_pending_orders(self, page, page_size): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002450.py"} {"focal_file": "trading_system/api/blinktrade/orders.py", "focal_class": null, "focal_method": "buy_bitcoins_with_market_order", "tests": "import unittest\n\nclass Test_buy_bitcoins_with_market_order(unittest.TestCase):\n @mock.patch('blinktrade.clients.AuthClient.buy_bitcoins_with_market_order', mock.Mock(return_value=[{u'OrderID': 1459144180001, u'ExecID': 202294, u'ExecType': u'0', u'OrdStatus': u'0', u'CumQty': 0, u'Symbol': u'BTCBRL', u'OrderQty': 0.0313, u'LastShares': 0, u'LastPx': 0, u'CxlQty': 0, u'TimeInForce': u'1', u'LeavesQty': 0.0313, u'MsgType': u'8', u'ExecSide': u'1', u'OrdType': u'1', u'Price': 2175.0, u'Side': u'1', u'ClOrdID': 1467403664, u'AvgPx': 0}, {u'BRL': 1.0, u'BRL_locked': 2.0, u'BTC': 3.0, u'BTC_locked': 4.0}]))\n def test_it_places_a_market_buy_order(self):\n order_response = self.orders_api.buy_bitcoins_with_market_order(quantity=0.0313)\n self.assertIsInstance(order_response, list)\n self.assertIsInstance(order_response[0], beans.PlacedOrder)\n self.assertEqual(order_response[0].order_id, '1459144180001')\n self.assertEqual(order_response[0].exec_id, '202294')\n self.assertEqual(order_response[0].exec_type, '0')\n self.assertEqual(order_response[0].order_status, '0')\n self.assertEqual(order_response[0].price, 2175.0)\n self.assertEqual(order_response[0].symbol, 'BTCBRL')\n self.assertEqual(order_response[0].amount, 0.0313)\n self.assertEqual(order_response[0].message_type, '8')\n self.assertEqual(order_response[0].side, '1')\n self.assertEqual(order_response[0].client_order_id, '1467403664')\n self.assertIsNone(order_response[0].order_rejection_reason)\n self.assertIsInstance(order_response[1], beans.Balance)\n self.assertEqual(order_response[1].currency_locked, 2.0)\n", "method_code": " def buy_bitcoins_with_market_order(self, quantity):\n response = self.client.auth_api.buy_bitcoins_with_market_order(quantity)\n return self._parse_order_response(response)\n ", "context": "class BlinkTradeOrdersApi(IOrdersApi):\n def buy_bitcoins_with_market_order(self, quantity): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def _parse_order_response(self, response): ...\n def _make_placed_order_from_dict(self, order): ...\n def _get_str_value_or_none(source, key): ...\n def _make_balance(self, balance): ...\n def cancel_order(self, order_id): ...\n def get_pending_orders(self, page, page_size): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002451.py"} {"focal_file": "trading_system/api/blinktrade/orders.py", "focal_class": null, "focal_method": "sell_bitcoins_with_limited_order", "tests": "import unittest\n\nclass Test_sell_bitcoins_with_limited_order(unittest.TestCase):\n @mock.patch('blinktrade.clients.AuthClient.sell_bitcoins_with_limited_order', mock.Mock(return_value=[{u'OrderID': 1459144180001, u'ExecID': 202294, u'ExecType': u'0', u'OrdStatus': u'0', u'CumQty': 0, u'Symbol': u'BTCBRL', u'OrderQty': 0.0313, u'LastShares': 0, u'LastPx': 0, u'CxlQty': 0, u'TimeInForce': u'1', u'LeavesQty': 0.0313, u'MsgType': u'8', u'ExecSide': u'1', u'OrdType': u'2', u'Price': 2175.0, u'Side': u'2', u'ClOrdID': 1467403664, u'AvgPx': 0}, {u'BRL': 1.0, u'BRL_locked': 2.0, u'BTC': 3.0, u'BTC_locked': 4.0}]))\n def test_it_places_a_limited_sell_order(self):\n order_response = self.orders_api.sell_bitcoins_with_limited_order(price=2175, quantity=0.0313)\n self.assertIsInstance(order_response, list)\n self.assertIsInstance(order_response[0], beans.PlacedOrder)\n self.assertEqual(order_response[0].order_id, '1459144180001')\n self.assertEqual(order_response[0].exec_id, '202294')\n self.assertEqual(order_response[0].exec_type, '0')\n self.assertEqual(order_response[0].order_status, '0')\n self.assertEqual(order_response[0].price, 2175.0)\n self.assertEqual(order_response[0].symbol, 'BTCBRL')\n self.assertEqual(order_response[0].amount, 0.0313)\n self.assertEqual(order_response[0].message_type, '8')\n self.assertEqual(order_response[0].side, '2')\n self.assertEqual(order_response[0].client_order_id, '1467403664')\n self.assertIsNone(order_response[0].order_rejection_reason)\n self.assertIsInstance(order_response[1], beans.Balance)\n self.assertEqual(order_response[1].currency_locked, 2.0)\n", "method_code": " def sell_bitcoins_with_limited_order(self, price, quantity):\n response = self.client.auth_api.sell_bitcoins_with_limited_order(price, quantity)\n return self._parse_order_response(response)\n ", "context": "class BlinkTradeOrdersApi(IOrdersApi):\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def _parse_order_response(self, response): ...\n def _make_placed_order_from_dict(self, order): ...\n def _get_str_value_or_none(source, key): ...\n def _make_balance(self, balance): ...\n def cancel_order(self, order_id): ...\n def get_pending_orders(self, page, page_size): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002452.py"} {"focal_file": "trading_system/api/blinktrade/orders.py", "focal_class": null, "focal_method": "sell_bitcoins_with_market_order", "tests": "import unittest\n\nclass Test_sell_bitcoins_with_market_order(unittest.TestCase):\n @mock.patch('blinktrade.clients.AuthClient.sell_bitcoins_with_market_order', mock.Mock(return_value=[{u'OrderID': 1459144180001, u'ExecID': 202294, u'ExecType': u'0', u'OrdStatus': u'0', u'CumQty': 0, u'Symbol': u'BTCBRL', u'OrderQty': 0.0313, u'LastShares': 0, u'LastPx': 0, u'CxlQty': 0, u'TimeInForce': u'1', u'LeavesQty': 0.0313, u'MsgType': u'8', u'ExecSide': u'1', u'OrdType': u'1', u'Price': 2175.0, u'Side': u'2', u'ClOrdID': 1467403664, u'AvgPx': 0}, {u'BRL': 1.0, u'BRL_locked': 2.0, u'BTC': 3.0, u'BTC_locked': 4.0}]))\n def test_it_places_a_market_sell_order(self):\n order_response = self.orders_api.sell_bitcoins_with_market_order(quantity=0.0313)\n self.assertIsInstance(order_response, list)\n self.assertIsInstance(order_response[0], beans.PlacedOrder)\n self.assertEqual(order_response[0].order_id, '1459144180001')\n self.assertEqual(order_response[0].exec_id, '202294')\n self.assertEqual(order_response[0].exec_type, '0')\n self.assertEqual(order_response[0].order_status, '0')\n self.assertEqual(order_response[0].price, 2175.0)\n self.assertEqual(order_response[0].symbol, 'BTCBRL')\n self.assertEqual(order_response[0].amount, 0.0313)\n self.assertEqual(order_response[0].message_type, '8')\n self.assertEqual(order_response[0].side, '2')\n self.assertEqual(order_response[0].client_order_id, '1467403664')\n self.assertIsNone(order_response[0].order_rejection_reason)\n self.assertIsInstance(order_response[1], beans.Balance)\n self.assertEqual(order_response[1].currency_locked, 2.0)\n", "method_code": " def sell_bitcoins_with_market_order(self, quantity):\n response = self.client.auth_api.sell_bitcoins_with_market_order(quantity)\n return self._parse_order_response(response)\n ", "context": "class BlinkTradeOrdersApi(IOrdersApi):\n def sell_bitcoins_with_market_order(self, quantity): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def _parse_order_response(self, response): ...\n def _make_placed_order_from_dict(self, order): ...\n def _get_str_value_or_none(source, key): ...\n def _make_balance(self, balance): ...\n def cancel_order(self, order_id): ...\n def get_pending_orders(self, page, page_size): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002453.py"} {"focal_file": "trading_system/api/blinktrade/orders.py", "focal_class": null, "focal_method": "cancel_order", "tests": "import unittest\n\nclass Test_cancel_order(unittest.TestCase):\n @mock.patch('blinktrade.clients.AuthClient.cancel_order', mock.Mock(return_value=[{u'OrderID': 1459144180001, u'ExecID': 202543, u'ExecType': u'4', u'OrdStatus': u'4', u'CumQty': 0, u'Symbol': u'BTCBRL', u'OrderQty': 0.0313, u'LastShares': 0, u'LastPx': 0, u'CxlQty': 0, u'TimeInForce': u'1', u'LeavesQty': 0.0313, u'MsgType': u'8', u'ExecSide': u'1', u'OrdType': u'2', u'Price': 2175.0, u'Side': u'1', u'ClOrdID': 1467403664, u'AvgPx': 0}, {u'BRL': 1.0, u'BRL_locked': 2.0, u'BTC': 3.0, u'BTC_locked': 4.0}]))\n def test_it_cancels_an_order(self):\n order_response = self.orders_api.cancel_order(order_id='1467403664')\n self.assertIsInstance(order_response, list)\n self.assertIsInstance(order_response[0], beans.PlacedOrder)\n self.assertEqual(order_response[0].order_id, '1459144180001')\n self.assertEqual(order_response[0].exec_id, '202543')\n self.assertEqual(order_response[0].exec_type, '4')\n self.assertEqual(order_response[0].order_status, '4')\n self.assertEqual(order_response[0].price, 2175.0)\n self.assertEqual(order_response[0].symbol, 'BTCBRL')\n self.assertEqual(order_response[0].amount, 0.0313)\n self.assertEqual(order_response[0].message_type, '8')\n self.assertEqual(order_response[0].side, '1')\n self.assertEqual(order_response[0].client_order_id, '1467403664')\n self.assertIsNone(order_response[0].order_rejection_reason)\n self.assertIsInstance(order_response[1], beans.Balance)\n self.assertEqual(order_response[1].currency_locked, 2.0)\n", "method_code": " def cancel_order(self, order_id):\n response = self.client.auth_api.cancel_order(order_id)\n return self._parse_order_response(response)\n ", "context": "class BlinkTradeOrdersApi(IOrdersApi):\n def cancel_order(self, order_id): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def _parse_order_response(self, response): ...\n def _make_placed_order_from_dict(self, order): ...\n def _get_str_value_or_none(source, key): ...\n def _make_balance(self, balance): ...\n def get_pending_orders(self, page, page_size): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002454.py"} {"focal_file": "trading_system/api/blinktrade/orders.py", "focal_class": null, "focal_method": "get_pending_orders", "tests": "import unittest\n\nclass Test_get_pending_orders(unittest.TestCase):\n @mock.patch('blinktrade.clients.AuthClient.get_pending_orders', mock.Mock(return_value=[{u'OrderID': 1459144180001, u'OrdStatus': u'0', u'CumQty': 0, u'Symbol': u'BTCBRL', u'OrderQty': 0.0313, u'LastShares': 0, u'LastPx': 0, u'CxlQty': 0, u'TimeInForce': u'1', u'LeavesQty': 0.0313, u'ExecSide': u'1', u'OrdType': u'2', u'Price': 2175.0, u'Side': u'1', u'ClOrdID': 1467403664, u'AvgPx': 0}]))\n def test_it_gets_pending_orders(self):\n order_response = self.orders_api.get_pending_orders(page=0, page_size=100)\n self.assertIsInstance(order_response, list)\n self.assertIsInstance(order_response[0], beans.PlacedOrder)\n self.assertEqual(order_response[0].order_id, '1459144180001')\n self.assertEqual(order_response[0].order_status, '0')\n self.assertEqual(order_response[0].price, 2175.0)\n self.assertEqual(order_response[0].symbol, 'BTCBRL')\n self.assertEqual(order_response[0].amount, 0.0313)\n self.assertEqual(order_response[0].side, '1')\n self.assertEqual(order_response[0].client_order_id, '1467403664')\n self.assertIsNone(order_response[0].exec_id)\n self.assertIsNone(order_response[0].exec_type)\n self.assertIsNone(order_response[0].message_type)\n self.assertIsNone(order_response[0].order_rejection_reason)\n", "method_code": " def get_pending_orders(self, page, page_size):\n response = self.client.auth_api.get_pending_orders(page, page_size)\n return list(map(self._make_placed_order_from_dict, response))\n ", "context": "class BlinkTradeOrdersApi(IOrdersApi):\n def get_pending_orders(self, page, page_size): ...\n def __init__(self, client): ...\n def buy_bitcoins_with_limited_order(self, price, quantity): ...\n def buy_bitcoins_with_market_order(self, quantity): ...\n def sell_bitcoins_with_limited_order(self, price, quantity): ...\n def sell_bitcoins_with_market_order(self, quantity): ...\n def _parse_order_response(self, response): ...\n def _make_placed_order_from_dict(self, order): ...\n def _get_str_value_or_none(source, key): ...\n def _make_balance(self, balance): ...\n def cancel_order(self, order_id): ...\n\n self.client = client\n", "repository": "vinicius-ronconi/bitcoin-trading-system", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002455.py"} {"focal_file": "flask_consent/__init__.py", "focal_class": "Consent", "focal_method": "add_standard_categories", "tests": "import unittest\n\nclass Test_Consent_add_standard_categories(unittest.TestCase):\n def test_get_categories(self):\n consent = Consent()\n consent.add_standard_categories()\n self.assertEqual(len(consent.categories), 3)\n self.assertEqual(consent.categories['required'].title, 'Required')\n", "method_code": " def add_standard_categories(self):\n \"\"\"\n For getting started quickly you can use this function to add 3 common categories of cookies\n \"\"\"\n self.add_category('required', 'Required', 'These cookies are required for the site to function, like handling login (remembering who you are logged in as between page visits).', default=True, is_required=True)\n self.add_category('preferences', 'Preferences', 'These cookies are used for convenience functionality, like saving local preferences you have made.', default=True, is_required=False)\n self.add_category('analytics', 'Analytics', 'These cookies are used to track your page visits across the site and record some basic information about your browser. We use this information in order to see how our users are using the site, allowing us to focus improvements.', default=True, is_required=False)\n ", "context": "class Consent():\n def add_standard_categories(self): ...\n def __init__(self, app: Flask=None): ...\n def domain_loader(self, func: Callable[[], Iterable[str]]): ...\n def domains(self) -> List[str]: ...\n def set_render_template_func(self, f): ...\n def init_app(self, app: Flask): ...\n def state(cls) -> ConsentExtensionState: ...\n def add_category(self, name: str, title: str, description: str, default: bool, is_required: bool=False) -> ConsentCategory: ...\n def categories(self) -> OrderedDict: ...\n def _handle_consent_route(self): ...\n\n self._categories = OrderedDict()\n self._domain_loader = lambda: []\n self._render_template_func = render_template\n self.app = app\n", "repository": "02JanDal/Flask-Consent", "test_name": "test_get_categories", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002456.py"} {"focal_file": "flask_consent/__init__.py", "focal_class": "ConsentData", "focal_method": "add_standard_categories", "tests": "import unittest\n\nclass Test_ConsentData_add_standard_categories(unittest.TestCase):\n def test_get_set_categories(self):\n app = Flask(__name__)\n consent = Consent(app)\n consent.add_standard_categories()\n with app.test_request_context():\n data = ConsentData(consent.state())\n self.assertIs(data['analytics'], True)\n data['analytics'] = False\n self.assertIs(data['analytics'], False)\n preferences_category = consent.categories['preferences']\n self.assertIs(data[preferences_category], True)\n data[preferences_category] = False\n self.assertIs(data[preferences_category], False)\n", "method_code": " def add_standard_categories(self):\n \"\"\"\n For getting started quickly you can use this function to add 3 common categories of cookies\n \"\"\"\n self.add_category('required', 'Required', 'These cookies are required for the site to function, like handling login (remembering who you are logged in as between page visits).', default=True, is_required=True)\n self.add_category('preferences', 'Preferences', 'These cookies are used for convenience functionality, like saving local preferences you have made.', default=True, is_required=False)\n self.add_category('analytics', 'Analytics', 'These cookies are used to track your page visits across the site and record some basic information about your browser. We use this information in order to see how our users are using the site, allowing us to focus improvements.', default=True, is_required=False)\n ", "context": "class Consent():\n def add_standard_categories(self): ...\n def __init__(self, app: Flask=None): ...\n def domain_loader(self, func: Callable[[], Iterable[str]]): ...\n def domains(self) -> List[str]: ...\n def set_render_template_func(self, f): ...\n def init_app(self, app: Flask): ...\n def state(cls) -> ConsentExtensionState: ...\n def add_category(self, name: str, title: str, description: str, default: bool, is_required: bool=False) -> ConsentCategory: ...\n def categories(self) -> OrderedDict: ...\n def _handle_consent_route(self): ...\n\n self._categories = OrderedDict()\n self._domain_loader = lambda: []\n self._render_template_func = render_template\n self.app = app\n", "repository": "02JanDal/Flask-Consent", "test_name": "test_get_set_categories", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002457.py"} {"focal_file": "TSOBattleSimulator/Unit.py", "focal_class": null, "focal_method": "get_damage", "tests": "import unittest\n\nclass Test_get_damage(unittest.TestCase):\n def test_damage_single(self):\n unit = Unit.ImportUnit(self.file_path, name=self.abbrev)\n damage = unit.get_damage(single=True)\n print('Damage : ' + str(damage))\n self.assertIn(damage, self.expected_damage_single)\n\n def test_damage_multi(self):\n unit = Unit.ImportUnit(self.file_path, name=self.abbrev)\n expected = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]\n unit.set_amount(5)\n damage = unit.get_damage(total=True)\n print('Damage : ' + str(damage))\n self.assertIn(damage, expected)\n\n def test_damage_multi_repeat(self):\n unit = Unit.ImportUnit(self.file_path, name=self.abbrev)\n expected = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]\n unit.set_amount(5)\n for i in range(0, 1000):\n damage = unit.get_damage(total=True)\n print('Damage : ' + str(damage))\n self.assertIn(damage, expected)\n", "method_code": " def get_damage(self, total=True, single=False):\n if total == True:\n total = 0\n for x in range(0, self.amount):\n acc = random.randint(0, 100)\n if acc >= self.accuracy:\n total += self.min_dmg\n else:\n total += self.max_dmg\n return total\n if single == True:\n acc = random.randint(0, 100)\n damage = 0\n if acc >= self.accuracy:\n damage = self.min_dmg\n else:\n damage = self.max_dmg\n return damage\n ", "context": "class Unit():\n def get_damage(self, total=True, single=False): ...\n def __init__(self, name: str, abbrev: str, hp: int, min_dmg: int, max_dmg: int, accuracy: int, strike_order, targetweakest: int, splashdamage: int, targetorder: int, amount=None): ...\n def debug(self): ...\n def set_amount(self, amount): ...\n def get_amount(self): ...\n def get_strikeorder(self): ...\n def get_hp(self): ...\n def get_total_hp(self): ...\n def get_splashdamage(self): ...\n\n self.name = name\n self.abbrev = abbrev\n self.hp = int(hp)\n self.min_dmg = int(min_dmg)\n self.max_dmg = int(max_dmg)\n self.accuracy = int(accuracy)\n self.strike_order = int(strike_order)\n self.splashdamage = bool(int(splashdamage))\n self.targetorder = int(targetorder)\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_damage_single", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_002458.py"} {"focal_file": "TSOBattleSimulator/Unit.py", "focal_class": null, "focal_method": "get_splashdamage", "tests": "import unittest\n\nclass Test_get_splashdamage(unittest.TestCase):\n def test_import_correct_splashdamage(self):\n unit = Unit.ImportUnit(self.file_path, name=self.name)\n self.assertEqual(unit.get_splashdamage(), self.expected_splash_damage)\n", "method_code": " def get_splashdamage(self):\n if self.splashdamage == 0:\n return False\n else:\n return True\n ", "context": "class Unit():\n def get_splashdamage(self): ...\n def __init__(self, name: str, abbrev: str, hp: int, min_dmg: int, max_dmg: int, accuracy: int, strike_order, targetweakest: int, splashdamage: int, targetorder: int, amount=None): ...\n def debug(self): ...\n def set_amount(self, amount): ...\n def get_amount(self): ...\n def get_strikeorder(self): ...\n def get_hp(self): ...\n def get_total_hp(self): ...\n def get_damage(self, total=True, single=False): ...\n\n self.name = name\n self.abbrev = abbrev\n self.hp = int(hp)\n self.min_dmg = int(min_dmg)\n self.max_dmg = int(max_dmg)\n self.accuracy = int(accuracy)\n self.strike_order = int(strike_order)\n self.splashdamage = bool(int(splashdamage))\n self.targetorder = int(targetorder)\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_import_correct_splashdamage", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002459.py"} {"focal_file": "TSOBattleSimulator/Unit.py", "focal_class": null, "focal_method": "set_amount", "tests": "import unittest\n\nclass Test_set_amount(unittest.TestCase):\n def test_set_amount(self):\n unit = Unit.ImportUnit(self.file_path, name=self.name)\n initial = unit.get_amount()\n unit.set_amount(initial + 5)\n self.assertEqual(initial + 5, unit.get_amount())\n", "method_code": " def set_amount(self, amount):\n self.amount = amount\n ", "context": "class Unit():\n def set_amount(self, amount): ...\n def __init__(self, name: str, abbrev: str, hp: int, min_dmg: int, max_dmg: int, accuracy: int, strike_order, targetweakest: int, splashdamage: int, targetorder: int, amount=None): ...\n def debug(self): ...\n def get_amount(self): ...\n def get_strikeorder(self): ...\n def get_hp(self): ...\n def get_total_hp(self): ...\n def get_splashdamage(self): ...\n def get_damage(self, total=True, single=False): ...\n\n self.name = name\n self.abbrev = abbrev\n self.hp = int(hp)\n self.min_dmg = int(min_dmg)\n self.max_dmg = int(max_dmg)\n self.accuracy = int(accuracy)\n self.strike_order = int(strike_order)\n self.splashdamage = bool(int(splashdamage))\n self.targetorder = int(targetorder)\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_set_amount", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002460.py"} {"focal_file": "TSOBattleSimulator/Unit.py", "focal_class": null, "focal_method": "debug", "tests": "import unittest\n\nclass Test_debug(unittest.TestCase):\n def test_debug(self):\n unit = Unit.ImportUnit(self.file_path, name=self.name)\n unit.debug()\n", "method_code": " def debug(self):\n print('name : ' + self.name)\n print('abbrev : ' + self.abbrev)\n print('hp : ' + str(self.hp))\n print('min_dmg : ' + str(self.min_dmg))\n print('max_dmg : ' + str(self.max_dmg))\n print('accuracy : ' + str(self.accuracy))\n print('strike_order : ' + str(self.strike_order))\n print('targetweakest : ' + str(self.targetweakest))\n print('splashdamage : ' + str(self.splashdamage))\n print('amount : ' + str(self.amount))\n print('targetorder : ' + str(self.targetorder))\n ", "context": "class Unit():\n def debug(self): ...\n def __init__(self, name: str, abbrev: str, hp: int, min_dmg: int, max_dmg: int, accuracy: int, strike_order, targetweakest: int, splashdamage: int, targetorder: int, amount=None): ...\n def set_amount(self, amount): ...\n def get_amount(self): ...\n def get_strikeorder(self): ...\n def get_hp(self): ...\n def get_total_hp(self): ...\n def get_splashdamage(self): ...\n def get_damage(self, total=True, single=False): ...\n\n self.name = name\n self.abbrev = abbrev\n self.hp = int(hp)\n self.min_dmg = int(min_dmg)\n self.max_dmg = int(max_dmg)\n self.accuracy = int(accuracy)\n self.strike_order = int(strike_order)\n self.splashdamage = bool(int(splashdamage))\n self.targetorder = int(targetorder)\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_debug", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002461.py"} {"focal_file": "TSOBattleSimulator/Adventure.py", "focal_class": null, "focal_method": "get_camp", "tests": "import unittest\n\nclass Test_get_camp(unittest.TestCase):\n def test_get_camp(self):\n adventure = Adventure.ImportAdventure('./Adventures/CN/adventure_info.json')\n camp = adventure.get_camp('1')\n self.assertEqual(camp.name, '1')\n", "method_code": " def get_camp(self, camp_name):\n for camp in self.camps:\n if camp.name == camp_name:\n return camp\n print('Camp introuvable')\n return None\n ", "context": "class Adventure():\n def get_camp(self, camp_name): ...\n def __init__(self, name: str, units_file: str, camps_f: str): ...\n def debug(self): ...\n\n self.name = name\n self.units_file = units_file\n self.camps_f = camps_f\n self.camps = ImportCamps(self.camps_f, self.units_file)\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_get_camp", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002462.py"} {"focal_file": "TSOBattleSimulator/Adventure.py", "focal_class": null, "focal_method": "debug", "tests": "import unittest\n\nclass Test_debug(unittest.TestCase):\n def test_debug(self):\n c_file = {}\n c_file['name'] = '1'\n c_file['file'] = './Adventures/CN/2.json'\n camp = Adventure.ImportCamp('./Adventures/CN/units.json', c_file)\n camp.debug()\n", "method_code": " def debug(self):\n print(self.units)\n ", "context": "class Camp():\n def debug(self): ...\n def __init__(self, name: str): ...\n def add_unit(self, unit): ...\n\n self.name = name\n self.units = []\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_debug", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002463.py"} {"focal_file": "TSOBattleSimulator/Adventure.py", "focal_class": null, "focal_method": "add_unit", "tests": "import unittest\n\nclass Test_add_unit(unittest.TestCase):\n def test_add_unit(self):\n c_file = {}\n c_file['name'] = '1'\n c_file['file'] = './Adventures/CN/2.json'\n camp = Adventure.ImportCamp('./Adventures/CN/units.json', c_file)\n unit = Unit.ImportUnit('./Adventures/CN/units.json', name='soldat')\n previous_len = len(camp.units)\n camp.add_unit(unit)\n self.assertEqual(len(camp.units), previous_len + 1)\n", "method_code": " def add_unit(self, unit):\n self.units.append(unit)\n ", "context": "class Camp():\n def add_unit(self, unit): ...\n def __init__(self, name: str): ...\n def debug(self): ...\n\n self.name = name\n self.units = []\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_add_unit", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002464.py"} {"focal_file": "TSOBattleSimulator/Battle.py", "focal_class": null, "focal_method": "add_unit", "tests": "import unittest\n\nclass Test_add_unit(unittest.TestCase):\n def test_add_unit(self):\n unit = Unit.ImportUnit(self.file_path, abbrev=self.abbrev, amount=200)\n self.Side.add_unit(unit)\n self.Side.add_unit(unit)\n self.assertEqual(len(self.Side.units), 2)\n", "method_code": " def add_unit(self, unit):\n self.units.append(unit)\n ", "context": "class Side():\n def add_unit(self, unit): ...\n def __init__(self, units=None): ...\n def add_units(self, units): ...\n def has_lost(self): ...\n def debug(self): ...\n def get_unit(self, weakest=False): ...\n def get_unit_with_name(self, name: str): ...\n def get_unit_with_abbrev(self, abbrev: str): ...\n\n self.units = []\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_add_unit", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002465.py"} {"focal_file": "TSOBattleSimulator/Battle.py", "focal_class": null, "focal_method": "add_units", "tests": "import unittest\n\nclass Test_add_units(unittest.TestCase):\n def test_add_units(self):\n unit = Unit.ImportUnit(self.file_path, abbrev=self.abbrev, amount=200)\n units = []\n units.append(unit)\n units.append(unit)\n self.Side.add_units(units)\n self.assertEqual(len(self.Side.units), 2)\n", "method_code": " def add_units(self, units):\n for unit in units:\n self.units.append(unit)\n ", "context": "class Side():\n def add_units(self, units): ...\n def __init__(self, units=None): ...\n def add_unit(self, unit): ...\n def has_lost(self): ...\n def debug(self): ...\n def get_unit(self, weakest=False): ...\n def get_unit_with_name(self, name: str): ...\n def get_unit_with_abbrev(self, abbrev: str): ...\n\n self.units = []\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_add_units", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002466.py"} {"focal_file": "TSOBattleSimulator/Battle.py", "focal_class": null, "focal_method": "get_unit", "tests": "import unittest\n\nclass Test_get_unit(unittest.TestCase):\n def test_get_unit(self):\n unit = Unit.ImportUnit(self.file_path, abbrev=self.abbrev, amount=200)\n units = []\n units.append(unit)\n self.Side.add_units(units)\n self.assertIsInstance(self.Side.get_unit(), Unit.Unit)\n\n def test_get_weakest_unit(self):\n returned_u = self.Side.get_unit(weakest=True)\n self.assertEqual(returned_u.abbrev, 'Cava')\n", "method_code": " def get_unit(self, weakest=False):\n if weakest == True:\n return get_weakest_unit(self.units)\n else:\n return get_next_targetorder_unit(self.units)\n ", "context": "class Side():\n def get_unit(self, weakest=False): ...\n def __init__(self, units=None): ...\n def add_units(self, units): ...\n def add_unit(self, unit): ...\n def has_lost(self): ...\n def debug(self): ...\n def get_unit_with_name(self, name: str): ...\n def get_unit_with_abbrev(self, abbrev: str): ...\n\n self.units = []\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_get_unit", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002467.py"} {"focal_file": "TSOBattleSimulator/Battle.py", "focal_class": null, "focal_method": "get_unit_with_name", "tests": "import unittest\n\nclass Test_get_unit_with_name(unittest.TestCase):\n def test_get_unit_with_name(self):\n unit = Unit.ImportUnit(self.file_path, abbrev=self.abbrev, amount=200)\n units = []\n units.append(unit)\n self.Side.add_units(units)\n self.assertEqual(self.Side.get_unit_with_name('soldat').name, 'soldat')\n", "method_code": "def get_unit_with_name(units, name: str):\n found_u = None\n for i in units:\n if i.name == name:\n found_u = i\n return found_u", "context": "def get_unit_with_name(units, name: str): ...\ndef get_next_targetorder_unit(units): ...\ndef get_weakest_unit(units): ...\ndef get_unit_with_name(units, name: str): ...\ndef get_unit_with_abbrev(units, abbrev: str): ...\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_get_unit_with_name", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002468.py"} {"focal_file": "TSOBattleSimulator/Battle.py", "focal_class": null, "focal_method": "get_unit_with_abbrev", "tests": "import unittest\n\nclass Test_get_unit_with_abbrev(unittest.TestCase):\n def test_get_unit_with_abbrev(self):\n unit = Unit.ImportUnit(self.file_path, abbrev=self.abbrev, amount=200)\n units = []\n units.append(unit)\n self.Side.add_units(units)\n self.assertEqual(self.Side.get_unit_with_abbrev('S').name, 'soldat')\n", "method_code": "def get_unit_with_abbrev(units, abbrev: str):\n found_u = None\n for i in units:\n if i.abbrev == abbrev:\n found_u = i\n return found_u", "context": "def get_unit_with_abbrev(units, abbrev: str): ...\ndef get_next_targetorder_unit(units): ...\ndef get_weakest_unit(units): ...\ndef get_unit_with_name(units, name: str): ...\ndef get_unit_with_abbrev(units, abbrev: str): ...\n", "repository": "Djipyy/TSOBattleSimulator", "test_name": "test_get_unit_with_abbrev", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002469.py"} {"focal_file": "caesar.py", "focal_class": null, "focal_method": "encode", "tests": "import unittest\n\nclass Test_encode(unittest.TestCase):\n def test_encode_valid(self):\n self.assertEqual(encode('Google forever', 5), 'Gttlqj ktwjajw')\n", "method_code": "def encode(text, key):\n alph = 'abcdefghijklmnopqrstuvwxyz'\n if key == 0 or key > 26:\n return 'Invalid key!'\n else:\n shift_alph = alph[key:] + alph[:key]\n ct = []\n for i in text:\n if (i in alph) == False:\n ct += [i]\n continue\n else:\n l_pos = int(alph.index(i))\n cl = shift_alph[l_pos]\n ct += cl\n return ''.join(ct)", "context": "def encode(text, key): ...\ndef encode(text, key): ...\ndef decode(ct, key): ...\n", "repository": "gerasymu4ka/homework", "test_name": "test_encode_valid", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002470.py"} {"focal_file": "caesar.py", "focal_class": null, "focal_method": "decode", "tests": "import unittest\n\nclass Test_decode(unittest.TestCase):\n def test_decode_valid(self):\n self.assertEqual(decode('Gttlqj ktwjajw', 5), 'Google forever')\n", "method_code": "def decode(ct, key):\n alph = 'abcdefghijklmnopqrstuvwxyz'\n if key > 26 or key == 0:\n return 'Invalid key!'\n else:\n shift_alph = alph[key:] + alph[:key]\n text = []\n for i in ct:\n if (i in shift_alph) == False:\n text += [i]\n else:\n cl_pos = int(shift_alph.index(i))\n letter = alph[cl_pos]\n text += letter\n return ''.join(text)", "context": "def decode(ct, key): ...\ndef encode(text, key): ...\ndef decode(ct, key): ...\n", "repository": "gerasymu4ka/homework", "test_name": "test_decode_valid", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002471.py"} {"focal_file": "factorial.py", "focal_class": null, "focal_method": "factorial", "tests": "import unittest\n\nclass Test_factorial(unittest.TestCase):\n def test_factorial(self):\n self.assertEqual(factorial(4), 24)\n", "method_code": "def factorial(x):\n if x == 0:\n return 'Factorial of 0 is 1'\n elif x < 0:\n return \"Factorial doesn't exist\"\n else:\n for i in xrange(1, x):\n x *= i\n return x", "context": "def factorial(x): ...\ndef factorial(x): ...\n", "repository": "gerasymu4ka/homework", "test_name": "test_factorial", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002472.py"} {"focal_file": "buter/util/OSUtil.py", "focal_class": null, "focal_method": "getOSInfo", "tests": "import unittest\n\nclass Test_getOSInfo(unittest.TestCase):\n def test_getOSInfo(self):\n print('system info : ', getOSInfo())\n", "method_code": "def getOSInfo():\n \"\"\"\n 获取操作系统信息\n :return:\n \"\"\"\n return {'system': platform.system(), 'version': platform.version(), 'machine': platform.machine(), 'platform': sys.platform, '64Bit': sys.maxsize > 2 ** 32, 'cpu': platform.processor()}", "context": "def getOSInfo(): ...\ndef getOSInfo(): ...\ndef getPythonInfo(): ...\ndef listDir(path, detail=False): ...\n", "repository": "0604hx/buter", "test_name": "test_getOSInfo", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_002473.py"} {"focal_file": "buter/util/OSUtil.py", "focal_class": null, "focal_method": "getPythonInfo", "tests": "import unittest\n\nclass Test_getPythonInfo(unittest.TestCase):\n def test_getPythonInfo(self):\n print('python info : ', getPythonInfo())\n", "method_code": "def getPythonInfo():\n \"\"\"\n 获取 python 信息,返回 version、 compiler 两个属性\n :return:\n \"\"\"\n return {'version': platform.python_version(), 'compiler': platform.python_compiler()}", "context": "def getPythonInfo(): ...\ndef getOSInfo(): ...\ndef getPythonInfo(): ...\ndef listDir(path, detail=False): ...\n", "repository": "0604hx/buter", "test_name": "test_getPythonInfo", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_002474.py"} {"focal_file": "buter/schedule/jobs.py", "focal_class": null, "focal_method": "checkDocker", "tests": "import unittest\n\nclass Test_checkDocker(unittest.TestCase):\n def test_check_docker(self):\n time.sleep(1)\n print('开始检测 docker。。。')\n jobs.checkDocker()\n", "method_code": "def checkDocker():\n with db.app.app_context():\n __tip('开始检测 docker connection...')\n if docker.client is None:\n LOG.debug('检测到 docker.client 未实例化,即将进行初始化...')\n docker.setup(current_app.config)\n LOG.info('^.^ docker.client 初始化成功 ^.^')\n else:\n try:\n LOG.debug('^.^ docker server 通讯正常 : ping=%s ^.^', docker.client.ping())\n except Exception as e:\n LOG.info('调用 docker.client.ping() 时出错:%s', str(e))\n docker.cleanup()\n __tip()", "context": "def checkDocker(): ...\ndef __tip(msg=None): ...\ndef checkDocker(): ...\n", "repository": "0604hx/buter", "test_name": "test_check_docker", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], "pynose_source_file": "test_002475.py"} {"focal_file": "buter/app/services.py", "focal_class": null, "focal_method": "load_from_file", "tests": "import unittest\n\nclass Test_load_from_file(unittest.TestCase):\n def test_load_from_file(self):\n load_from_file('G:/tidb.zip')\n", "method_code": "def load_from_file(file_path: str, application: Application, update=False, **kwargs):\n \"\"\"\n 从指定的目录加载文件(用户上传的文件要求为`zip`格式的压缩文件)\n :param application:\n :param update: True = 迭代更新,False = 全新部署\n :param file_path:\n :param kwargs:\n remove 是否移除同名的旧容器,默认 True\n\n :return:\n \"\"\"\n if file_path is None or not os.path.exists(file_path):\n raise ServiceException('参数 file_path 未定义或者找不到相应的文件:%s' % file_path)\n if not file_path.endswith(ZIP):\n raise ServiceException('load_from_file 只支持 %s 结尾的文件' % ZIP)\n app_dir = detect_app_dir(application)\n if update:\n files = update_app_with_zip(file_path, app_dir)\n return (application.name, files)\n unzip_dir, files = unzip(file_path)\n LOG.info('解压到 %s' % unzip_dir)\n container_name = application.name\n for file in [str(f) for f in files]:\n LOG.debug('processing %s', file)\n if file.endswith(TAR):\n LOG.info('检测到 %s 文件 %s,即将导入该镜像...' % (TAR, file))\n docker.loadImage(os.path.join(unzip_dir, file))\n LOG.info('docker 镜像导入成功')\n if file.endswith(ZIP):\n '对于 zip 格式的文件,解压到程序根目录'\n unzip(os.path.join(unzip_dir, file), app_dir)\n LOG.info('解压 %s 到 %s' % (file, app_dir))\n if file in ['{}-{}.jar'.format(application.name, application.version), '{}.jar'.format(application.name)]:\n '\\n 对于 {application.name}.jar 、 {application.name}-{version}.jar 的文件,直接复制到 app_dir\\n 通常经过 spring-boot 打包的 jar 可以直接运行\\n '\n copyFileToDir(os.path.join(unzip_dir, file), app_dir)\n if file == APP_JSON:\n with open(os.path.join(unzip_dir, file)) as app_json:\n content = __transform_placeholder(app_json.read(), application)\n LOG.info('获取并填充 %s :%s' % (APP_JSON, content))\n app_ps = json.loads(content)\n if 'args' not in app_ps:\n app_ps['args'] = {}\n if 'image' not in app_ps:\n raise ServiceException(\"{} 中必须定义 'image' 属性,否则无法创建容器\".format(APP_JSON))\n container_name = detect_app_name(app_ps['args'], app_ps['image'])\n LOG.info('检测到 容器名:%s', container_name)\n old_container = None\n if kwargs.pop('remove', True):\n try:\n old_container = docker.getContainer(container_name)\n LOG.info('name={} 的容器已经存在:{}, id={}'.format(container_name, old_container, old_container.id))\n except Exception:\n pass\n if old_container is not None:\n try:\n old_container.remove()\n LOG.info('成功删除name=%s 的容器' % container_name)\n except Exception as e:\n raise ServiceException('无法删除 name={} 的容器: {}'.format(container_name, str(e)))\n network = docker.createDefaultNetwork()\n app_ps['args']['network'] = network.name\n docker.createContainer(app_ps['image'], container_name, app_ps['cmd'], app_ps['args'])\n LOG.info('APP 容器 创建成功(image=%s,name=%s, network=%s)' % (app_ps['image'], container_name, network.name))\n shutil.rmtree(unzip_dir)\n return (container_name, files)", "context": "def load_from_file(file_path: str, application: Application, update=False, **kwargs): ...\ndef list_all_container(toDict=False): ...\ndef do_with_container(name, op): ...\ndef load_from_file(file_path: str, application: Application, update=False, **kwargs): ...\ndef update_app_with_zip(file_path, app_dir): ...\ndef detect_app_name(name, image_name: str=None): ...\ndef detect_app_dir(app_or_name): ...\ndef __transform_placeholder(content: str, app: Application): ...\n", "repository": "0604hx/buter", "test_name": "test_load_from_file", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002476.py"} {"focal_file": "buter/app/services.py", "focal_class": null, "focal_method": "detect_app_name", "tests": "import unittest\n\nclass Test_detect_app_name(unittest.TestCase):\n def test_detect_app_name(self):\n app = json.loads('{\"image\":\"pingcap/tidb\", \"args\":{\"name\":\"tidb01\"}}')\n self.assertEqual('tidb', detect_app_name(None, app['image']))\n self.assertEqual('tidb01', detect_app_name(app['args']))\n self.assertEqual('tidb', detect_app_name('tidb'))\n", "method_code": "def detect_app_name(name, image_name: str=None):\n \"\"\"\n 识别application名称,优先使用 name ,仅当前者无效时才使用 image_name\n :param name: 如果 name 是字符串,则直接使用;若是 dict 则查询 name 属性\n :param image_name: docker 镜像名,使用时先进行 / 分割\n :return:\n \"\"\"\n if name is not None and isinstance(name, (str, dict)):\n return name if isinstance(name, str) else name['name']\n elif image_name is not None:\n return image_name.split('/').pop()\n else:\n return None", "context": "def detect_app_name(name, image_name: str=None): ...\ndef list_all_container(toDict=False): ...\ndef do_with_container(name, op): ...\ndef load_from_file(file_path: str, application: Application, update=False, **kwargs): ...\ndef update_app_with_zip(file_path, app_dir): ...\ndef detect_app_name(name, image_name: str=None): ...\ndef detect_app_dir(app_or_name): ...\ndef __transform_placeholder(content: str, app: Application): ...\n", "repository": "0604hx/buter", "test_name": "test_detect_app_name", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002477.py"} {"focal_file": "hr/doctype/leave_block_list/leave_block_list.py", "focal_class": null, "focal_method": "get_applicable_block_dates", "tests": "import unittest\n\nclass Test_get_applicable_block_dates(unittest.TestCase):\n def test_get_applicable_block_dates(self):\n webnotes.session.user = 'test@example.com'\n webnotes.conn.set_value('Department', '_Test Department', 'leave_block_list', '_Test Leave Block List')\n self.assertTrue('2013-01-02' in [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03')])\n\n def test_get_applicable_block_dates_for_allowed_user(self):\n webnotes.session.user = 'test1@example.com'\n webnotes.conn.set_value('Department', '_Test Department 1', 'leave_block_list', '_Test Leave Block List')\n self.assertEquals([], [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03')])\n\n def test_get_applicable_block_dates_all_lists(self):\n webnotes.session.user = 'test1@example.com'\n webnotes.conn.set_value('Department', '_Test Department 1', 'leave_block_list', '_Test Leave Block List')\n self.assertTrue('2013-01-02' in [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03', all_lists=True)])\n", "method_code": "def get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False):\n block_dates = []\n for block_list in get_applicable_block_lists(employee, company, all_lists):\n block_dates.extend(webnotes.conn.sql('select block_date, reason \\n\\t\\t\\tfrom `tabLeave Block List Date` where parent=%s \\n\\t\\t\\tand block_date between %s and %s', (block_list, from_date, to_date), as_dict=1))\n return block_dates", "context": "@webnotes.whitelist()\ndef get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False): ...\ndef get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False): ...\ndef get_applicable_block_lists(employee=None, company=None, all_lists=False): ...\ndef is_user_in_allow_list(block_list): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_get_applicable_block_dates", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002478.py"} {"focal_file": "buying/doctype/supplier_quotation/supplier_quotation.py", "focal_class": null, "focal_method": "make_purchase_order", "tests": "import unittest\n\nclass Test_make_purchase_order(unittest.TestCase):\n def test_make_purchase_order(self):\n from buying.doctype.supplier_quotation.supplier_quotation import make_purchase_order\n sq = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_purchase_order, sq.doc.name)\n sq = webnotes.bean('Supplier Quotation', sq.doc.name)\n sq.submit()\n po = make_purchase_order(sq.doc.name)\n self.assertEquals(po[0]['doctype'], 'Purchase Order')\n self.assertEquals(len(po), len(sq.doclist))\n po[0]['naming_series'] = '_T-Purchase Order-'\n for doc in po:\n if doc.get('item_code'):\n doc['schedule_date'] = '2013-04-12'\n webnotes.bean(po).insert()\n", "method_code": "def make_purchase_order(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n\n def set_missing_values(source, target):\n bean = webnotes.bean(target)\n bean.run_method('set_missing_values')\n bean.run_method('get_schedule_dates')\n\n def update_item(obj, target, source_parent):\n target.conversion_factor = 1\n doclist = get_mapped_doclist('Supplier Quotation', source_name, {'Supplier Quotation': {'doctype': 'Purchase Order', 'validation': {'docstatus': ['=', 1]}}, 'Supplier Quotation Item': {'doctype': 'Purchase Order Item', 'field_map': [['name', 'supplier_quotation_item'], ['parent', 'supplier_quotation'], ['uom', 'stock_uom'], ['uom', 'uom'], ['prevdoc_detail_docname', 'prevdoc_detail_docname'], ['prevdoc_doctype', 'prevdoc_doctype'], ['prevdoc_docname', 'prevdoc_docname']], 'postprocess': update_item}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef make_purchase_order(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_purchase_order", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002479.py"} {"focal_file": "buying/doctype/purchase_order/purchase_order.py", "focal_class": null, "focal_method": "make_purchase_receipt", "tests": "import unittest\n\nclass Test_make_purchase_receipt(unittest.TestCase):\n def test_make_purchase_receipt(self):\n from buying.doctype.purchase_order.purchase_order import make_purchase_receipt\n po = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_purchase_receipt, po.doc.name)\n po = webnotes.bean('Purchase Order', po.doc.name)\n po.submit()\n pr = make_purchase_receipt(po.doc.name)\n pr[0]['supplier_warehouse'] = '_Test Warehouse 1 - _TC'\n pr[0]['posting_date'] = '2013-05-12'\n self.assertEquals(pr[0]['doctype'], 'Purchase Receipt')\n self.assertEquals(len(pr), len(test_records[0]))\n pr[0].naming_series = '_T-Purchase Receipt-'\n pr_bean = webnotes.bean(pr)\n pr_bean.insert()\n", "method_code": "def make_purchase_receipt(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n\n def set_missing_values(source, target):\n bean = webnotes.bean(target)\n bean.run_method('set_missing_values')\n\n def update_item(obj, target, source_parent):\n target.qty = flt(obj.qty) - flt(obj.received_qty)\n target.stock_qty = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.conversion_factor)\n target.import_amount = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.import_rate)\n target.amount = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.purchase_rate)\n doclist = get_mapped_doclist('Purchase Order', source_name, {'Purchase Order': {'doctype': 'Purchase Receipt', 'validation': {'docstatus': ['=', 1]}}, 'Purchase Order Item': {'doctype': 'Purchase Receipt Item', 'field_map': {'name': 'prevdoc_detail_docname', 'parent': 'prevdoc_docname', 'parenttype': 'prevdoc_doctype'}, 'postprocess': update_item, 'condition': lambda doc: doc.received_qty < doc.qty}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_purchase_receipt(source_name, target_doclist=None): ...\ndef make_purchase_receipt(source_name, target_doclist=None): ...\ndef make_purchase_invoice(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_purchase_receipt", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002480.py"} {"focal_file": "buying/doctype/purchase_order/purchase_order.py", "focal_class": null, "focal_method": "make_purchase_invoice", "tests": "import unittest\n\nclass Test_make_purchase_invoice(unittest.TestCase):\n def test_make_purchase_invocie(self):\n from buying.doctype.purchase_order.purchase_order import make_purchase_invoice\n po = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_purchase_invoice, po.doc.name)\n po = webnotes.bean('Purchase Order', po.doc.name)\n po.submit()\n pi = make_purchase_invoice(po.doc.name)\n self.assertEquals(pi[0]['doctype'], 'Purchase Invoice')\n self.assertEquals(len(pi), len(test_records[0]))\n pi[0]['posting_date'] = '2013-05-12'\n pi[0].bill_no = 'NA'\n webnotes.bean(pi).insert()\n", "method_code": "def make_purchase_invoice(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n\n def set_missing_values(source, target):\n bean = webnotes.bean(target)\n bean.run_method('set_missing_values')\n bean.run_method('set_supplier_defaults')\n\n def update_item(obj, target, source_parent):\n target.import_amount = flt(obj.import_amount) - flt(obj.billed_amt)\n target.amount = target.import_amount * flt(source_parent.conversion_rate)\n if flt(obj.purchase_rate):\n target.qty = target.amount / flt(obj.purchase_rate)\n doclist = get_mapped_doclist('Purchase Order', source_name, {'Purchase Order': {'doctype': 'Purchase Invoice', 'validation': {'docstatus': ['=', 1]}}, 'Purchase Order Item': {'doctype': 'Purchase Invoice Item', 'field_map': {'name': 'po_detail', 'parent': 'purchase_order', 'purchase_rate': 'rate'}, 'postprocess': update_item, 'condition': lambda doc: doc.amount == 0 or doc.billed_amt < doc.import_amount}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_purchase_invoice(source_name, target_doclist=None): ...\ndef make_purchase_receipt(source_name, target_doclist=None): ...\ndef make_purchase_invoice(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_purchase_invocie", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002481.py"} {"focal_file": "selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_material_request", "tests": "import unittest\n\nclass Test_make_material_request(unittest.TestCase):\n def test_make_material_request(self):\n from selling.doctype.sales_order.sales_order import make_material_request\n so = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_material_request, so.doc.name)\n sales_order = webnotes.bean('Sales Order', so.doc.name)\n sales_order.submit()\n mr = make_material_request(so.doc.name)\n self.assertEquals(mr[0]['material_request_type'], 'Purchase')\n self.assertEquals(len(mr), len(sales_order.doclist))\n", "method_code": "def make_material_request(source_name, target_doclist=None):\n\n def postprocess(source, doclist):\n doclist[0].material_request_type = 'Purchase'\n doclist = get_mapped_doclist('Sales Order', source_name, {'Sales Order': {'doctype': 'Material Request', 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Material Request Item', 'field_map': {'parent': 'sales_order_no', 'reserved_warehouse': 'warehouse', 'stock_uom': 'uom'}}}, target_doclist, postprocess)\n return [d if isinstance(d, dict) else d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_material_request(source_name, target_doclist=None): ...\ndef set_missing_values(source, target): ...\ndef make_material_request(source_name, target_doclist=None): ...\ndef make_delivery_note(source_name, target_doclist=None): ...\ndef make_sales_invoice(source_name, target_doclist=None): ...\ndef make_maintenance_schedule(source_name, target_doclist=None): ...\ndef make_maintenance_visit(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_material_request", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002482.py"} {"focal_file": "selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_delivery_note", "tests": "import unittest\n\nclass Test_make_delivery_note(unittest.TestCase):\n def test_make_delivery_note(self):\n from selling.doctype.sales_order.sales_order import make_delivery_note\n so = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_delivery_note, so.doc.name)\n sales_order = webnotes.bean('Sales Order', so.doc.name)\n sales_order.submit()\n dn = make_delivery_note(so.doc.name)\n self.assertEquals(dn[0]['doctype'], 'Delivery Note')\n self.assertEquals(len(dn), len(sales_order.doclist))\n", "method_code": "def make_delivery_note(source_name, target_doclist=None):\n\n def update_item(obj, target, source_parent):\n target.amount = (flt(obj.qty) - flt(obj.delivered_qty)) * flt(obj.basic_rate)\n target.export_amount = (flt(obj.qty) - flt(obj.delivered_qty)) * flt(obj.export_rate)\n target.qty = flt(obj.qty) - flt(obj.delivered_qty)\n doclist = get_mapped_doclist('Sales Order', source_name, {'Sales Order': {'doctype': 'Delivery Note', 'field_map': {'shipping_address': 'address_display', 'shipping_address_name': 'customer_address'}, 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Delivery Note Item', 'field_map': {'export_rate': 'export_rate', 'name': 'prevdoc_detail_docname', 'parent': 'against_sales_order', 'reserved_warehouse': 'warehouse'}, 'postprocess': update_item, 'condition': lambda doc: doc.delivered_qty < doc.qty}, 'Sales Taxes and Charges': {'doctype': 'Sales Taxes and Charges', 'add_if_empty': True}, 'Sales Team': {'doctype': 'Sales Team', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_delivery_note(source_name, target_doclist=None): ...\ndef set_missing_values(source, target): ...\ndef make_material_request(source_name, target_doclist=None): ...\ndef make_delivery_note(source_name, target_doclist=None): ...\ndef make_sales_invoice(source_name, target_doclist=None): ...\ndef make_maintenance_schedule(source_name, target_doclist=None): ...\ndef make_maintenance_visit(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_delivery_note", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002483.py"} {"focal_file": "selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_sales_invoice", "tests": "import unittest\n\nclass Test_make_sales_invoice(unittest.TestCase):\n def test_make_sales_invoice(self):\n from selling.doctype.sales_order.sales_order import make_sales_invoice\n so = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_sales_invoice, so.doc.name)\n sales_order = webnotes.bean('Sales Order', so.doc.name)\n sales_order.submit()\n si = make_sales_invoice(so.doc.name)\n self.assertEquals(si[0]['doctype'], 'Sales Invoice')\n self.assertEquals(len(si), len(sales_order.doclist))\n self.assertEquals(len([d for d in si if d['doctype'] == 'Sales Invoice Item']), 1)\n si = webnotes.bean(si)\n si.doc.posting_date = '2013-10-10'\n si.insert()\n si.submit()\n si1 = make_sales_invoice(so.doc.name)\n self.assertEquals(len([d for d in si1 if d['doctype'] == 'Sales Invoice Item']), 0)\n", "method_code": "def make_sales_invoice(source_name, target_doclist=None):\n\n def set_missing_values(source, target):\n bean = webnotes.bean(target)\n bean.doc.is_pos = 0\n bean.run_method('onload_post_render')\n\n def update_item(obj, target, source_parent):\n target.export_amount = flt(obj.export_amount) - flt(obj.billed_amt)\n target.amount = target.export_amount * flt(source_parent.conversion_rate)\n target.qty = obj.export_rate and target.export_amount / flt(obj.export_rate) or obj.qty\n doclist = get_mapped_doclist('Sales Order', source_name, {'Sales Order': {'doctype': 'Sales Invoice', 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Sales Invoice Item', 'field_map': {'name': 'so_detail', 'parent': 'sales_order', 'reserved_warehouse': 'warehouse'}, 'postprocess': update_item, 'condition': lambda doc: doc.amount == 0 or doc.billed_amt < doc.export_amount}, 'Sales Taxes and Charges': {'doctype': 'Sales Taxes and Charges', 'add_if_empty': True}, 'Sales Team': {'doctype': 'Sales Team', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_sales_invoice(source_name, target_doclist=None): ...\ndef set_missing_values(source, target): ...\ndef make_material_request(source_name, target_doclist=None): ...\ndef make_delivery_note(source_name, target_doclist=None): ...\ndef make_sales_invoice(source_name, target_doclist=None): ...\ndef make_maintenance_schedule(source_name, target_doclist=None): ...\ndef make_maintenance_visit(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_sales_invoice", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002484.py"} {"focal_file": "selling/doctype/shopping_cart_settings/shopping_cart_settings.py", "focal_class": null, "focal_method": "validate_exchange_rates_exist", "tests": "import unittest\n\nclass Test_validate_exchange_rates_exist(unittest.TestCase):\n def test_exchange_rate_exists(self):\n webnotes.conn.sql('delete from `tabCurrency Exchange`')\n cart_settings = self.test_price_list_territory_overlap()\n controller = cart_settings.make_controller()\n self.assertRaises(ShoppingCartSetupError, controller.validate_exchange_rates_exist)\n from setup.doctype.currency_exchange.test_currency_exchange import test_records as currency_exchange_records\n webnotes.bean(currency_exchange_records[0]).insert()\n controller.validate_exchange_rates_exist()\n", "method_code": " def validate_exchange_rates_exist(self):\n \"\"\"check if exchange rates exist for all Price List currencies (to company's currency)\"\"\"\n company_currency = webnotes.conn.get_value('Company', self.doc.company, 'default_currency')\n if not company_currency:\n msgprint(_('Please specify currency in Company') + ': ' + self.doc.company, raise_exception=ShoppingCartSetupError)\n price_list_currency_map = webnotes.conn.get_values('Price List', [d.selling_price_list for d in self.doclist.get({'parentfield': 'price_lists'})], 'currency')\n for price_list, currency in price_list_currency_map.items():\n if not currency:\n webnotes.throw('%s: %s' % (_('Currency is missing for Price List'), price_list))\n expected_to_exist = [currency + '-' + company_currency for currency in price_list_currency_map.values() if currency != company_currency]\n if expected_to_exist:\n exists = webnotes.conn.sql_list('select name from `tabCurrency Exchange`\\n\\t\\t\\t\\twhere name in (%s)' % (', '.join(['%s'] * len(expected_to_exist)),), tuple(expected_to_exist))\n missing = list(set(expected_to_exist).difference(exists))\n if missing:\n msgprint(_('Missing Currency Exchange Rates for' + ': ' + comma_and(missing)), raise_exception=ShoppingCartSetupError)\n ", "context": "class DocType(DocListController):\n def validate_exchange_rates_exist(self): ...\n def onload(self): ...\n def validate(self): ...\n def on_update(self): ...\n def validate_overlapping_territories(self, parentfield, fieldname): ...\n def validate_price_lists(self): ...\n def validate_tax_masters(self): ...\n def get_territory_name_map(self, parentfield, fieldname): ...\n def get_name_from_territory(self, territory, parentfield, fieldname): ...\n def get_price_list(self, billing_territory): ...\n def get_tax_master(self, billing_territory): ...\n def get_shipping_rules(self, shipping_territory): ...\n def get_territory_ancestry(self, territory): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_exchange_rate_exists", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002485.py"} {"focal_file": "selling/doctype/lead/lead.py", "focal_class": null, "focal_method": "make_customer", "tests": "import unittest\n\nclass Test_make_customer(unittest.TestCase):\n def test_make_customer(self):\n from selling.doctype.lead.lead import make_customer\n customer = make_customer('_T-Lead-00001')\n self.assertEquals(customer[0]['doctype'], 'Customer')\n self.assertEquals(customer[0]['lead_name'], '_T-Lead-00001')\n customer[0].customer_group = '_Test Customer Group'\n webnotes.bean(customer).insert()\n", "method_code": "def make_customer(source_name, target_doclist=None):\n return _make_customer(source_name, target_doclist)", "context": "@webnotes.whitelist()\ndef make_customer(source_name, target_doclist=None): ...\ndef make_customer(source_name, target_doclist=None): ...\ndef _make_customer(source_name, target_doclist=None, ignore_permissions=False): ...\ndef make_opportunity(source_name, target_doclist=None): ...\ndef get_lead_owner(doctype, txt, searchfield, start, page_len, filters): ...\ndef create_contact(contact_details): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_customer", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002486.py"} {"focal_file": "manufacturing/doctype/bom/bom.py", "focal_class": null, "focal_method": "get_bom_items_as_dict", "tests": "import unittest\n\nclass Test_get_bom_items_as_dict(unittest.TestCase):\n def test_get_items(self):\n from manufacturing.doctype.bom.bom import get_bom_items_as_dict\n items_dict = get_bom_items_as_dict(bom='BOM/_Test FG Item 2/001', qty=1, fetch_exploded=0)\n self.assertTrue(test_records[2][1]['item_code'] in items_dict)\n self.assertTrue(test_records[2][2]['item_code'] in items_dict)\n self.assertEquals(len(items_dict.values()), 2)\n", "method_code": "def get_bom_items_as_dict(bom, qty=1, fetch_exploded=1):\n item_dict = {}\n query = 'select \\n\\t\\t\\t\\tbom_item.item_code,\\n\\t\\t\\t\\titem.item_name,\\n\\t\\t\\t\\tifnull(sum(bom_item.qty_consumed_per_unit),0) * %(qty)s as qty, \\n\\t\\t\\t\\titem.description, \\n\\t\\t\\t\\titem.stock_uom,\\n\\t\\t\\t\\titem.default_warehouse,\\n\\t\\t\\t\\titem.purchase_account as expense_account,\\n\\t\\t\\t\\titem.cost_center\\n\\t\\t\\tfrom \\n\\t\\t\\t\\t`tab%(table)s` bom_item, `tabItem` item \\n\\t\\t\\twhere \\n\\t\\t\\t\\tbom_item.docstatus < 2 \\n\\t\\t\\t\\tand bom_item.parent = \"%(bom)s\"\\n\\t\\t\\t\\tand item.name = bom_item.item_code \\n\\t\\t\\t\\t%(conditions)s\\n\\t\\t\\t\\tgroup by item_code, stock_uom'\n if fetch_exploded:\n items = webnotes.conn.sql(query % {'qty': qty, 'table': 'BOM Explosion Item', 'bom': bom, 'conditions': \"and ifnull(item.is_pro_applicable, 'No') = 'No'\\n\\t\\t\\t\\t\\tand ifnull(item.is_sub_contracted_item, 'No') = 'No' \"}, as_dict=True)\n else:\n items = webnotes.conn.sql(query % {'qty': qty, 'table': 'BOM Item', 'bom': bom, 'conditions': ''}, as_dict=True)\n for item in items:\n if item_dict.has_key(item.item_code):\n item_dict[item.item_code]['qty'] += flt(item.qty)\n else:\n item_dict[item.item_code] = item\n return item_dict", "context": "def get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_get_items", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002487.py"} {"focal_file": "manufacturing/doctype/bom/bom.py", "focal_class": null, "focal_method": "get_bom_items", "tests": "import unittest\n\nclass Test_get_bom_items(unittest.TestCase):\n def test_get_items_list(self):\n from manufacturing.doctype.bom.bom import get_bom_items\n self.assertEquals(len(get_bom_items(bom='BOM/_Test FG Item 2/001', qty=1, fetch_exploded=1)), 3)\n", "method_code": "def get_bom_items(bom, qty=1, fetch_exploded=1):\n items = get_bom_items_as_dict(bom, qty, fetch_exploded).values()\n items.sort(lambda a, b: a.item_code > b.item_code and 1 or -1)\n return items", "context": "@webnotes.whitelist()\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_get_items_list", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002488.py"} {"focal_file": "stock/doctype/purchase_receipt/test_purchase_receipt.py", "focal_class": null, "focal_method": "set_perpetual_inventory", "tests": "import unittest\n\nclass Test_set_perpetual_inventory(unittest.TestCase):\n def test_purchase_receipt_no_gl_entry(self):\n self._clear_stock_account_balance()\n set_perpetual_inventory(0)\n pr = webnotes.bean(copy=test_records[0])\n pr.insert()\n pr.submit()\n stock_value, stock_value_difference = webnotes.conn.get_value('Stock Ledger Entry', {'voucher_type': 'Purchase Receipt', 'voucher_no': pr.doc.name, 'item_code': '_Test Item', 'warehouse': '_Test Warehouse - _TC'}, ['stock_value', 'stock_value_difference'])\n self.assertEqual(stock_value, 375)\n self.assertEqual(stock_value_difference, 375)\n bin_stock_value = webnotes.conn.get_value('Bin', {'item_code': '_Test Item', 'warehouse': '_Test Warehouse - _TC'}, 'stock_value')\n self.assertEqual(bin_stock_value, 375)\n self.assertFalse(get_gl_entries('Purchase Receipt', pr.doc.name))\n\n def test_purchase_receipt_gl_entry(self):\n self._clear_stock_account_balance()\n set_perpetual_inventory()\n self.assertEqual(cint(webnotes.defaults.get_global_default('auto_accounting_for_stock')), 1)\n pr = webnotes.bean(copy=test_records[0])\n pr.insert()\n pr.submit()\n gl_entries = get_gl_entries('Purchase Receipt', pr.doc.name)\n self.assertTrue(gl_entries)\n stock_in_hand_account = webnotes.conn.get_value('Account', {'master_name': pr.doclist[1].warehouse})\n fixed_asset_account = webnotes.conn.get_value('Account', {'master_name': pr.doclist[2].warehouse})\n expected_values = {stock_in_hand_account: [375.0, 0.0], fixed_asset_account: [375.0, 0.0], 'Stock Received But Not Billed - _TC': [0.0, 750.0]}\n for gle in gl_entries:\n self.assertEquals(expected_values[gle.account][0], gle.debit)\n self.assertEquals(expected_values[gle.account][1], gle.credit)\n pr.cancel()\n self.assertFalse(get_gl_entries('Purchase Receipt', pr.doc.name))\n set_perpetual_inventory(0)\n", "method_code": "def set_perpetual_inventory(enable=1):\n accounts_settings = webnotes.bean('Accounts Settings')\n accounts_settings.doc.auto_accounting_for_stock = enable\n accounts_settings.save()", "context": "def set_perpetual_inventory(enable=1): ...\ndef get_gl_entries(voucher_type, voucher_no): ...\ndef set_perpetual_inventory(enable=1): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_purchase_receipt_no_gl_entry", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002489.py"} {"focal_file": "stock/doctype/serial_no/serial_no.py", "focal_class": null, "focal_method": "get_serial_nos", "tests": "import unittest\n\nclass Test_get_serial_nos(unittest.TestCase):\n def test_serialized_cancel(self):\n from stock.doctype.serial_no.serial_no import get_serial_nos\n dn = self.test_serialized()\n dn.cancel()\n serial_nos = get_serial_nos(dn.doclist[1].serial_no)\n self.assertEquals(webnotes.conn.get_value('Serial No', serial_nos[0], 'status'), 'Available')\n self.assertEquals(webnotes.conn.get_value('Serial No', serial_nos[0], 'warehouse'), '_Test Warehouse - _TC')\n self.assertFalse(webnotes.conn.get_value('Serial No', serial_nos[0], 'delivery_document_no'))\n", "method_code": "def get_serial_nos(serial_no):\n return [s.strip() for s in cstr(serial_no).strip().upper().replace(',', '\\n').split('\\n') if s.strip()]", "context": "def get_serial_nos(serial_no): ...\ndef process_serial_no(sle): ...\ndef validate_serial_no(sle, item_det): ...\ndef update_serial_nos(sle, item_det): ...\ndef get_item_details(item_code): ...\ndef get_serial_nos(serial_no): ...\ndef make_serial_no(serial_no, sle): ...\ndef update_serial_nos_after_submit(controller, parentfield): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_serialized_cancel", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002490.py"} {"focal_file": "stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_purchase_order", "tests": "import unittest\n\nclass Test_make_purchase_order(unittest.TestCase):\n def test_make_purchase_order(self):\n from stock.doctype.material_request.material_request import make_purchase_order\n mr = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_purchase_order, mr.doc.name)\n mr = webnotes.bean('Material Request', mr.doc.name)\n mr.submit()\n po = make_purchase_order(mr.doc.name)\n self.assertEquals(po[0]['doctype'], 'Purchase Order')\n self.assertEquals(len(po), len(mr.doclist))\n", "method_code": "def make_purchase_order(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n doclist = get_mapped_doclist('Material Request', source_name, {'Material Request': {'doctype': 'Purchase Order', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Purchase']}}, 'Material Request Item': {'doctype': 'Purchase Order Item', 'field_map': [['name', 'prevdoc_detail_docname'], ['parent', 'prevdoc_docname'], ['parenttype', 'prevdoc_doctype'], ['uom', 'stock_uom'], ['uom', 'uom']], 'postprocess': update_item}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef update_completed_qty(controller, caller_method): ...\ndef _update_requested_qty(controller, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doclist): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doclist=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doclist=None): ...\ndef make_stock_entry(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_purchase_order", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002491.py"} {"focal_file": "stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_supplier_quotation", "tests": "import unittest\n\nclass Test_make_supplier_quotation(unittest.TestCase):\n def test_make_supplier_quotation(self):\n from stock.doctype.material_request.material_request import make_supplier_quotation\n mr = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_supplier_quotation, mr.doc.name)\n mr = webnotes.bean('Material Request', mr.doc.name)\n mr.submit()\n sq = make_supplier_quotation(mr.doc.name)\n self.assertEquals(sq[0]['doctype'], 'Supplier Quotation')\n self.assertEquals(len(sq), len(mr.doclist))\n", "method_code": "def make_supplier_quotation(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n doclist = get_mapped_doclist('Material Request', source_name, {'Material Request': {'doctype': 'Supplier Quotation', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Purchase']}}, 'Material Request Item': {'doctype': 'Supplier Quotation Item', 'field_map': {'name': 'prevdoc_detail_docname', 'parent': 'prevdoc_docname', 'parenttype': 'prevdoc_doctype'}}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_supplier_quotation(source_name, target_doclist=None): ...\ndef update_completed_qty(controller, caller_method): ...\ndef _update_requested_qty(controller, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doclist): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doclist=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doclist=None): ...\ndef make_stock_entry(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_supplier_quotation", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002492.py"} {"focal_file": "stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_stock_entry", "tests": "import unittest\n\nclass Test_make_stock_entry(unittest.TestCase):\n def test_make_stock_entry(self):\n from stock.doctype.material_request.material_request import make_stock_entry\n mr = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_stock_entry, mr.doc.name)\n mr = webnotes.bean('Material Request', mr.doc.name)\n mr.doc.material_request_type = 'Transfer'\n mr.submit()\n se = make_stock_entry(mr.doc.name)\n self.assertEquals(se[0]['doctype'], 'Stock Entry')\n self.assertEquals(len(se), len(mr.doclist))\n\n def test_incorrect_mapping_of_stock_entry(self):\n mr = webnotes.bean(copy=test_records[0])\n mr.doc.material_request_type = 'Transfer'\n mr.insert()\n mr.submit()\n from stock.doctype.material_request.material_request import make_stock_entry\n se_doclist = make_stock_entry(mr.doc.name)\n se_doclist[0].update({'posting_date': '2013-03-01', 'posting_time': '00:00', 'fiscal_year': '_Test Fiscal Year 2013'})\n se_doclist[1].update({'qty': 60.0, 'transfer_qty': 60.0, 's_warehouse': '_Test Warehouse - _TC', 't_warehouse': '_Test Warehouse 1 - _TC', 'incoming_rate': 1.0})\n se_doclist[2].update({'qty': 3.0, 'transfer_qty': 3.0, 's_warehouse': '_Test Warehouse 1 - _TC', 'incoming_rate': 1.0})\n se = webnotes.bean(copy=se_doclist)\n self.assertRaises(webnotes.MappingMismatchError, se.insert)\n", "method_code": "def make_stock_entry(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n\n def update_item(obj, target, source_parent):\n target.conversion_factor = 1\n target.qty = flt(obj.qty) - flt(obj.ordered_qty)\n target.transfer_qty = flt(obj.qty) - flt(obj.ordered_qty)\n\n def set_missing_values(source, target):\n target[0].purpose = 'Material Transfer'\n se = webnotes.bean(target)\n se.run_method('get_stock_and_rate')\n doclist = get_mapped_doclist('Material Request', source_name, {'Material Request': {'doctype': 'Stock Entry', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Transfer']}}, 'Material Request Item': {'doctype': 'Stock Entry Detail', 'field_map': {'name': 'material_request_item', 'parent': 'material_request', 'uom': 'stock_uom', 'warehouse': 't_warehouse'}, 'postprocess': update_item}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_stock_entry(source_name, target_doclist=None): ...\ndef update_completed_qty(controller, caller_method): ...\ndef _update_requested_qty(controller, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doclist): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doclist=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doclist=None): ...\ndef make_stock_entry(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/test_final_med_app", "test_name": "test_make_stock_entry", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002493.py"} {"focal_file": "hr/doctype/leave_block_list/leave_block_list.py", "focal_class": null, "focal_method": "get_applicable_block_dates", "tests": "import unittest\n\nclass Test_get_applicable_block_dates(unittest.TestCase):\n def test_get_applicable_block_dates(self):\n webnotes.session.user = 'test@example.com'\n webnotes.conn.set_value('Department', '_Test Department', 'leave_block_list', '_Test Leave Block List')\n self.assertTrue('2013-01-02' in [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03')])\n\n def test_get_applicable_block_dates_for_allowed_user(self):\n webnotes.session.user = 'test1@example.com'\n webnotes.conn.set_value('Department', '_Test Department 1', 'leave_block_list', '_Test Leave Block List')\n self.assertEquals([], [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03')])\n\n def test_get_applicable_block_dates_all_lists(self):\n webnotes.session.user = 'test1@example.com'\n webnotes.conn.set_value('Department', '_Test Department 1', 'leave_block_list', '_Test Leave Block List')\n self.assertTrue('2013-01-02' in [d.block_date for d in get_applicable_block_dates('2013-01-01', '2013-01-03', all_lists=True)])\n", "method_code": "def get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False):\n block_dates = []\n for block_list in get_applicable_block_lists(employee, company, all_lists):\n block_dates.extend(webnotes.conn.sql('select block_date, reason \\n\\t\\t\\tfrom `tabLeave Block List Date` where parent=%s \\n\\t\\t\\tand block_date between %s and %s', (block_list, from_date, to_date), as_dict=1))\n return block_dates", "context": "@webnotes.whitelist()\ndef get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False): ...\ndef get_applicable_block_dates(from_date, to_date, employee=None, company=None, all_lists=False): ...\ndef get_applicable_block_lists(employee=None, company=None, all_lists=False): ...\ndef is_user_in_allow_list(block_list): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_get_applicable_block_dates", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002494.py"} {"focal_file": "buying/doctype/supplier_quotation/supplier_quotation.py", "focal_class": null, "focal_method": "make_purchase_order", "tests": "import unittest\n\nclass Test_make_purchase_order(unittest.TestCase):\n def test_make_purchase_order(self):\n from buying.doctype.supplier_quotation.supplier_quotation import make_purchase_order\n sq = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_purchase_order, sq.doc.name)\n sq = webnotes.bean('Supplier Quotation', sq.doc.name)\n sq.submit()\n po = make_purchase_order(sq.doc.name)\n self.assertEquals(po[0]['doctype'], 'Purchase Order')\n self.assertEquals(len(po), len(sq.doclist))\n po[0]['naming_series'] = '_T-Purchase Order-'\n for doc in po:\n if doc.get('item_code'):\n doc['schedule_date'] = '2013-04-12'\n webnotes.bean(po).insert()\n", "method_code": "def make_purchase_order(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n\n def set_missing_values(source, target):\n bean = webnotes.bean(target)\n bean.run_method('set_missing_values')\n bean.run_method('get_schedule_dates')\n\n def update_item(obj, target, source_parent):\n target.conversion_factor = 1\n doclist = get_mapped_doclist('Supplier Quotation', source_name, {'Supplier Quotation': {'doctype': 'Purchase Order', 'validation': {'docstatus': ['=', 1]}}, 'Supplier Quotation Item': {'doctype': 'Purchase Order Item', 'field_map': [['name', 'supplier_quotation_item'], ['parent', 'supplier_quotation'], ['uom', 'stock_uom'], ['uom', 'uom'], ['prevdoc_detail_docname', 'prevdoc_detail_docname'], ['prevdoc_doctype', 'prevdoc_doctype'], ['prevdoc_docname', 'prevdoc_docname']], 'postprocess': update_item}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef make_purchase_order(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_purchase_order", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002495.py"} {"focal_file": "buying/doctype/purchase_order/purchase_order.py", "focal_class": null, "focal_method": "make_purchase_receipt", "tests": "import unittest\n\nclass Test_make_purchase_receipt(unittest.TestCase):\n def test_make_purchase_receipt(self):\n from buying.doctype.purchase_order.purchase_order import make_purchase_receipt\n po = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_purchase_receipt, po.doc.name)\n po = webnotes.bean('Purchase Order', po.doc.name)\n po.submit()\n pr = make_purchase_receipt(po.doc.name)\n pr[0]['supplier_warehouse'] = '_Test Warehouse 1 - _TC'\n pr[0]['posting_date'] = '2013-05-12'\n self.assertEquals(pr[0]['doctype'], 'Purchase Receipt')\n self.assertEquals(len(pr), len(test_records[0]))\n pr[0].naming_series = '_T-Purchase Receipt-'\n pr_bean = webnotes.bean(pr)\n pr_bean.insert()\n", "method_code": "def make_purchase_receipt(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n\n def set_missing_values(source, target):\n bean = webnotes.bean(target)\n bean.run_method('set_missing_values')\n\n def update_item(obj, target, source_parent):\n target.qty = flt(obj.qty) - flt(obj.received_qty)\n target.stock_qty = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.conversion_factor)\n target.import_amount = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.import_rate)\n target.amount = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.purchase_rate)\n doclist = get_mapped_doclist('Purchase Order', source_name, {'Purchase Order': {'doctype': 'Purchase Receipt', 'validation': {'docstatus': ['=', 1]}}, 'Purchase Order Item': {'doctype': 'Purchase Receipt Item', 'field_map': {'name': 'prevdoc_detail_docname', 'parent': 'prevdoc_docname', 'parenttype': 'prevdoc_doctype'}, 'postprocess': update_item, 'condition': lambda doc: doc.received_qty < doc.qty}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_purchase_receipt(source_name, target_doclist=None): ...\ndef make_purchase_receipt(source_name, target_doclist=None): ...\ndef make_purchase_invoice(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_purchase_receipt", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002496.py"} {"focal_file": "buying/doctype/purchase_order/purchase_order.py", "focal_class": null, "focal_method": "make_purchase_invoice", "tests": "import unittest\n\nclass Test_make_purchase_invoice(unittest.TestCase):\n def test_make_purchase_invocie(self):\n from buying.doctype.purchase_order.purchase_order import make_purchase_invoice\n po = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_purchase_invoice, po.doc.name)\n po = webnotes.bean('Purchase Order', po.doc.name)\n po.submit()\n pi = make_purchase_invoice(po.doc.name)\n self.assertEquals(pi[0]['doctype'], 'Purchase Invoice')\n self.assertEquals(len(pi), len(test_records[0]))\n pi[0]['posting_date'] = '2013-05-12'\n pi[0].bill_no = 'NA'\n webnotes.bean(pi).insert()\n", "method_code": "def make_purchase_invoice(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n\n def set_missing_values(source, target):\n bean = webnotes.bean(target)\n bean.run_method('set_missing_values')\n bean.run_method('set_supplier_defaults')\n\n def update_item(obj, target, source_parent):\n target.import_amount = flt(obj.import_amount) - flt(obj.billed_amt)\n target.amount = target.import_amount * flt(source_parent.conversion_rate)\n if flt(obj.purchase_rate):\n target.qty = target.amount / flt(obj.purchase_rate)\n doclist = get_mapped_doclist('Purchase Order', source_name, {'Purchase Order': {'doctype': 'Purchase Invoice', 'validation': {'docstatus': ['=', 1]}}, 'Purchase Order Item': {'doctype': 'Purchase Invoice Item', 'field_map': {'name': 'po_detail', 'parent': 'purchase_order', 'purchase_rate': 'rate'}, 'postprocess': update_item, 'condition': lambda doc: doc.amount == 0 or doc.billed_amt < doc.import_amount}, 'Purchase Taxes and Charges': {'doctype': 'Purchase Taxes and Charges', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_purchase_invoice(source_name, target_doclist=None): ...\ndef make_purchase_receipt(source_name, target_doclist=None): ...\ndef make_purchase_invoice(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_purchase_invocie", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002497.py"} {"focal_file": "selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_material_request", "tests": "import unittest\n\nclass Test_make_material_request(unittest.TestCase):\n def test_make_material_request(self):\n from selling.doctype.sales_order.sales_order import make_material_request\n so = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_material_request, so.doc.name)\n sales_order = webnotes.bean('Sales Order', so.doc.name)\n sales_order.submit()\n mr = make_material_request(so.doc.name)\n self.assertEquals(mr[0]['material_request_type'], 'Purchase')\n self.assertEquals(len(mr), len(sales_order.doclist))\n", "method_code": "def make_material_request(source_name, target_doclist=None):\n\n def postprocess(source, doclist):\n doclist[0].material_request_type = 'Purchase'\n doclist = get_mapped_doclist('Sales Order', source_name, {'Sales Order': {'doctype': 'Material Request', 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Material Request Item', 'field_map': {'parent': 'sales_order_no', 'reserved_warehouse': 'warehouse', 'stock_uom': 'uom'}}}, target_doclist, postprocess)\n return [d if isinstance(d, dict) else d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_material_request(source_name, target_doclist=None): ...\ndef set_missing_values(source, target): ...\ndef make_material_request(source_name, target_doclist=None): ...\ndef make_delivery_note(source_name, target_doclist=None): ...\ndef make_sales_invoice(source_name, target_doclist=None): ...\ndef make_maintenance_schedule(source_name, target_doclist=None): ...\ndef make_maintenance_visit(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_material_request", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002498.py"} {"focal_file": "selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_delivery_note", "tests": "import unittest\n\nclass Test_make_delivery_note(unittest.TestCase):\n def test_make_delivery_note(self):\n from selling.doctype.sales_order.sales_order import make_delivery_note\n so = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_delivery_note, so.doc.name)\n sales_order = webnotes.bean('Sales Order', so.doc.name)\n sales_order.submit()\n dn = make_delivery_note(so.doc.name)\n self.assertEquals(dn[0]['doctype'], 'Delivery Note')\n self.assertEquals(len(dn), len(sales_order.doclist))\n", "method_code": "def make_delivery_note(source_name, target_doclist=None):\n\n def update_item(obj, target, source_parent):\n target.amount = (flt(obj.qty) - flt(obj.delivered_qty)) * flt(obj.basic_rate)\n target.export_amount = (flt(obj.qty) - flt(obj.delivered_qty)) * flt(obj.export_rate)\n target.qty = flt(obj.qty) - flt(obj.delivered_qty)\n doclist = get_mapped_doclist('Sales Order', source_name, {'Sales Order': {'doctype': 'Delivery Note', 'field_map': {'shipping_address': 'address_display', 'shipping_address_name': 'customer_address'}, 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Delivery Note Item', 'field_map': {'export_rate': 'export_rate', 'name': 'prevdoc_detail_docname', 'parent': 'against_sales_order', 'reserved_warehouse': 'warehouse'}, 'postprocess': update_item, 'condition': lambda doc: doc.delivered_qty < doc.qty}, 'Sales Taxes and Charges': {'doctype': 'Sales Taxes and Charges', 'add_if_empty': True}, 'Sales Team': {'doctype': 'Sales Team', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_delivery_note(source_name, target_doclist=None): ...\ndef set_missing_values(source, target): ...\ndef make_material_request(source_name, target_doclist=None): ...\ndef make_delivery_note(source_name, target_doclist=None): ...\ndef make_sales_invoice(source_name, target_doclist=None): ...\ndef make_maintenance_schedule(source_name, target_doclist=None): ...\ndef make_maintenance_visit(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_delivery_note", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002499.py"} {"focal_file": "selling/doctype/sales_order/sales_order.py", "focal_class": null, "focal_method": "make_sales_invoice", "tests": "import unittest\n\nclass Test_make_sales_invoice(unittest.TestCase):\n def test_make_sales_invoice(self):\n from selling.doctype.sales_order.sales_order import make_sales_invoice\n so = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_sales_invoice, so.doc.name)\n sales_order = webnotes.bean('Sales Order', so.doc.name)\n sales_order.submit()\n si = make_sales_invoice(so.doc.name)\n self.assertEquals(si[0]['doctype'], 'Sales Invoice')\n self.assertEquals(len(si), len(sales_order.doclist))\n self.assertEquals(len([d for d in si if d['doctype'] == 'Sales Invoice Item']), 1)\n si = webnotes.bean(si)\n si.doc.posting_date = '2013-10-10'\n si.insert()\n si.submit()\n si1 = make_sales_invoice(so.doc.name)\n self.assertEquals(len([d for d in si1 if d['doctype'] == 'Sales Invoice Item']), 0)\n", "method_code": "def make_sales_invoice(source_name, target_doclist=None):\n\n def set_missing_values(source, target):\n bean = webnotes.bean(target)\n bean.doc.is_pos = 0\n bean.run_method('onload_post_render')\n\n def update_item(obj, target, source_parent):\n target.export_amount = flt(obj.export_amount) - flt(obj.billed_amt)\n target.amount = target.export_amount * flt(source_parent.conversion_rate)\n target.qty = obj.export_rate and target.export_amount / flt(obj.export_rate) or obj.qty\n doclist = get_mapped_doclist('Sales Order', source_name, {'Sales Order': {'doctype': 'Sales Invoice', 'validation': {'docstatus': ['=', 1]}}, 'Sales Order Item': {'doctype': 'Sales Invoice Item', 'field_map': {'name': 'so_detail', 'parent': 'sales_order', 'reserved_warehouse': 'warehouse'}, 'postprocess': update_item, 'condition': lambda doc: doc.amount == 0 or doc.billed_amt < doc.export_amount}, 'Sales Taxes and Charges': {'doctype': 'Sales Taxes and Charges', 'add_if_empty': True}, 'Sales Team': {'doctype': 'Sales Team', 'add_if_empty': True}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_sales_invoice(source_name, target_doclist=None): ...\ndef set_missing_values(source, target): ...\ndef make_material_request(source_name, target_doclist=None): ...\ndef make_delivery_note(source_name, target_doclist=None): ...\ndef make_sales_invoice(source_name, target_doclist=None): ...\ndef make_maintenance_schedule(source_name, target_doclist=None): ...\ndef make_maintenance_visit(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_sales_invoice", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002500.py"} {"focal_file": "selling/doctype/shopping_cart_settings/shopping_cart_settings.py", "focal_class": null, "focal_method": "validate_exchange_rates_exist", "tests": "import unittest\n\nclass Test_validate_exchange_rates_exist(unittest.TestCase):\n def test_exchange_rate_exists(self):\n webnotes.conn.sql('delete from `tabCurrency Exchange`')\n cart_settings = self.test_price_list_territory_overlap()\n controller = cart_settings.make_controller()\n self.assertRaises(ShoppingCartSetupError, controller.validate_exchange_rates_exist)\n from setup.doctype.currency_exchange.test_currency_exchange import test_records as currency_exchange_records\n webnotes.bean(currency_exchange_records[0]).insert()\n controller.validate_exchange_rates_exist()\n", "method_code": " def validate_exchange_rates_exist(self):\n \"\"\"check if exchange rates exist for all Price List currencies (to company's currency)\"\"\"\n company_currency = webnotes.conn.get_value('Company', self.doc.company, 'default_currency')\n if not company_currency:\n msgprint(_('Please specify currency in Company') + ': ' + self.doc.company, raise_exception=ShoppingCartSetupError)\n price_list_currency_map = webnotes.conn.get_values('Price List', [d.selling_price_list for d in self.doclist.get({'parentfield': 'price_lists'})], 'currency')\n for price_list, currency in price_list_currency_map.items():\n if not currency:\n webnotes.throw('%s: %s' % (_('Currency is missing for Price List'), price_list))\n expected_to_exist = [currency + '-' + company_currency for currency in price_list_currency_map.values() if currency != company_currency]\n if expected_to_exist:\n exists = webnotes.conn.sql_list('select name from `tabCurrency Exchange`\\n\\t\\t\\t\\twhere name in (%s)' % (', '.join(['%s'] * len(expected_to_exist)),), tuple(expected_to_exist))\n missing = list(set(expected_to_exist).difference(exists))\n if missing:\n msgprint(_('Missing Currency Exchange Rates for' + ': ' + comma_and(missing)), raise_exception=ShoppingCartSetupError)\n ", "context": "class DocType(DocListController):\n def validate_exchange_rates_exist(self): ...\n def onload(self): ...\n def validate(self): ...\n def on_update(self): ...\n def validate_overlapping_territories(self, parentfield, fieldname): ...\n def validate_price_lists(self): ...\n def validate_tax_masters(self): ...\n def get_territory_name_map(self, parentfield, fieldname): ...\n def get_name_from_territory(self, territory, parentfield, fieldname): ...\n def get_price_list(self, billing_territory): ...\n def get_tax_master(self, billing_territory): ...\n def get_shipping_rules(self, shipping_territory): ...\n def get_territory_ancestry(self, territory): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_exchange_rate_exists", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002501.py"} {"focal_file": "selling/doctype/lead/lead.py", "focal_class": null, "focal_method": "make_customer", "tests": "import unittest\n\nclass Test_make_customer(unittest.TestCase):\n def test_make_customer(self):\n from selling.doctype.lead.lead import make_customer\n customer = make_customer('_T-Lead-00001')\n self.assertEquals(customer[0]['doctype'], 'Customer')\n self.assertEquals(customer[0]['lead_name'], '_T-Lead-00001')\n customer[0].customer_group = '_Test Customer Group'\n webnotes.bean(customer).insert()\n", "method_code": "def make_customer(source_name, target_doclist=None):\n return _make_customer(source_name, target_doclist)", "context": "@webnotes.whitelist()\ndef make_customer(source_name, target_doclist=None): ...\ndef make_customer(source_name, target_doclist=None): ...\ndef _make_customer(source_name, target_doclist=None, ignore_permissions=False): ...\ndef make_opportunity(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_customer", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002502.py"} {"focal_file": "manufacturing/doctype/bom/bom.py", "focal_class": null, "focal_method": "get_bom_items_as_dict", "tests": "import unittest\n\nclass Test_get_bom_items_as_dict(unittest.TestCase):\n def test_get_items(self):\n from manufacturing.doctype.bom.bom import get_bom_items_as_dict\n items_dict = get_bom_items_as_dict(bom='BOM/_Test FG Item 2/001', qty=1, fetch_exploded=0)\n self.assertTrue(test_records[2][1]['item_code'] in items_dict)\n self.assertTrue(test_records[2][2]['item_code'] in items_dict)\n self.assertEquals(len(items_dict.values()), 2)\n", "method_code": "def get_bom_items_as_dict(bom, qty=1, fetch_exploded=1):\n item_dict = {}\n query = 'select \\n\\t\\t\\t\\tbom_item.item_code,\\n\\t\\t\\t\\titem.item_name,\\n\\t\\t\\t\\tifnull(sum(bom_item.qty_consumed_per_unit),0) * %(qty)s as qty, \\n\\t\\t\\t\\titem.description, \\n\\t\\t\\t\\titem.stock_uom,\\n\\t\\t\\t\\titem.default_warehouse,\\n\\t\\t\\t\\titem.purchase_account as expense_account,\\n\\t\\t\\t\\titem.cost_center\\n\\t\\t\\tfrom \\n\\t\\t\\t\\t`tab%(table)s` bom_item, `tabItem` item \\n\\t\\t\\twhere \\n\\t\\t\\t\\tbom_item.docstatus < 2 \\n\\t\\t\\t\\tand bom_item.parent = \"%(bom)s\"\\n\\t\\t\\t\\tand item.name = bom_item.item_code \\n\\t\\t\\t\\t%(conditions)s\\n\\t\\t\\t\\tgroup by item_code, stock_uom'\n if fetch_exploded:\n items = webnotes.conn.sql(query % {'qty': qty, 'table': 'BOM Explosion Item', 'bom': bom, 'conditions': \"and ifnull(item.is_pro_applicable, 'No') = 'No'\\n\\t\\t\\t\\t\\tand ifnull(item.is_sub_contracted_item, 'No') = 'No' \"}, as_dict=True)\n else:\n items = webnotes.conn.sql(query % {'qty': qty, 'table': 'BOM Item', 'bom': bom, 'conditions': ''}, as_dict=True)\n for item in items:\n if item_dict.has_key(item.item_code):\n item_dict[item.item_code]['qty'] += flt(item.qty)\n else:\n item_dict[item.item_code] = item\n return item_dict", "context": "def get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_get_items", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002503.py"} {"focal_file": "manufacturing/doctype/bom/bom.py", "focal_class": null, "focal_method": "get_bom_items", "tests": "import unittest\n\nclass Test_get_bom_items(unittest.TestCase):\n def test_get_items_list(self):\n from manufacturing.doctype.bom.bom import get_bom_items\n self.assertEquals(len(get_bom_items(bom='BOM/_Test FG Item 2/001', qty=1, fetch_exploded=1)), 3)\n", "method_code": "def get_bom_items(bom, qty=1, fetch_exploded=1):\n items = get_bom_items_as_dict(bom, qty, fetch_exploded).values()\n items.sort(lambda a, b: a.item_code > b.item_code and 1 or -1)\n return items", "context": "@webnotes.whitelist()\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items_as_dict(bom, qty=1, fetch_exploded=1): ...\ndef get_bom_items(bom, qty=1, fetch_exploded=1): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_get_items_list", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002504.py"} {"focal_file": "stock/doctype/purchase_receipt/test_purchase_receipt.py", "focal_class": null, "focal_method": "set_perpetual_inventory", "tests": "import unittest\n\nclass Test_set_perpetual_inventory(unittest.TestCase):\n def test_purchase_receipt_no_gl_entry(self):\n self._clear_stock_account_balance()\n set_perpetual_inventory(0)\n pr = webnotes.bean(copy=test_records[0])\n pr.insert()\n pr.submit()\n stock_value, stock_value_difference = webnotes.conn.get_value('Stock Ledger Entry', {'voucher_type': 'Purchase Receipt', 'voucher_no': pr.doc.name, 'item_code': '_Test Item', 'warehouse': '_Test Warehouse - _TC'}, ['stock_value', 'stock_value_difference'])\n self.assertEqual(stock_value, 375)\n self.assertEqual(stock_value_difference, 375)\n bin_stock_value = webnotes.conn.get_value('Bin', {'item_code': '_Test Item', 'warehouse': '_Test Warehouse - _TC'}, 'stock_value')\n self.assertEqual(bin_stock_value, 375)\n self.assertFalse(get_gl_entries('Purchase Receipt', pr.doc.name))\n\n def test_purchase_receipt_gl_entry(self):\n self._clear_stock_account_balance()\n set_perpetual_inventory()\n self.assertEqual(cint(webnotes.defaults.get_global_default('auto_accounting_for_stock')), 1)\n pr = webnotes.bean(copy=test_records[0])\n pr.insert()\n pr.submit()\n gl_entries = get_gl_entries('Purchase Receipt', pr.doc.name)\n self.assertTrue(gl_entries)\n stock_in_hand_account = webnotes.conn.get_value('Account', {'master_name': pr.doclist[1].warehouse})\n fixed_asset_account = webnotes.conn.get_value('Account', {'master_name': pr.doclist[2].warehouse})\n expected_values = {stock_in_hand_account: [375.0, 0.0], fixed_asset_account: [375.0, 0.0], 'Stock Received But Not Billed - _TC': [0.0, 750.0]}\n for gle in gl_entries:\n self.assertEquals(expected_values[gle.account][0], gle.debit)\n self.assertEquals(expected_values[gle.account][1], gle.credit)\n pr.cancel()\n self.assertFalse(get_gl_entries('Purchase Receipt', pr.doc.name))\n set_perpetual_inventory(0)\n", "method_code": "def set_perpetual_inventory(enable=1):\n accounts_settings = webnotes.bean('Accounts Settings')\n accounts_settings.doc.auto_accounting_for_stock = enable\n accounts_settings.save()", "context": "def set_perpetual_inventory(enable=1): ...\ndef get_gl_entries(voucher_type, voucher_no): ...\ndef set_perpetual_inventory(enable=1): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_purchase_receipt_no_gl_entry", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002505.py"} {"focal_file": "stock/doctype/serial_no/serial_no.py", "focal_class": null, "focal_method": "get_serial_nos", "tests": "import unittest\n\nclass Test_get_serial_nos(unittest.TestCase):\n def test_serialized_cancel(self):\n from stock.doctype.serial_no.serial_no import get_serial_nos\n dn = self.test_serialized()\n dn.cancel()\n serial_nos = get_serial_nos(dn.doclist[1].serial_no)\n self.assertEquals(webnotes.conn.get_value('Serial No', serial_nos[0], 'status'), 'Available')\n self.assertEquals(webnotes.conn.get_value('Serial No', serial_nos[0], 'warehouse'), '_Test Warehouse - _TC')\n self.assertFalse(webnotes.conn.get_value('Serial No', serial_nos[0], 'delivery_document_no'))\n\n def test_serialize_status(self):\n from stock.doctype.serial_no.serial_no import SerialNoStatusError, get_serial_nos\n from stock.doctype.stock_entry.test_stock_entry import make_serialized_item\n se = make_serialized_item()\n serial_nos = get_serial_nos(se.doclist[1].serial_no)\n sr = webnotes.bean('Serial No', serial_nos[0])\n sr.doc.status = 'Not Available'\n sr.save()\n dn = webnotes.bean(copy=test_records[0])\n dn.doclist[1].item_code = '_Test Serialized Item With Series'\n dn.doclist[1].qty = 1\n dn.doclist[1].serial_no = serial_nos[0]\n dn.insert()\n self.assertRaises(SerialNoStatusError, dn.submit)\n", "method_code": "def get_serial_nos(serial_no):\n return [s.strip() for s in cstr(serial_no).strip().upper().replace(',', '\\n').split('\\n') if s.strip()]", "context": "def get_serial_nos(serial_no): ...\ndef process_serial_no(sle): ...\ndef validate_serial_no(sle, item_det): ...\ndef update_serial_nos(sle, item_det): ...\ndef get_item_details(item_code): ...\ndef get_serial_nos(serial_no): ...\ndef make_serial_no(serial_no, sle): ...\ndef update_serial_nos_after_submit(controller, parentfield): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_serialized_cancel", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002506.py"} {"focal_file": "stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_purchase_order", "tests": "import unittest\n\nclass Test_make_purchase_order(unittest.TestCase):\n def test_make_purchase_order(self):\n from stock.doctype.material_request.material_request import make_purchase_order\n mr = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_purchase_order, mr.doc.name)\n mr = webnotes.bean('Material Request', mr.doc.name)\n mr.submit()\n po = make_purchase_order(mr.doc.name)\n self.assertEquals(po[0]['doctype'], 'Purchase Order')\n self.assertEquals(len(po), len(mr.doclist))\n", "method_code": "def make_purchase_order(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n doclist = get_mapped_doclist('Material Request', source_name, {'Material Request': {'doctype': 'Purchase Order', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Purchase']}}, 'Material Request Item': {'doctype': 'Purchase Order Item', 'field_map': [['name', 'prevdoc_detail_docname'], ['parent', 'prevdoc_docname'], ['parenttype', 'prevdoc_doctype'], ['uom', 'stock_uom'], ['uom', 'uom']], 'postprocess': update_item}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef update_completed_qty(controller, caller_method): ...\ndef _update_requested_qty(controller, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doclist): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doclist=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doclist=None): ...\ndef make_stock_entry(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_purchase_order", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002507.py"} {"focal_file": "stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_supplier_quotation", "tests": "import unittest\n\nclass Test_make_supplier_quotation(unittest.TestCase):\n def test_make_supplier_quotation(self):\n from stock.doctype.material_request.material_request import make_supplier_quotation\n mr = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_supplier_quotation, mr.doc.name)\n mr = webnotes.bean('Material Request', mr.doc.name)\n mr.submit()\n sq = make_supplier_quotation(mr.doc.name)\n self.assertEquals(sq[0]['doctype'], 'Supplier Quotation')\n self.assertEquals(len(sq), len(mr.doclist))\n", "method_code": "def make_supplier_quotation(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n doclist = get_mapped_doclist('Material Request', source_name, {'Material Request': {'doctype': 'Supplier Quotation', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Purchase']}}, 'Material Request Item': {'doctype': 'Supplier Quotation Item', 'field_map': {'name': 'prevdoc_detail_docname', 'parent': 'prevdoc_docname', 'parenttype': 'prevdoc_doctype'}}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_supplier_quotation(source_name, target_doclist=None): ...\ndef update_completed_qty(controller, caller_method): ...\ndef _update_requested_qty(controller, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doclist): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doclist=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doclist=None): ...\ndef make_stock_entry(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_supplier_quotation", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002508.py"} {"focal_file": "stock/doctype/material_request/material_request.py", "focal_class": null, "focal_method": "make_stock_entry", "tests": "import unittest\n\nclass Test_make_stock_entry(unittest.TestCase):\n def test_make_stock_entry(self):\n from stock.doctype.material_request.material_request import make_stock_entry\n mr = webnotes.bean(copy=test_records[0]).insert()\n self.assertRaises(webnotes.ValidationError, make_stock_entry, mr.doc.name)\n mr = webnotes.bean('Material Request', mr.doc.name)\n mr.doc.material_request_type = 'Transfer'\n mr.submit()\n se = make_stock_entry(mr.doc.name)\n self.assertEquals(se[0]['doctype'], 'Stock Entry')\n self.assertEquals(len(se), len(mr.doclist))\n\n def test_incorrect_mapping_of_stock_entry(self):\n mr = webnotes.bean(copy=test_records[0])\n mr.doc.material_request_type = 'Transfer'\n mr.insert()\n mr.submit()\n from stock.doctype.material_request.material_request import make_stock_entry\n se_doclist = make_stock_entry(mr.doc.name)\n se_doclist[0].update({'posting_date': '2013-03-01', 'posting_time': '00:00', 'fiscal_year': '_Test Fiscal Year 2013'})\n se_doclist[1].update({'qty': 60.0, 'transfer_qty': 60.0, 's_warehouse': '_Test Warehouse - _TC', 't_warehouse': '_Test Warehouse 1 - _TC', 'incoming_rate': 1.0})\n se_doclist[2].update({'qty': 3.0, 'transfer_qty': 3.0, 's_warehouse': '_Test Warehouse 1 - _TC', 'incoming_rate': 1.0})\n se = webnotes.bean(copy=se_doclist)\n self.assertRaises(webnotes.MappingMismatchError, se.insert)\n", "method_code": "def make_stock_entry(source_name, target_doclist=None):\n from webnotes.model.mapper import get_mapped_doclist\n\n def update_item(obj, target, source_parent):\n target.conversion_factor = 1\n target.qty = flt(obj.qty) - flt(obj.ordered_qty)\n target.transfer_qty = flt(obj.qty) - flt(obj.ordered_qty)\n\n def set_missing_values(source, target):\n target[0].purpose = 'Material Transfer'\n se = webnotes.bean(target)\n se.run_method('get_stock_and_rate')\n doclist = get_mapped_doclist('Material Request', source_name, {'Material Request': {'doctype': 'Stock Entry', 'validation': {'docstatus': ['=', 1], 'material_request_type': ['=', 'Transfer']}}, 'Material Request Item': {'doctype': 'Stock Entry Detail', 'field_map': {'name': 'material_request_item', 'parent': 'material_request', 'uom': 'stock_uom', 'warehouse': 't_warehouse'}, 'postprocess': update_item}}, target_doclist, set_missing_values)\n return [d.fields for d in doclist]", "context": "@webnotes.whitelist()\ndef make_stock_entry(source_name, target_doclist=None): ...\ndef update_completed_qty(controller, caller_method): ...\ndef _update_requested_qty(controller, mr_obj, mr_items): ...\ndef set_missing_values(source, target_doclist): ...\ndef update_item(obj, target, source_parent): ...\ndef make_purchase_order(source_name, target_doclist=None): ...\ndef make_purchase_order_based_on_supplier(source_name, target_doclist=None): ...\ndef get_material_requests_based_on_supplier(supplier): ...\ndef make_supplier_quotation(source_name, target_doclist=None): ...\ndef make_stock_entry(source_name, target_doclist=None): ...\n", "repository": "saurabh6790/aimobilize-app-backup", "test_name": "test_make_stock_entry", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002509.py"} {"focal_file": "newrem/converters.py", "focal_class": null, "focal_method": "to_url", "tests": "import unittest\n\nclass Test_to_url(unittest.TestCase):\n def test_apocalypse_to_url(self):\n dt = datetime(2012, 12, 21)\n news = Newspost('Test')\n news.time = dt\n expected = '1356048000'\n self.assertEqual(self.converter.to_url(news), expected)\n", "method_code": " def to_url(self, value):\n return self.freezer(getattr(value, self.field))\n ", "context": "class ModelConverter(BaseConverter):\n def to_url(self, value): ...\n def to_python(self, value): ...\n", "repository": "MostAwesomeDude/dcon", "test_name": "test_apocalypse_to_url", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002510.py"} {"focal_file": "newrem/converters.py", "focal_class": null, "focal_method": "to_python", "tests": "import unittest\n\nclass Test_to_python(unittest.TestCase):\n def test_apocalypse_to_python(self):\n dt = datetime(2012, 12, 21)\n news = Newspost(u'Test')\n news.time = dt\n news.portrait_id = 0\n fragment = '1356048000'\n with self.app.test_request_context():\n db.session.add(news)\n db.session.commit()\n result = self.converter.to_python(fragment)\n db.session.add(result)\n self.assertEqual(result.title, news.title)\n self.assertEqual(result.time, news.time)\n", "method_code": " def to_python(self, value):\n value = self.thawer(value)\n try:\n with self.app.test_request_context():\n obj = self.model.query.filter_by(**{self.field: value}).one()\n except (MultipleResultsFound, NoResultFound):\n raise ValidationError()\n return obj\n ", "context": "class ModelConverter(BaseConverter):\n def to_python(self, value): ...\n def to_url(self, value): ...\n", "repository": "MostAwesomeDude/dcon", "test_name": "test_apocalypse_to_python", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002511.py"} {"focal_file": "newrem/files.py", "focal_class": null, "focal_method": "extend_url", "tests": "import unittest\n\nclass Test_extend_url(unittest.TestCase):\n def test_extend_url_example(self):\n url = 'http://example.com/'\n segments = ['test', 'path']\n expected = 'http://example.com/test/path'\n self.assertEqual(extend_url(url, segments), expected)\n", "method_code": "def extend_url(url, segments):\n \"\"\"\n Extend a URL given a list of segments.\n \"\"\"\n return url + '/'.join(segments)", "context": "def extend_url(url, segments): ...\ndef fp_root(app): ...\ndef url_root(app): ...\ndef extend_url(url, segments): ...\ndef save_file(fp, fs): ...\ndef assets_in_paths(app, segments): ...\n", "repository": "MostAwesomeDude/dcon", "test_name": "test_extend_url_example", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002512.py"} {"focal_file": "newrem/forms.py", "focal_class": null, "focal_method": "label_for_comic", "tests": "import unittest\n\nclass Test_label_for_comic(unittest.TestCase):\n def test_label_for_comic(self):\n comic = FauxComic(1, 'Test', 0)\n expected = u'\"Test\" (0)'\n self.assertEqual(label_for_comic(comic), expected)\n", "method_code": "def label_for_comic(comic):\n return u'\"%s\" (%d)' % (comic.title, comic.position)", "context": "def label_for_comic(comic): ...\ndef makeCU(form): ...\ndef label_for_comic(comic): ...\ndef select_option_for_comics(first, second): ...\ndef select_list_for_comics(comics): ...\n", "repository": "MostAwesomeDude/dcon", "test_name": "test_label_for_comic", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002513.py"} {"focal_file": "newrem/forms.py", "focal_class": null, "focal_method": "select_option_for_comics", "tests": "import unittest\n\nclass Test_select_option_for_comics(unittest.TestCase):\n def test_select_option_for_comics(self):\n first = FauxComic(1, 'First', 0)\n second = FauxComic(2, 'Second', 1)\n expected = (1, u'\"First\" (0) to \"Second\" (1)')\n self.assertEqual(select_option_for_comics(first, second), expected)\n", "method_code": "def select_option_for_comics(first, second):\n first_label = label_for_comic(first)\n second_label = label_for_comic(second)\n return (first.id, u'%s to %s' % (first_label, second_label))", "context": "def select_option_for_comics(first, second): ...\ndef makeCU(form): ...\ndef label_for_comic(comic): ...\ndef select_option_for_comics(first, second): ...\ndef select_list_for_comics(comics): ...\n", "repository": "MostAwesomeDude/dcon", "test_name": "test_select_option_for_comics", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002514.py"} {"focal_file": "newrem/forms.py", "focal_class": null, "focal_method": "select_list_for_comics", "tests": "import unittest\n\nclass Test_select_list_for_comics(unittest.TestCase):\n def test_select_list_for_comics_one(self):\n comics = [FauxComic(1, 'First', 0)]\n expected = [(-1, u'Before \"First\" (0)'), (1, u'After \"First\" (0)')]\n self.assertEqual(select_list_for_comics(comics), expected)\n\n def test_select_list_for_comics_one_id(self):\n comics = [FauxComic(42, 'First', 0)]\n expected = [(-1, u'Before \"First\" (0)'), (42, u'After \"First\" (0)')]\n self.assertEqual(select_list_for_comics(comics), expected)\n\n def test_select_list_for_comics_two(self):\n comics = [FauxComic(1, 'First', 0), FauxComic(2, 'Second', 1)]\n expected = [(-1, u'Before \"First\" (0)'), (1, u'\"First\" (0) to \"Second\" (1)'), (2, u'After \"Second\" (1)')]\n self.assertEqual(select_list_for_comics(comics), expected)\n", "method_code": "def select_list_for_comics(comics):\n if comics:\n first = comics[0]\n l = [(-1, u'Before %s' % label_for_comic(first))]\n if len(comics) > 1:\n for first, second in zip(comics, comics[1:]):\n l.append(select_option_for_comics(first, second))\n last = comics[-1]\n l.append((second.id, u'After %s' % label_for_comic(last)))\n else:\n l.append((comics[0].id, u'After %s' % label_for_comic(comics[0])))\n return l\n else:\n return [(-2, '')]", "context": "def select_list_for_comics(comics): ...\ndef makeCU(form): ...\ndef label_for_comic(comic): ...\ndef select_option_for_comics(first, second): ...\ndef select_list_for_comics(comics): ...\n", "repository": "MostAwesomeDude/dcon", "test_name": "test_select_list_for_comics_one", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002515.py"} {"focal_file": "mozsystemmonitor/mozsystemmonitor/resourcemonitor.py", "focal_class": "SystemResourceMonitor", "focal_method": "record_event", "tests": "import unittest\n\nclass Test_SystemResourceMonitor_record_event(unittest.TestCase):\n def test_events(self):\n monitor = SystemResourceMonitor(poll_interval=0.25)\n monitor.start()\n time.sleep(0.5)\n t0 = time.time()\n monitor.record_event('t0')\n time.sleep(0.5)\n t1 = time.time()\n monitor.record_event('t1')\n time.sleep(0.5)\n monitor.stop()\n events = monitor.events\n self.assertEqual(len(events), 2)\n event = events[0]\n self.assertEqual(event[1], 't0')\n self.assertAlmostEqual(event[0], t0, delta=0.25)\n data = list(monitor.between_events_usage('t0', 't1'))\n self.assertGreater(len(data), 0)\n", "method_code": " def record_event(self, name):\n \"\"\"Record an event as occuring now.\n \n Events are actions that occur at a specific point in time. If you are\n looking for an action that has a duration, see the phase API below.\n \"\"\"\n self.events.append((time.time(), name))\n ", "context": "class SystemResourceMonitor(object):\n def record_event(self, name): ...\n def __init__(self, poll_interval=1.0): ...\n def __del__(self): ...\n def start(self): ...\n def stop(self): ...\n def phase(self, name): ...\n def begin_phase(self, name): ...\n def finish_phase(self, name): ...\n def range_usage(self, start=None, end=None): ...\n def phase_usage(self, phase): ...\n def between_events_usage(self, start_event, end_event): ...\n def aggregate_cpu_percent(self, start=None, end=None, phase=None, per_cpu=True): ...\n def aggregate_cpu_times(self, start=None, end=None, phase=None, per_cpu=True): ...\n def aggregate_io(self, start=None, end=None, phase=None): ...\n def min_memory_available(self, start=None, end=None, phase=None): ...\n def max_memory_percent(self, start=None, end=None, phase=None): ...\n\n self.start_time = None\n self.end_time = None\n self.events = []\n self.phases = OrderedDict()\n self._active_phases = {}\n self._running = False\n self._stopped = False\n self._cpu_cores = len(cpu_percent)\n self._cpu_times_type = type(cpu_times)\n self._cpu_times_len = len(cpu_times)\n self._io_type = type(io)\n self._io_len = len(io)\n self._virt_type = type(virt)\n self._virt_len = len(virt)\n self._swap_type = type(swap)\n self._swap_len = len(swap)\n self._pipe, child_pipe = multiprocessing.Pipe(True)\n self._process = multiprocessing.Process(None, _collect, args=(child_pipe, poll_interval))\n", "repository": "ffledgling/mozbase-testing-temp", "test_name": "test_events", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002516.py"} {"focal_file": "mozsystemmonitor/mozsystemmonitor/resourcemonitor.py", "focal_class": "SystemResourceMonitor", "focal_method": "aggregate_cpu_times", "tests": "import unittest\n\nclass Test_SystemResourceMonitor_aggregate_cpu_times(unittest.TestCase):\n def test_aggregate_cpu(self):\n monitor = SystemResourceMonitor(poll_interval=0.25)\n monitor.start()\n time.sleep(1)\n monitor.stop()\n values = monitor.aggregate_cpu_percent()\n self.assertIsInstance(values, list)\n self.assertEqual(len(values), multiprocessing.cpu_count())\n for v in values:\n self.assertIsInstance(v, float)\n value = monitor.aggregate_cpu_percent(per_cpu=False)\n self.assertIsInstance(value, float)\n values = monitor.aggregate_cpu_times()\n self.assertIsInstance(values, list)\n self.assertGreater(len(values), 0)\n self.assertTrue(hasattr(values[0], 'user'))\n t = type(values[0])\n value = monitor.aggregate_cpu_times(per_cpu=False)\n self.assertIsInstance(value, t)\n", "method_code": " def aggregate_cpu_times(self, start=None, end=None, phase=None, per_cpu=True):\n \"\"\"Obtain the aggregate CPU times for a range.\n \n If per_cpu is True (the default), this returns a list of named tuples.\n Each tuple is as if it were returned by psutil.cpu_times(). If per_cpu\n is False, this returns a single named tuple of the aforementioned type.\n \"\"\"\n empty = [0 for i in range(0, self._cpu_times_len)]\n cpu = [list(empty) for i in range(0, self._cpu_cores)]\n if phase:\n data = self.phase_usage(phase)\n else:\n data = self.range_usage(start, end)\n for usage in data:\n for i, core_values in enumerate(usage.cpu_times):\n for j, v in enumerate(core_values):\n cpu[i][j] += v\n if per_cpu:\n return [self._cpu_times_type(*v) for v in cpu]\n sums = list(empty)\n for core in cpu:\n for i, v in enumerate(core):\n sums[i] += v\n return self._cpu_times_type(*sums)\n ", "context": "class SystemResourceMonitor(object):\n def aggregate_cpu_times(self, start=None, end=None, phase=None, per_cpu=True): ...\n def __init__(self, poll_interval=1.0): ...\n def __del__(self): ...\n def start(self): ...\n def stop(self): ...\n def record_event(self, name): ...\n def phase(self, name): ...\n def begin_phase(self, name): ...\n def finish_phase(self, name): ...\n def range_usage(self, start=None, end=None): ...\n def phase_usage(self, phase): ...\n def between_events_usage(self, start_event, end_event): ...\n def aggregate_cpu_percent(self, start=None, end=None, phase=None, per_cpu=True): ...\n def aggregate_io(self, start=None, end=None, phase=None): ...\n def min_memory_available(self, start=None, end=None, phase=None): ...\n def max_memory_percent(self, start=None, end=None, phase=None): ...\n\n self.start_time = None\n self.end_time = None\n self.events = []\n self.phases = OrderedDict()\n self._active_phases = {}\n self._running = False\n self._stopped = False\n self._cpu_cores = len(cpu_percent)\n self._cpu_times_type = type(cpu_times)\n self._cpu_times_len = len(cpu_times)\n self._io_type = type(io)\n self._io_len = len(io)\n self._virt_type = type(virt)\n self._virt_len = len(virt)\n self._swap_type = type(swap)\n self._swap_len = len(swap)\n self._pipe, child_pipe = multiprocessing.Pipe(True)\n self._process = multiprocessing.Process(None, _collect, args=(child_pipe, poll_interval))\n", "repository": "ffledgling/mozbase-testing-temp", "test_name": "test_aggregate_cpu", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002517.py"} {"focal_file": "mozsystemmonitor/mozsystemmonitor/resourcemonitor.py", "focal_class": "SystemResourceMonitor", "focal_method": "aggregate_io", "tests": "import unittest\n\nclass Test_SystemResourceMonitor_aggregate_io(unittest.TestCase):\n def test_aggregate_io(self):\n monitor = SystemResourceMonitor(poll_interval=0.25)\n monitor.start()\n time.sleep(1.0)\n monitor.stop()\n values = monitor.aggregate_io()\n self.assertTrue(hasattr(values, 'read_count'))\n", "method_code": " def aggregate_io(self, start=None, end=None, phase=None):\n \"\"\"Obtain aggregate I/O counters for a range.\n \n Returns an iostat named tuple from psutil.\n \"\"\"\n io = [0 for i in range(self._io_len)]\n if phase:\n data = self.phase_usage(phase)\n else:\n data = self.range_usage(start, end)\n for usage in data:\n for i, v in enumerate(usage.io):\n io[i] += v\n return self._io_type(*io)\n ", "context": "class SystemResourceMonitor(object):\n def aggregate_io(self, start=None, end=None, phase=None): ...\n def __init__(self, poll_interval=1.0): ...\n def __del__(self): ...\n def start(self): ...\n def stop(self): ...\n def record_event(self, name): ...\n def phase(self, name): ...\n def begin_phase(self, name): ...\n def finish_phase(self, name): ...\n def range_usage(self, start=None, end=None): ...\n def phase_usage(self, phase): ...\n def between_events_usage(self, start_event, end_event): ...\n def aggregate_cpu_percent(self, start=None, end=None, phase=None, per_cpu=True): ...\n def aggregate_cpu_times(self, start=None, end=None, phase=None, per_cpu=True): ...\n def min_memory_available(self, start=None, end=None, phase=None): ...\n def max_memory_percent(self, start=None, end=None, phase=None): ...\n\n self.start_time = None\n self.end_time = None\n self.events = []\n self.phases = OrderedDict()\n self._active_phases = {}\n self._running = False\n self._stopped = False\n self._cpu_cores = len(cpu_percent)\n self._cpu_times_type = type(cpu_times)\n self._cpu_times_len = len(cpu_times)\n self._io_type = type(io)\n self._io_len = len(io)\n self._virt_type = type(virt)\n self._virt_len = len(virt)\n self._swap_type = type(swap)\n self._swap_len = len(swap)\n self._pipe, child_pipe = multiprocessing.Pipe(True)\n self._process = multiprocessing.Process(None, _collect, args=(child_pipe, poll_interval))\n", "repository": "ffledgling/mozbase-testing-temp", "test_name": "test_aggregate_io", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002518.py"} {"focal_file": "target_decisioning_engine/allocation_provider.py", "focal_class": null, "focal_method": "compute_allocation", "tests": "import unittest\n\nclass Test_compute_allocation(unittest.TestCase):\n def test_compute_allocation_visitor_id_str(self):\n visitor_id = 'ecid123'\n allocation = compute_allocation(CLIENT_ID, ACTIVITY_ID, visitor_id, SALT)\n self.assertEqual(allocation, 29.06)\n\n def test_compute_allocation_ecid(self):\n visitor_id = VisitorId(marketing_cloud_visitor_id='ecid123')\n allocation = compute_allocation(CLIENT_ID, ACTIVITY_ID, visitor_id, SALT)\n self.assertEqual(allocation, 29.06)\n\n def test_compute_allocation_tnt_id(self):\n visitor_id = VisitorId(tnt_id='tntId123')\n allocation = compute_allocation(CLIENT_ID, ACTIVITY_ID, visitor_id, SALT)\n self.assertEqual(allocation, 21.94)\n\n def test_compute_allocation_tnt_id_with_location_hint(self):\n visitor_id = VisitorId(tnt_id='tntId123.28_0')\n allocation = compute_allocation(CLIENT_ID, ACTIVITY_ID, visitor_id, SALT)\n self.assertEqual(allocation, 21.94)\n\n def test_compute_allocation_third_party_id(self):\n visitor_id = VisitorId(third_party_id='thirtPartyId123')\n allocation = compute_allocation(CLIENT_ID, ACTIVITY_ID, visitor_id, SALT)\n self.assertEqual(allocation, 73.15)\n\n def test_compute_allocation_generate_visitor_id(self):\n visitor_id = None\n allocation = compute_allocation(CLIENT_ID, ACTIVITY_ID, visitor_id, SALT)\n self.assertTrue(isinstance(allocation, float))\n self.assertTrue(allocation >= 0)\n self.assertTrue(allocation < 100)\n visitor_id = VisitorId()\n allocation = compute_allocation(CLIENT_ID, ACTIVITY_ID, visitor_id, SALT)\n self.assertTrue(isinstance(allocation, float))\n self.assertTrue(allocation >= 0)\n self.assertTrue(allocation < 100)\n", "method_code": "def compute_allocation(client_id, activity_id, visitor_id, salt=CAMPAIGN_BUCKET_SALT):\n \"\"\"\n :param client_id: (str) client ID\n :param activity_id: (str) activity ID\n :param visitor_id: (str | delivery_api_client.Model.visitor_id.VisitorId) visitor ID\n :param salt: (str) hashing salt\n :return: (float) allocation value\n \"\"\"\n device_id = '.'.join([client_id, str(activity_id), visitor_id if visitor_id and is_string(visitor_id) else get_or_create_visitor_id(visitor_id), salt])\n return calculate_allocation_memoized(device_id)", "context": "def compute_allocation(client_id, activity_id, visitor_id, salt=CAMPAIGN_BUCKET_SALT): ...\ndef valid_tnt_id(tnt_id=None): ...\ndef get_or_create_visitor_id(visitor_id): ...\ndef _calculate_allocation(device_id): ...\ndef compute_allocation(client_id, activity_id, visitor_id, salt=CAMPAIGN_BUCKET_SALT): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_compute_allocation_visitor_id_str", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002519.py"} {"focal_file": "target_decisioning_engine/allocation_provider.py", "focal_class": null, "focal_method": "get_or_create_visitor_id", "tests": "import unittest\n\nclass Test_get_or_create_visitor_id(unittest.TestCase):\n def test_get_or_create_visitor_id_uses_ecid(self):\n customer_id = CustomerId(id='custId123', integration_code='A', authenticated_state=AuthenticatedState.UNKNOWN)\n visitor_id = VisitorId(tnt_id='tnt123', marketing_cloud_visitor_id='mcid123', customer_ids=[customer_id], third_party_id='thirtPartyId123')\n result = get_or_create_visitor_id(visitor_id)\n self.assertEqual(result, 'mcid123')\n\n def test_get_or_create_visitor_id_uses_tnt_id(self):\n customer_id = CustomerId(id='custId123', integration_code='A', authenticated_state=AuthenticatedState.UNKNOWN)\n visitor_id = VisitorId(tnt_id='tnt123', customer_ids=[customer_id], third_party_id='thirtPartyId123')\n result = get_or_create_visitor_id(visitor_id)\n self.assertEqual(result, 'tnt123')\n\n def test_get_or_create_visitor_id_uses_third_party_id(self):\n customer_id = CustomerId(id='custId123', integration_code='A', authenticated_state=AuthenticatedState.UNKNOWN)\n visitor_id = VisitorId(customer_ids=[customer_id], third_party_id='thirtPartyId123')\n result = get_or_create_visitor_id(visitor_id)\n self.assertEqual(result, 'thirtPartyId123')\n\n def test_get_or_create_visitor_id_never_uses_customer_id(self):\n customer_ids = [CustomerId(id='custId123unknown', integration_code='A', authenticated_state=AuthenticatedState.UNKNOWN), CustomerId(id='custId123loggedout', integration_code='A', authenticated_state=AuthenticatedState.LOGGED_OUT), CustomerId(id='custId123authenticated', integration_code='A', authenticated_state=AuthenticatedState.AUTHENTICATED)]\n visitor_id = VisitorId(customer_ids=customer_ids)\n result = get_or_create_visitor_id(visitor_id)\n self.assertTrue(isinstance(result, str))\n self.assertGreater(len(result), 0)\n self.assertIsNot(result, 'custId123unknown')\n self.assertIsNot(result, 'custId123loggedout')\n self.assertIsNot(result, 'custId123authenticated')\n\n def test_get_or_create_visitor_id_generate_id(self):\n result = get_or_create_visitor_id('')\n self.assertTrue(isinstance(result, str))\n self.assertGreater(len(result), 0)\n", "method_code": "def get_or_create_visitor_id(visitor_id):\n \"\"\"\n :param visitor_id: (delivery_api_client.Model.visitor_id.VisitorId) visitor ID object\n :return: (str) Returns visitor ID that will be used to compute the allocation\n \"\"\"\n if not visitor_id:\n return create_uuid()\n return visitor_id.marketing_cloud_visitor_id or valid_tnt_id(visitor_id.tnt_id) or visitor_id.third_party_id or create_uuid()", "context": "def get_or_create_visitor_id(visitor_id): ...\ndef valid_tnt_id(tnt_id=None): ...\ndef get_or_create_visitor_id(visitor_id): ...\ndef _calculate_allocation(device_id): ...\ndef compute_allocation(client_id, activity_id, visitor_id, salt=CAMPAIGN_BUCKET_SALT): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_or_create_visitor_id_uses_ecid", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002520.py"} {"focal_file": "target_decisioning_engine/allocation_provider.py", "focal_class": null, "focal_method": "valid_tnt_id", "tests": "import unittest\n\nclass Test_valid_tnt_id(unittest.TestCase):\n def test_valid_tnt_id_no_cluster(self):\n result = valid_tnt_id('338e3c1e51f7416a8e1ccba4f81acea0')\n self.assertEqual(result, '338e3c1e51f7416a8e1ccba4f81acea0')\n\n def test_valid_tnt_id_invalid(self):\n result = valid_tnt_id('')\n self.assertIsNone(result)\n result = valid_tnt_id(None)\n self.assertIsNone(result)\n result = valid_tnt_id()\n self.assertIsNone(result)\n result = valid_tnt_id(100)\n self.assertIsNone(result)\n", "method_code": "def valid_tnt_id(tnt_id=None):\n \"\"\"\n :param tnt_id: (str) tntId\n :return: (str) tntId without the location hint\n \"\"\"\n if tnt_id and is_string(tnt_id):\n return tnt_id.split('.')[0]\n return None", "context": "def valid_tnt_id(tnt_id=None): ...\ndef valid_tnt_id(tnt_id=None): ...\ndef get_or_create_visitor_id(visitor_id): ...\ndef _calculate_allocation(device_id): ...\ndef compute_allocation(client_id, activity_id, visitor_id, salt=CAMPAIGN_BUCKET_SALT): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_valid_tnt_id_no_cluster", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002521.py"} {"focal_file": "target_decisioning_engine/artifact_provider.py", "focal_class": "ArtifactProvider", "focal_method": "stop_polling", "tests": "import unittest\n\nclass Test_ArtifactProvider_stop_polling(unittest.TestCase):\n def test_stop_all_polling(self):\n self.provider = ArtifactProvider(self.default_config)\n with patch.object(self.provider.pool_manager, 'request', return_value=HTTPResponse()):\n self.provider.initialize()\n self.assertTrue(self.provider.polling_timer.is_alive())\n self.assertFalse(self.provider.polling_halted)\n self.provider.stop_polling()\n self.assertIsNone(self.provider.polling_timer)\n self.assertTrue(self.provider.polling_halted)\n", "method_code": " def stop_polling(self):\n \"\"\"Disable artifact polling\"\"\"\n if self.polling_timer:\n self.polling_timer.cancel()\n self.polling_timer = None\n self.polling_halted = True\n ", "context": "class ArtifactProvider():\n def stop_polling(self): ...\n def __init__(self, config): ...\n def _get_polling_interval(self): ...\n def initialize(self): ...\n def _emit_new_artifact(self, artifact_payload, geo_context=None): ...\n def subscribe(self, callback_func): ...\n def unsubscribe(self, _id): ...\n def _fetch_and_schedule(self): ...\n def _schedule_next_update(self): ...\n def resume_polling(self): ...\n def get_artifact(self): ...\n def _get_initial_artifact(self): ...\n def _artifact_tracer_update(self, artifact): ...\n def get_trace(self): ...\n def _fetch_artifact(self, artifact_url): ...\n\n self.pool_manager = urllib3.PoolManager()\n self.http_retry = Retry(total=NUM_FETCH_RETRIES, backoff_factor=BACKOFF_FACTOR, status_forcelist=CODES_TO_RETRY)\n self.config = config\n self.logger = get_logger()\n self.event_emitter = config.event_emitter or noop\n self.polling_interval = None\n self.artifact_location = None\n self.polling_halted = False\n self.polling_timer = None\n self.artifact = None\n self.subscriptions = {}\n self.subscription_count = 0\n self.last_response_etag = None\n self.last_response_data = None\n self.artifact_tracer = None\n self.perf_tool = get_perf_tool_instance()\n", "repository": "adobe/target-python-sdk", "test_name": "test_stop_all_polling", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002522.py"} {"focal_file": "target_decisioning_engine/artifact_provider.py", "focal_class": "ArtifactProvider", "focal_method": "resume_polling", "tests": "import unittest\n\nclass Test_ArtifactProvider_resume_polling(unittest.TestCase):\n def test_resume_polling(self):\n self.provider = ArtifactProvider(self.default_config)\n with patch.object(self.provider.pool_manager, 'request', return_value=HTTPResponse()):\n self.provider.initialize()\n self.provider.stop_polling()\n self.assertTrue(self.provider.polling_halted)\n self.provider.resume_polling()\n self.assertTrue(self.provider.polling_timer.is_alive())\n self.assertFalse(self.provider.polling_halted)\n", "method_code": " def resume_polling(self):\n \"\"\"Enable artifact polling\"\"\"\n self.polling_halted = False\n self._schedule_next_update()\n ", "context": "class ArtifactProvider():\n def resume_polling(self): ...\n def __init__(self, config): ...\n def _get_polling_interval(self): ...\n def initialize(self): ...\n def _emit_new_artifact(self, artifact_payload, geo_context=None): ...\n def subscribe(self, callback_func): ...\n def unsubscribe(self, _id): ...\n def _fetch_and_schedule(self): ...\n def _schedule_next_update(self): ...\n def stop_polling(self): ...\n def get_artifact(self): ...\n def _get_initial_artifact(self): ...\n def _artifact_tracer_update(self, artifact): ...\n def get_trace(self): ...\n def _fetch_artifact(self, artifact_url): ...\n\n self.pool_manager = urllib3.PoolManager()\n self.http_retry = Retry(total=NUM_FETCH_RETRIES, backoff_factor=BACKOFF_FACTOR, status_forcelist=CODES_TO_RETRY)\n self.config = config\n self.logger = get_logger()\n self.event_emitter = config.event_emitter or noop\n self.polling_interval = None\n self.artifact_location = None\n self.polling_halted = False\n self.polling_timer = None\n self.artifact = None\n self.subscriptions = {}\n self.subscription_count = 0\n self.last_response_etag = None\n self.last_response_data = None\n self.artifact_tracer = None\n self.perf_tool = get_perf_tool_instance()\n", "repository": "adobe/target-python-sdk", "test_name": "test_resume_polling", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002523.py"} {"focal_file": "target_decisioning_engine/context_provider.py", "focal_class": null, "focal_method": "create_decisioning_context", "tests": "import unittest\n\nclass Test_create_decisioning_context(unittest.TestCase):\n def test_create_browser_context(self):\n request_context = Context(channel=ChannelType.WEB, user_agent=FIREFOX_USER_AGENT)\n request = DeliveryRequest(context=request_context)\n result = create_decisioning_context(request)\n self.assertTrue(isinstance(result.get('user'), UserContext))\n self.assertEqual(result.get('user').get('browserType'), 'firefox')\n self.assertEqual(result.get('user').get('platform'), 'Windows')\n self.assertEqual(result.get('user').get('locale'), 'en')\n self.assertEqual(result.get('user').get('browserVersion'), 47)\n\n def test_create_timing_context(self):\n request_context = Context(ChannelType.WEB)\n request = DeliveryRequest(context=request_context)\n result = create_decisioning_context(request)\n self.assertTrue(result.get('current_day') > 0)\n self.assertTrue(result.get('current_day') < 8)\n self.assertEqual(len(result.get('current_time')), 4)\n self.assertTrue(result.get('current_timestamp') > 0)\n\n def test_create_decisioning_context_generate_blank_context(self):\n request_context = Context(ChannelType.WEB)\n request = DeliveryRequest(context=request_context)\n result = create_decisioning_context(request)\n self.assertTrue(isinstance(result, DecisioningContext))\n self.assertIsNotNone(result.get('current_time'))\n self.assertIsNotNone(result.get('current_timestamp'))\n self.assertIsNotNone(result.get('current_day'))\n self.assertIsNone(result.get('geo').get('latitude'))\n self.assertIsNone(result.get('geo').get('longitude'))\n self.assertIsNone(result.get('geo').get('country'))\n self.assertIsNone(result.get('geo').get('region'))\n self.assertIsNone(result.get('geo').get('city'))\n self.assertEqual(result.get('page').get('domain'), '')\n self.assertEqual(result.get('page').get('domain_lc'), '')\n self.assertEqual(result.get('page').get('fragment'), '')\n self.assertEqual(result.get('page').get('fragment_lc'), '')\n self.assertEqual(result.get('page').get('path'), '')\n self.assertEqual(result.get('page').get('path_lc'), '')\n self.assertEqual(result.get('page').get('query'), '')\n self.assertEqual(result.get('page').get('query_lc'), '')\n self.assertEqual(result.get('page').get('subdomain'), '')\n self.assertEqual(result.get('page').get('subdomain_lc'), '')\n self.assertEqual(result.get('page').get('topLevelDomain'), '')\n self.assertEqual(result.get('page').get('topLevelDomain_lc'), '')\n self.assertEqual(result.get('page').get('url'), '')\n self.assertEqual(result.get('page').get('url_lc'), '')\n self.assertEqual(result.get('referring').get('domain'), '')\n self.assertEqual(result.get('referring').get('domain_lc'), '')\n self.assertEqual(result.get('referring').get('fragment'), '')\n self.assertEqual(result.get('referring').get('fragment_lc'), '')\n self.assertEqual(result.get('referring').get('path'), '')\n self.assertEqual(result.get('referring').get('path_lc'), '')\n self.assertEqual(result.get('referring').get('query'), '')\n self.assertEqual(result.get('referring').get('query_lc'), '')\n self.assertEqual(result.get('referring').get('subdomain'), '')\n self.assertEqual(result.get('referring').get('subdomain_lc'), '')\n self.assertEqual(result.get('referring').get('topLevelDomain'), '')\n self.assertEqual(result.get('referring').get('topLevelDomain_lc'), '')\n self.assertEqual(result.get('referring').get('url'), '')\n self.assertEqual(result.get('referring').get('url_lc'), '')\n self.assertEqual(result.get('user').get('browserType'), 'unknown')\n self.assertEqual(result.get('user').get('platform'), 'Unknown')\n self.assertEqual(result.get('user').get('locale'), 'en')\n self.assertEqual(result.get('user').get('browserVersion'), -1)\n\n def test_create_decisioning_context(self):\n geo = Geo(country_code='US', state_code='CA', city='San Francisco', latitude=38.8, longitude=-77.0)\n address = Address(url=TEST_URL, referring_url=TEST_URL)\n request_context = Context(channel=ChannelType.WEB, user_agent=FIREFOX_USER_AGENT, address=address, geo=geo)\n request = DeliveryRequest(context=request_context)\n result = create_decisioning_context(request)\n self.assertTrue(isinstance(result, DecisioningContext))\n self.assertIsNotNone(result.get('current_time'))\n self.assertIsNotNone(result.get('current_timestamp'))\n self.assertIsNotNone(result.get('current_day'))\n self.validate_object_values(result.get('geo'))\n self.validate_object_values(result.get('user'))\n self.validate_object_values(result.get('page'))\n self.validate_object_values(result.get('referring'))\n", "method_code": "def create_decisioning_context(delivery_request):\n \"\"\"Create decisioning context\n :param delivery_request: (delivery_api_client.Model.delivery_request.DeliveryRequest) Delivery API request\n :return: (target_decisioning_engine.types.decisioning_context.DecisioningContext) Decisioning context\n \"\"\"\n context = delivery_request.context or EMPTY_CONTEXT\n timing_context = _create_timing_context()\n return DecisioningContext(current_timestamp=timing_context.get('current_timestamp'), current_time=timing_context.get('current_time'), current_day=timing_context.get('current_day'), user=_create_browser_context(context), page=create_page_context(context.address), referring=create_referring_context(context.address), geo=create_geo_context(context.geo))", "context": "def create_decisioning_context(delivery_request): ...\ndef get_lower_case_attributes(obj): ...\ndef _create_browser_context(context): ...\ndef _create_url_context(url): ...\ndef create_page_context(address): ...\ndef create_referring_context(address): ...\ndef create_mbox_context(mbox_request): ...\ndef create_geo_context(_geo=None): ...\ndef two_digit_string(_value): ...\ndef _create_timing_context(): ...\ndef create_decisioning_context(delivery_request): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_create_browser_context", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002524.py"} {"focal_file": "target_decisioning_engine/context_provider.py", "focal_class": null, "focal_method": "create_page_context", "tests": "import unittest\n\nclass Test_create_page_context(unittest.TestCase):\n def test_create_page_context_url_empty_string(self):\n address = Address(url=EMPTY_STRING)\n result = create_page_context(address)\n self.assertTrue(isinstance(result, PageContext))\n for key in result.values():\n self.assertEqual(key, EMPTY_STRING)\n\n def test_create_page_context_non_empty_url(self):\n address = Address(url=TEST_URL)\n result = create_page_context(address)\n self.assertTrue(isinstance(result, PageContext))\n self.assertEqual(result.get('domain'), 'geocities')\n self.assertEqual(result.get('domain_lc'), 'geocities')\n self.assertEqual(result.get('fragment'), 'Bottom')\n self.assertEqual(result.get('fragment_lc'), 'bottom')\n self.assertEqual(result.get('path'), '/Posts')\n self.assertEqual(result.get('path_lc'), '/posts')\n self.assertEqual(result.get('query'), 'Page=1')\n self.assertEqual(result.get('query_lc'), 'page=1')\n self.assertEqual(result.get('subdomain'), 'blog.myfavesite')\n self.assertEqual(result.get('subdomain_lc'), 'blog.myfavesite')\n self.assertEqual(result.get('topLevelDomain'), 'com')\n self.assertEqual(result.get('topLevelDomain_lc'), 'com')\n self.assertEqual(result.get('url'), 'http://Blog.Myfavesite.GeoCities.com/Posts?Page=1#Bottom')\n self.assertEqual(result.get('url_lc'), 'http://blog.myfavesite.geocities.com/posts?page=1#bottom')\n\n def test_create_page_context_applookout(self):\n address = Address(url='https://stage.applookout.net/')\n result = create_page_context(address)\n self.assertTrue(isinstance(result, PageContext))\n self.assertEqual(result.get('domain'), 'applookout')\n self.assertEqual(result.get('domain_lc'), 'applookout')\n self.assertEqual(result.get('fragment'), '')\n self.assertEqual(result.get('fragment_lc'), '')\n self.assertEqual(result.get('path'), '/')\n self.assertEqual(result.get('path_lc'), '/')\n self.assertEqual(result.get('query'), '')\n self.assertEqual(result.get('query_lc'), '')\n self.assertEqual(result.get('subdomain'), 'stage')\n self.assertEqual(result.get('subdomain_lc'), 'stage')\n self.assertEqual(result.get('topLevelDomain'), 'net')\n self.assertEqual(result.get('topLevelDomain_lc'), 'net')\n self.assertEqual(result.get('url'), 'https://stage.applookout.net/')\n self.assertEqual(result.get('url_lc'), 'https://stage.applookout.net/')\n", "method_code": "def create_page_context(address):\n \"\"\"Create page context from address url\n :param address: (delivery_api_client.Model.address.Address) Delivery API address\n :return: (target_decisioning_engine.types.decisioning_context.PageContext) Page context\n \"\"\"\n return _create_url_context(address.url if address else '')", "context": "def create_page_context(address): ...\ndef get_lower_case_attributes(obj): ...\ndef _create_browser_context(context): ...\ndef _create_url_context(url): ...\ndef create_page_context(address): ...\ndef create_referring_context(address): ...\ndef create_mbox_context(mbox_request): ...\ndef create_geo_context(_geo=None): ...\ndef two_digit_string(_value): ...\ndef _create_timing_context(): ...\ndef create_decisioning_context(delivery_request): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_create_page_context_url_empty_string", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002525.py"} {"focal_file": "target_decisioning_engine/context_provider.py", "focal_class": null, "focal_method": "create_referring_context", "tests": "import unittest\n\nclass Test_create_referring_context(unittest.TestCase):\n def test_create_referring_context_url_empty_string(self):\n address = Address(referring_url=EMPTY_STRING)\n result = create_referring_context(address)\n self.assertTrue(isinstance(result, PageContext))\n for attribute in result.__dict__.values():\n self.assertEqual(attribute, EMPTY_STRING)\n\n def test_create_referring_context_non_empty_url(self):\n address = Address(referring_url=TEST_URL)\n result = create_referring_context(address)\n self.assertTrue(isinstance(result, PageContext))\n self.assertEqual(result.get('domain'), 'geocities')\n self.assertEqual(result.get('domain_lc'), 'geocities')\n self.assertEqual(result.get('fragment'), 'Bottom')\n self.assertEqual(result.get('fragment_lc'), 'bottom')\n self.assertEqual(result.get('path'), '/Posts')\n self.assertEqual(result.get('path_lc'), '/posts')\n self.assertEqual(result.get('query'), 'Page=1')\n self.assertEqual(result.get('query_lc'), 'page=1')\n self.assertEqual(result.get('subdomain'), 'blog.myfavesite')\n self.assertEqual(result.get('subdomain_lc'), 'blog.myfavesite')\n self.assertEqual(result.get('topLevelDomain'), 'com')\n self.assertEqual(result.get('topLevelDomain_lc'), 'com')\n self.assertEqual(result.get('url'), 'http://Blog.Myfavesite.GeoCities.com/Posts?Page=1#Bottom')\n self.assertEqual(result.get('url_lc'), 'http://blog.myfavesite.geocities.com/posts?page=1#bottom')\n", "method_code": "def create_referring_context(address):\n \"\"\"Create page context from address referring url\n :param address: (delivery_api_client.Model.address.Address) Delivery API address\n :return: (target_decisioning_engine.types.decisioning_context.PageContext) Page context\n \"\"\"\n return _create_url_context(address.referring_url if address else '')", "context": "def create_referring_context(address): ...\ndef get_lower_case_attributes(obj): ...\ndef _create_browser_context(context): ...\ndef _create_url_context(url): ...\ndef create_page_context(address): ...\ndef create_referring_context(address): ...\ndef create_mbox_context(mbox_request): ...\ndef create_geo_context(_geo=None): ...\ndef two_digit_string(_value): ...\ndef _create_timing_context(): ...\ndef create_decisioning_context(delivery_request): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_create_referring_context_url_empty_string", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002526.py"} {"focal_file": "target_decisioning_engine/context_provider.py", "focal_class": null, "focal_method": "create_mbox_context", "tests": "import unittest\n\nclass Test_create_mbox_context(unittest.TestCase):\n def test_create_mbox_context(self):\n params = {'a': 'FirstParam', 'b': 'SecondOne', 'c': 'third'}\n mbox = MboxRequest(parameters=params)\n result = create_mbox_context(mbox)\n self.assertEqual(result.get('a'), 'FirstParam')\n self.assertEqual(result.get('b'), 'SecondOne')\n self.assertEqual(result.get('c'), 'third')\n self.assertEqual(result.get('a_lc'), 'firstparam')\n self.assertEqual(result.get('b_lc'), 'secondone')\n self.assertEqual(result.get('c_lc'), 'third')\n", "method_code": "def create_mbox_context(mbox_request):\n \"\"\"Create mbox context\n :param mbox_request: (delivery_api_client.Model.mbox_request.MboxRequest) Delivery API mbox request\n :return: (dict) Mbox context\n \"\"\"\n if not mbox_request:\n return {}\n parameters = mbox_request.parameters or {}\n lc_parameters = get_lower_case_attributes(parameters)\n parameters.update(lc_parameters)\n return parameters", "context": "def create_mbox_context(mbox_request): ...\ndef get_lower_case_attributes(obj): ...\ndef _create_browser_context(context): ...\ndef _create_url_context(url): ...\ndef create_page_context(address): ...\ndef create_referring_context(address): ...\ndef create_mbox_context(mbox_request): ...\ndef create_geo_context(_geo=None): ...\ndef two_digit_string(_value): ...\ndef _create_timing_context(): ...\ndef create_decisioning_context(delivery_request): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_create_mbox_context", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002527.py"} {"focal_file": "target_decisioning_engine/context_provider.py", "focal_class": null, "focal_method": "create_geo_context", "tests": "import unittest\n\nclass Test_create_geo_context(unittest.TestCase):\n def test_create_geo_context_no_geo(self):\n result = create_geo_context(None)\n for val in result.__dict__.values():\n self.assertEqual(val, None)\n\n def test_create_geo_context(self):\n geo = Geo(country_code='US', state_code='CA', city='San Francisco', latitude=38.8, longitude=-77.0)\n result = create_geo_context(geo)\n self.assertTrue(isinstance(result, GeoContext))\n self.assertEqual(result.get('country'), 'US')\n self.assertEqual(result.get('region'), 'CA')\n self.assertEqual(result.get('city'), 'San Francisco')\n self.assertEqual(result.get('latitude'), 38.8)\n self.assertEqual(result.get('longitude'), -77.0)\n", "method_code": "def create_geo_context(_geo=None):\n \"\"\"Create geo context\n :param _geo: (delivery_api_client.Model.geo.Geo) Delivery API geo\n :return: (target_decisioning_engine.types.decisioning_context.GeoContext) Geo context\n \"\"\"\n if not _geo:\n return GeoContext()\n return GeoContext(country=_geo.country_code, region=_geo.state_code, city=_geo.city, latitude=_geo.latitude, longitude=_geo.longitude)", "context": "def create_geo_context(_geo=None): ...\ndef get_lower_case_attributes(obj): ...\ndef _create_browser_context(context): ...\ndef _create_url_context(url): ...\ndef create_page_context(address): ...\ndef create_referring_context(address): ...\ndef create_mbox_context(mbox_request): ...\ndef create_geo_context(_geo=None): ...\ndef two_digit_string(_value): ...\ndef _create_timing_context(): ...\ndef create_decisioning_context(delivery_request): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_create_geo_context_no_geo", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002528.py"} {"focal_file": "target_decisioning_engine/geo_provider.py", "focal_class": null, "focal_method": "create_or_update_geo_object", "tests": "import unittest\n\nclass Test_create_or_update_geo_object(unittest.TestCase):\n def test_create_or_update_geo_object_no_existing_and_empty_geo_data(self):\n result = create_or_update_geo_object()\n expected = Geo()\n self.assertEqual(result, expected)\n\n def test_create_or_update_geo_object_no_existing(self):\n result = create_or_update_geo_object(geo_data=self.headers)\n expected = Geo(**{'latitude': 37.773972, 'longitude': -122.431297, 'city': 'SANFRANCISCO', 'country_code': 'US', 'state_code': 'CA'})\n self.assertEqual(result, expected)\n\n def test_create_or_update_geo_object_merge_with_existing(self):\n existing_geo = Geo(latitude=37.773972, longitude=-122.431297)\n headers = {'x-geo-country-code': 'US', 'x-geo-region-code': 'CA', 'x-geo-city': 'SANFRANCISCO'}\n result = create_or_update_geo_object(geo_data=headers, existing_geo_context=existing_geo)\n expected = Geo(**{'latitude': 37.773972, 'longitude': -122.431297, 'city': 'SANFRANCISCO', 'country_code': 'US', 'state_code': 'CA'})\n self.assertEqual(result, expected)\n\n def test_create_or_update_geo_object_empty_geo_data(self):\n existing_geo = Geo(latitude=37.773972, longitude=-122.431297)\n result = create_or_update_geo_object(geo_data=None, existing_geo_context=existing_geo)\n expected = Geo(**{'latitude': 37.773972, 'longitude': -122.431297})\n self.assertEqual(result, expected)\n", "method_code": "def create_or_update_geo_object(geo_data=None, existing_geo_context=None):\n \"\"\"\n :param existing_geo_context: (delivery_api_client.Model.geo.Geo) geo object\n :param geo_data: (dict) geo payload or headers to merge into existing_geo_context\n :return: (delivery_api_client.Model.geo.Geo) geo object\n \"\"\"\n if not geo_data:\n geo_data = {}\n\n def _get_payload(key):\n return geo_data.get(key)\n return _map_geo_values(_get_payload, existing_geo_context)", "context": "def create_or_update_geo_object(geo_data=None, existing_geo_context=None): ...\ndef _map_geo_values(value_fn, initial=None): ...\ndef create_or_update_geo_object(geo_data=None, existing_geo_context=None): ...\ndef is_missing_geo_fields(geo_request_context): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_create_or_update_geo_object_no_existing_and_empty_geo_data", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002529.py"} {"focal_file": "target_decisioning_engine/geo_provider.py", "focal_class": "GeoProvider", "focal_method": "valid_geo_request_context", "tests": "import unittest\n\nclass Test_GeoProvider_valid_geo_request_context(unittest.TestCase):\n def test_valid_geo_request_context_geo_targeting_disabled(self):\n artifact = deepcopy(ARTIFACT_BLANK)\n artifact['geoTargetingEnabled'] = False\n geo_provider = GeoProvider(self.config, artifact)\n with patch.object(geo_provider.pool_manager, 'request', return_value=self.mock_geo_response) as mock_http_call:\n geo_input = Geo(ip_address='12.21.1.40')\n result = geo_provider.valid_geo_request_context(geo_input)\n time.sleep(1)\n self.assertEqual(result, geo_input)\n self.assertEqual(mock_http_call.call_count, 0)\n\n def test_valid_geo_request_context_no_ip_address(self):\n expected = Geo(**{'city': 'SAN FRANCISCO', 'country_code': 'US', 'latitude': 37.75, 'longitude': -122.4, 'state_code': 'CA'})\n artifact = deepcopy(ARTIFACT_BLANK)\n artifact['geoTargetingEnabled'] = True\n geo_provider = GeoProvider(self.config, artifact)\n with patch.object(geo_provider.pool_manager, 'request', return_value=self.mock_geo_response) as mock_http_call:\n geo_input = Geo(ip_address=None)\n result = geo_provider.valid_geo_request_context(geo_input)\n time.sleep(1)\n self.assertEqual(result, expected)\n self.assertEqual(mock_http_call.call_count, 1)\n self.assertEqual(mock_http_call.call_args[0][1], 'https://assets.adobetarget.com/v1/geo')\n self.assertIsNone(mock_http_call.call_args[1].get('headers').get(HTTP_HEADER_FORWARDED_FOR))\n\n def test_valid_geo_request_context_not_missing_geo_fields(self):\n expected = Geo(city='Las Vegas')\n artifact = deepcopy(ARTIFACT_BLANK)\n artifact['geoTargetingEnabled'] = True\n geo_provider = GeoProvider(self.config, artifact)\n with patch.object(geo_provider.pool_manager, 'request', return_value=self.mock_geo_response) as mock_http_call:\n geo_input = Geo(ip_address=None, city='Las Vegas')\n result = geo_provider.valid_geo_request_context(geo_input)\n time.sleep(1)\n self.assertEqual(result, expected)\n self.assertEqual(mock_http_call.call_count, 0)\n\n def test_valid_geo_request_non_200_response(self):\n artifact = deepcopy(ARTIFACT_BLANK)\n artifact['geoTargetingEnabled'] = True\n geo_provider = GeoProvider(self.config, artifact)\n mock_bad_response = HTTPResponse(body='Bad Request', status=BAD_REQUEST)\n with patch.object(geo_provider.pool_manager, 'request', return_value=mock_bad_response) as mock_http_call:\n geo_input = Geo(ip_address='12.21.1.40')\n result = geo_provider.valid_geo_request_context(geo_input)\n time.sleep(1)\n self.assertEqual(result, None)\n self.assertEqual(mock_http_call.call_count, 1)\n self.assertEqual(mock_http_call.call_args[0][1], 'https://assets.adobetarget.com/v1/geo')\n self.assertEqual(mock_http_call.call_args[1].get('headers').get(HTTP_HEADER_FORWARDED_FOR), '12.21.1.40')\n", "method_code": " def valid_geo_request_context(self, geo_request_context=None):\n \"\"\"\n :param geo_request_context: (delivery_api_client.Model.geo.Geo) geo object\n :return: (delivery_api_client.Model.geo.Geo) geo object\n \"\"\"\n if not geo_request_context:\n geo_request_context = Geo()\n validated_geo_request_context = deepcopy(geo_request_context)\n geo_lookup_path = get_geo_lookup_path(self.config)\n if self.geo_targeting_enabled and is_missing_geo_fields(geo_request_context):\n headers = {}\n if geo_request_context.ip_address:\n headers[HTTP_HEADER_FORWARDED_FOR] = geo_request_context.ip_address\n try:\n response = self._request_geo(geo_lookup_path, headers)\n return self.geo_response_handler(response, validated_geo_request_context)\n except Exception as err:\n self.logger.error('Exception while fetching geo data at: {} - error: {}'.format(geo_lookup_path, str(err)))\n return None\n return validated_geo_request_context\n ", "context": "class GeoProvider():\n def valid_geo_request_context(self, geo_request_context=None): ...\n def __init__(self, config, artifact): ...\n def _execute_request(self, geo_lookup_path, headers, queue): ...\n def _request_geo(self, geo_lookup_path, headers): ...\n def geo_response_handler(self, response, validated_geo_request_context): ...\n\n self.logger = get_logger()\n self.pool_manager = urllib3.PoolManager()\n self.config = config\n self.artifact = artifact\n self.geo_targeting_enabled = artifact.get('geoTargetingEnabled', False)\n self.event_emitter = config.event_emitter or noop\n", "repository": "adobe/target-python-sdk", "test_name": "test_valid_geo_request_context_geo_targeting_disabled", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002530.py"} {"focal_file": "target_decisioning_engine/tests/helpers.py", "focal_class": null, "focal_method": "get_test_artifacts", "tests": "import unittest\n\nclass Test_get_test_artifacts(unittest.TestCase):\n def test_get_test_artifacts(self):\n test_artifacts = get_test_artifacts()\n self.assertGreater(len(list(test_artifacts)), 0)\n", "method_code": "def get_test_artifacts():\n \"\"\"Retrieves all json filenames from the artifacts directory\n :return (iterable)\n \"\"\"\n return filter(is_json, get_files_in_dir(TEST_ARTIFACTS_FOLDER))", "context": "def get_test_artifacts(): ...\ndef get_files_in_dir(directory): ...\ndef get_test_artifacts(): ...\ndef get_test_models(): ...\ndef _hydrate_artifacts(artifact_folder, artifact_list, test_obj=None): ...\ndef get_test_suites(test_suite_name, exclude_suites): ...\ndef create_decisioning_config(config_dict): ...\ndef create_target_delivery_request(get_offers_opts): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_test_artifacts", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002531.py"} {"focal_file": "target_decisioning_engine/tests/helpers.py", "focal_class": null, "focal_method": "get_test_models", "tests": "import unittest\n\nclass Test_get_test_models(unittest.TestCase):\n def test_get_test_models(self):\n test_models = list(get_test_models())\n self.assertGreater(len(list(test_models)), 0)\n", "method_code": "def get_test_models():\n \"\"\"Retrieves all json filenames from the models directory (returns iterable)\n :return (iterable)\n \"\"\"\n return filter(is_json, get_files_in_dir(TEST_MODELS_FOLDER))", "context": "def get_test_models(): ...\ndef get_files_in_dir(directory): ...\ndef get_test_artifacts(): ...\ndef get_test_models(): ...\ndef _hydrate_artifacts(artifact_folder, artifact_list, test_obj=None): ...\ndef get_test_suites(test_suite_name, exclude_suites): ...\ndef create_decisioning_config(config_dict): ...\ndef create_target_delivery_request(get_offers_opts): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_test_models", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002532.py"} {"focal_file": "target_decisioning_engine/__init__.py", "focal_class": "TargetDecisioningEngine", "focal_method": "initialize", "tests": "import unittest\n\nclass Test_TargetDecisioningEngine_initialize(unittest.TestCase):\n def test_initialize(self):\n config = deepcopy(CONFIG)\n config.polling_interval = 0\n self.decisioning = TargetDecisioningEngine(config)\n with patch.object(PoolManager, 'request', return_value=MOCK_ARTIFACT_RESPONSE):\n self.decisioning.initialize()\n self.assertEqual(self.decisioning.artifact, ARTIFACT_BLANK)\n self.assertIsNotNone(self.decisioning._artifact_provider)\n self.assertEqual(self.decisioning._artifact_provider.subscription_count, 2)\n", "method_code": " def initialize(self):\n \"\"\"Initializes TargetDecisioningEngine. Must be called in order to start artifact polling\"\"\"\n self._artifact_provider = ArtifactProvider(self.config)\n self._artifact_provider.initialize()\n self.artifact = self._artifact_provider.get_artifact()\n if not self.artifact:\n raise Exception(MESSAGES.get('ARTIFACT_NOT_AVAILABLE'))\n \n def _artifact_subscriber(data):\n self.artifact = data\n self._artifact_provider.subscribe(_artifact_subscriber)\n ", "context": "class TargetDecisioningEngine():\n def initialize(self): ...\n def __init__(self, config): ...\n def get_offers(self, target_options): ...\n def is_ready(self): ...\n def get_raw_artifact(self): ...\n def stop_polling(self): ...\n def has_remote_dependency(self, request): ...\n\n self.config = config\n self._artifact_provider = None\n self.artifact = None\n", "repository": "adobe/target-python-sdk", "test_name": "test_initialize", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002533.py"} {"focal_file": "target_decisioning_engine/__init__.py", "focal_class": "TargetDecisioningEngine", "focal_method": "get_offers", "tests": "import unittest\n\nclass Test_TargetDecisioningEngine_get_offers(unittest.TestCase):\n def test_get_offers(self):\n config = deepcopy(CONFIG)\n config.polling_interval = 0\n self.decisioning = TargetDecisioningEngine(config)\n with patch.object(PoolManager, 'request', return_value=MOCK_ARTIFACT_RESPONSE):\n self.decisioning.initialize()\n get_offers_opts = TargetDeliveryRequest(request=TARGET_REQUEST, session_id='dummy_session')\n offers = self.decisioning.get_offers(get_offers_opts)\n self.assertIsNotNone(offers)\n", "method_code": " def get_offers(self, target_options):\n \"\"\"\n :param target_options: (target_decisioning_engine.types.target_delivery_request.TargetDeliveryRequest)\n :return: (dict) get offers response\n \"\"\"\n request = target_options.request\n if not self.artifact:\n raise Exception(MESSAGES.get('ARTIFACT_NOT_AVAILABLE'))\n if not match_major_version(self.artifact.get('version'), SUPPORTED_ARTIFACT_MAJOR_VERSION):\n raise Exception(MESSAGES.get('ARTIFACT_VERSION_UNSUPPORTED')(self.artifact.get('version'), SUPPORTED_ARTIFACT_MAJOR_VERSION))\n _geo_provider = GeoProvider(self.config, self.artifact)\n valid_request = valid_delivery_request(request, target_options.target_location_hint, _geo_provider.valid_geo_request_context)\n options = deepcopy(target_options)\n options.request = valid_request\n _trace_provider = TraceProvider(self.config, options, self._artifact_provider.get_trace())\n decisioning = DecisionProvider(self.config, options, create_decisioning_context(valid_request), self.artifact, _trace_provider)\n return decisioning.run()\n ", "context": "class TargetDecisioningEngine():\n def get_offers(self, target_options): ...\n def __init__(self, config): ...\n def is_ready(self): ...\n def get_raw_artifact(self): ...\n def stop_polling(self): ...\n def has_remote_dependency(self, request): ...\n def initialize(self): ...\n\n self.config = config\n self._artifact_provider = None\n self.artifact = None\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_offers", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002534.py"} {"focal_file": "target_decisioning_engine/notification_provider.py", "focal_class": null, "focal_method": "send_notifications", "tests": "import unittest\n\nclass Test_send_notifications(unittest.TestCase):\n def test_send_notifications_display_type(self):\n event_token = 'B8C2FP2IuBgmeJcDfXHjGpNWHtnQtQrJfmRrQugEa2qCnQ9Y9OaLL2gsdrWQTvE54PwSz67rmXWmSnkXpSSS2Q=='\n options = [Option(content=\"

it's firefox

\", type=OptionType.HTML, event_token=event_token)]\n mbox = MboxResponse(options=options, metrics=[], name='browser-mbox')\n self.provider.add_notification(mbox)\n self.provider.send_notifications()\n time.sleep(1)\n self.assertEqual(self.mock_notify.call_count, 1)\n self.assertEqual(len(self.mock_notify.call_args[0][0]['request'].notifications), 1)\n received = to_dict(self.mock_notify.call_args[0][0]['request'].notifications[0])\n expected = {'id': 'expect.any(String)', 'impressionId': 'expect.any(String)', 'timestamp': 'expect.any(Number)', 'type': 'display', 'mbox': {'name': 'browser-mbox'}, 'tokens': ['B8C2FP2IuBgmeJcDfXHjGpNWHtnQtQrJfmRrQugEa2qCnQ9Y9OaLL2gsdrWQTvE54PwSz67rmXWmSnkXpSSS2Q==']}\n expect_to_match_object(received, expected)\n\n def test_send_notifications_no_duplicates(self):\n event_token = 'yYWdmhDasVXGPWlpX1TRZDSAQdPpz2XBromX4n+pX9jf5r+rP39VCIaiiZlXOAYq'\n content = [{'type': 'insertAfter', 'selector': 'HTML > BODY > DIV:nth-of-type(1) > H1:nth-of-type(1)', 'cssSelector': 'HTML > BODY > DIV:nth-of-type(1) > H1:nth-of-type(1)', 'content': \"

Better to remain silent and be thought a fool than to speak out and remove all doubt.

\"}]\n options = [Option(content=content, type=OptionType.ACTIONS, event_token=event_token)]\n metrics = [Metric(type=MetricType.CLICK, event_token='/GMYvcjhUsR6WVqQElppUw==', selector='#action_insert_15882853393943012')]\n mbox = MboxResponse(options=options, metrics=metrics, name='target-global-mbox')\n self.provider.add_notification(mbox)\n self.provider.add_notification(mbox)\n self.provider.send_notifications()\n time.sleep(1)\n self.assertEqual(self.mock_notify.call_count, 1)\n self.assertEqual(len(self.mock_notify.call_args[0][0]['request'].notifications), 1)\n received = to_dict(self.mock_notify.call_args[0][0]['request'].notifications[0])\n expected = {'id': 'expect.any(String)', 'impressionId': 'expect.any(String)', 'timestamp': 'expect.any(Number)', 'type': 'display', 'mbox': {'name': 'target-global-mbox'}, 'tokens': ['yYWdmhDasVXGPWlpX1TRZDSAQdPpz2XBromX4n+pX9jf5r+rP39VCIaiiZlXOAYq']}\n expect_to_match_object(received, expected)\n\n def test_send_notifications_distinct_per_mbox(self):\n event_token = 'yYWdmhDasVXGPWlpX1TRZDSAQdPpz2XBromX4n+pX9jf5r+rP39VCIaiiZlXOAYq'\n content = [{'type': 'insertAfter', 'selector': 'HTML > BODY > DIV:nth-of-type(1) > H1:nth-of-type(1)', 'cssSelector': 'HTML > BODY > DIV:nth-of-type(1) > H1:nth-of-type(1)', 'content': \"

Better to remain silent and be thought a fool than to speak out and remove all doubt.

\"}]\n options = [Option(content=content, type=OptionType.ACTIONS, event_token=event_token)]\n metrics = [Metric(type=MetricType.CLICK, event_token='/GMYvcjhUsR6WVqQElppUw==', selector='#action_insert_15882853393943012')]\n mbox = MboxResponse(options=options, metrics=metrics, name='my-mbox')\n self.provider.add_notification(mbox)\n another_mbox = MboxResponse(options=options, metrics=metrics, name='another-mbox')\n self.provider.add_notification(another_mbox)\n self.provider.send_notifications()\n time.sleep(1)\n self.assertEqual(self.mock_notify.call_count, 1)\n self.assertEqual(len(self.mock_notify.call_args[0][0]['request'].notifications), 2)\n first_received = to_dict(self.mock_notify.call_args[0][0]['request'].notifications[0])\n expected = {'id': 'expect.any(String)', 'impressionId': 'expect.any(String)', 'timestamp': 'expect.any(Number)', 'type': 'display', 'mbox': {}, 'tokens': ['yYWdmhDasVXGPWlpX1TRZDSAQdPpz2XBromX4n+pX9jf5r+rP39VCIaiiZlXOAYq']}\n first_expected = dict(expected)\n first_expected['mbox']['name'] = 'my-mbox'\n expect_to_match_object(first_received, first_expected)\n second_received = to_dict(self.mock_notify.call_args[0][0]['request'].notifications[1])\n second_expected = dict(expected)\n second_expected['mbox']['name'] = 'another-mbox'\n expect_to_match_object(second_received, second_expected)\n", "method_code": " def send_notifications(self):\n \"\"\"Send notifications via the send_notification_func\"\"\"\n self.logger.debug('{}.send_notifications - Notifications: {} \\nTelemetry Entries: {}'.format(LOG_TAG, self.notifications, self.telemetry_entries))\n if not self.notifications and (not self.telemetry_entries):\n return\n _id = self.request.id\n context = self.request.context\n experience_cloud = self.request.experience_cloud\n notifications = self.notifications if self.notifications else None\n telemetry = Telemetry(entries=self.telemetry_entries) if self.telemetry_entries else None\n request = DeliveryRequest(id=_id, context=context, experience_cloud=experience_cloud, notifications=notifications, telemetry=telemetry)\n send_notification_opts = {'request': request, 'visitor': self.visitor}\n async_send = threading.Thread(target=self.send_notification_func, args=(send_notification_opts,))\n async_send.start()\n self.notifications = []\n self.telemetry_entries = []\n ", "context": "class NotificationProvider():\n def send_notifications(self): ...\n def __init__(self, request, visitor, send_notification_func=noop, telemetry_enabled=True): ...\n def add_notification(self, mbox, trace_func=noop): ...\n def add_telemetry_entry(self, entry): ...\n\n self.visitor = visitor\n self.send_notification_func = send_notification_func\n self.telemetry_enabled = telemetry_enabled\n self.request = request\n self.request_id = request.request_id\n self.prev_event_keys = set()\n self.notifications = []\n self.telemetry_entries = []\n self.logger = get_logger()\n", "repository": "adobe/target-python-sdk", "test_name": "test_send_notifications_display_type", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002535.py"} {"focal_file": "target_decisioning_engine/request_provider.py", "focal_class": null, "focal_method": "valid_visitor_id", "tests": "import unittest\n\nclass Test_valid_visitor_id(unittest.TestCase):\n def test_valid_visitor_id_existing_tnt_id(self):\n customer_ids = [CustomerId(id='custId123', integration_code='A', authenticated_state=AuthenticatedState.AUTHENTICATED)]\n visitor_id = VisitorId(tnt_id='tnt123', third_party_id='thirdParty123', marketing_cloud_visitor_id='mcid123', customer_ids=customer_ids)\n result = valid_visitor_id(visitor_id, LOCATION_HINT)\n self.assertEqual(visitor_id, result)\n\n def test_valid_visitor_id_existing_third_party(self):\n visitor_id = VisitorId(third_party_id='thirdParty123')\n result = valid_visitor_id(visitor_id, LOCATION_HINT)\n self.assertEqual(visitor_id, result)\n\n def test_valid_visitor_id_existing_customer_id(self):\n customer_ids = [CustomerId(id='custId123', integration_code='A', authenticated_state=AuthenticatedState.AUTHENTICATED)]\n visitor_id = VisitorId(customer_ids=customer_ids)\n result = valid_visitor_id(visitor_id, LOCATION_HINT)\n self.assertEqual(visitor_id, result)\n\n def test_valid_visitor_id_existing_ecid(self):\n visitor_id = VisitorId(marketing_cloud_visitor_id='mcid123')\n result = valid_visitor_id(visitor_id, LOCATION_HINT)\n self.assertEqual(visitor_id, result)\n\n def test_valid_visitor_id_generate_tnt_id(self):\n visitor_id = VisitorId()\n result = valid_visitor_id(visitor_id, LOCATION_HINT)\n self.assertIsNotNone(result.tnt_id)\n\n def test_valid_visitor_id_invalid_customer_id(self):\n customer_ids = [CustomerId(id='custIdUnknown', integration_code='A', authenticated_state=AuthenticatedState.UNKNOWN), CustomerId(id='custIdLoggedOut', integration_code='A', authenticated_state=AuthenticatedState.LOGGED_OUT)]\n visitor_id = VisitorId(customer_ids=customer_ids)\n result = valid_visitor_id(visitor_id, LOCATION_HINT)\n self.assertIsNotNone(result.tnt_id)\n", "method_code": "def valid_visitor_id(visitor_id, target_location_hint):\n \"\"\"\n :param visitor_id: (delivery_api_client.Model.visitor_id.VisitorId) visitor ID object\n :param target_location_hint: (str) Target location hint\n :return: (delivery_api_client.Model.visitor_id.VisitorId) updated copy of visitor ID object\n \"\"\"\n result = deepcopy(visitor_id) if visitor_id else VisitorId()\n if _no_ids(result):\n location_hint = '.{}_0'.format(target_location_hint) if target_location_hint and is_string(target_location_hint) else ''\n result.tnt_id = '{}{}'.format(create_uuid(), location_hint)\n return result", "context": "def valid_visitor_id(visitor_id, target_location_hint): ...\ndef get_customer_id(visitor_id): ...\ndef _no_ids(visitor_id): ...\ndef valid_visitor_id(visitor_id, target_location_hint): ...\ndef valid_delivery_request(request, target_location_hint, valid_geo_request_context): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_valid_visitor_id_existing_tnt_id", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002536.py"} {"focal_file": "target_decisioning_engine/utils.py", "focal_class": null, "focal_method": "has_remote_dependency", "tests": "import unittest\n\nclass Test_has_remote_dependency(unittest.TestCase):\n def test_has_remote_dependency_no_artifact(self):\n with self.assertRaises(Exception) as err:\n has_remote_dependency(None, None)\n self.assertEqual(str(err.exception), 'The decisioning artifact is not available')\n\n def test_has_remote_dependency_mboxes_and_views(self):\n request_opts = {'execute': {'mboxes': [{'name': 'mbox1'}, {'name': 'mbox2'}]}, 'prefetch': {'mboxes': [{'name': 'mbox3'}], 'views': [{'name': 'view1'}, {'name': 'view2'}, {'name': 'view3'}]}}\n request = create_delivery_request(request_opts)\n remote_mboxes = ['mbox1']\n local_mboxes = ['mbox2']\n remote_views = ['view1']\n local_views = ['view2']\n artifact = DecisioningArtifact({'remoteMboxes': remote_mboxes, 'localMboxes': local_mboxes, 'remoteViews': remote_views, 'localViews': local_views})\n result = has_remote_dependency(artifact, request)\n self.assertEqual(result.get('remote_needed'), True)\n self.assertEqual(set(result.get('remote_mboxes')), set(['mbox1', 'mbox3']))\n self.assertEqual(set(result.get('remote_views')), set(['view1', 'view3']))\n", "method_code": "def has_remote_dependency(artifact, request):\n \"\"\"\n :param artifact: (target_decisioning_engine.types.decisioning_artifact.DecisioningArtifact)\n Decisioning artifact, required\n :param request: (delivery_api_client.Model.delivery_request.DeliveryRequest)\n Target Delivery API request, required\n :return: (dict) items with remote dependencies\n \"\"\"\n if not artifact:\n raise Exception(MESSAGES.get('ARTIFACT_NOT_AVAILABLE'))\n requested_mboxes = get_mbox_names(request)\n requested_views = get_view_names(request)\n remote_mboxes, local_mboxes, remote_views, local_views = [artifact.get(k, []) for k in ('remoteMboxes', 'localMboxes', 'remoteViews', 'localViews')]\n mboxes_that_require_remote = set()\n for mbox_name in remote_mboxes:\n if mbox_name in requested_mboxes:\n mboxes_that_require_remote.add(mbox_name)\n for mbox_name in requested_mboxes:\n if mbox_name not in local_mboxes:\n mboxes_that_require_remote.add(mbox_name)\n if has_requested_views(request) and (not requested_views):\n views_that_require_remote = set(remote_views)\n else:\n views_that_require_remote = set()\n for view_name in remote_views:\n if view_name in requested_views:\n views_that_require_remote.add(view_name)\n for view_name in requested_views:\n if view_name not in local_views:\n views_that_require_remote.add(view_name)\n return {'remote_needed': bool(mboxes_that_require_remote or views_that_require_remote), 'remote_mboxes': list(mboxes_that_require_remote), 'remote_views': list(views_that_require_remote)}", "context": "def has_remote_dependency(artifact, request): ...\ndef get_rule_key(rule): ...\ndef _get_default_parsed_url(url): ...\ndef parse_url(url): ...\ndef has_remote_dependency(artifact, request): ...\ndef match_major_version(semantic_version, major_version): ...\ndef get_valid_environment(environment_name): ...\ndef get_target_environment(config): ...\ndef get_cdn_environment(config): ...\ndef get_cdn_base_path(config): ...\ndef get_geo_lookup_path(config): ...\ndef determine_artifact_location(config): ...\ndef should_retry_http_code(status_code): ...\ndef get_http_codes_to_retry(): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_has_remote_dependency_no_artifact", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002537.py"} {"focal_file": "target_decisioning_engine/utils.py", "focal_class": null, "focal_method": "determine_artifact_location", "tests": "import unittest\n\nclass Test_determine_artifact_location(unittest.TestCase):\n def test_determine_artifact_location(self):\n config = DecisioningConfig('MyClient', '12345@AdobeOrg', environment=ENVIRONMENT_DEV, cdn_environment=ENVIRONMENT_STAGE)\n artifact_location = determine_artifact_location(config)\n self.assertEqual(artifact_location, 'https://assets.staging.adobetarget.com/MyClient/development/v1/rules.json')\n\n def test_determine_artifact_location_invalid_env(self):\n config = DecisioningConfig('MyClient', '12345@AdobeOrg', environment='bad')\n mock_logger = Mock()\n with patch('target_decisioning_engine.utils.logger', mock_logger):\n artifact_location = determine_artifact_location(config)\n self.assertEqual(artifact_location, 'https://assets.adobetarget.com/MyClient/production/v1/rules.json')\n self.assertEqual(mock_logger.debug.call_count, 1)\n self.assertEqual(mock_logger.debug.call_args[0][0], \"'bad' is not a valid target environment, defaulting to 'production'.\")\n\n def test_determine_artifact_location_filter_missing_parts(self):\n config = DecisioningConfig(None, None, environment=ENVIRONMENT_DEV)\n artifact_location = determine_artifact_location(config)\n self.assertEqual(artifact_location, 'https://assets.adobetarget.com/development/v1/rules.json')\n", "method_code": "def determine_artifact_location(config):\n \"\"\"\n :param config: (target_decisioning_engine.types.decisioning_config.DecisioningConfig) config\n \"\"\"\n target_environment = get_target_environment(config)\n location_parts = [get_cdn_base_path(config), config.client, target_environment, 'v{}'.format(SUPPORTED_ARTIFACT_MAJOR_VERSION), ARTIFACT_FILENAME]\n filtered = filter(None, location_parts)\n return '/'.join(filtered)", "context": "def determine_artifact_location(config): ...\ndef get_rule_key(rule): ...\ndef _get_default_parsed_url(url): ...\ndef parse_url(url): ...\ndef has_remote_dependency(artifact, request): ...\ndef match_major_version(semantic_version, major_version): ...\ndef get_valid_environment(environment_name): ...\ndef get_target_environment(config): ...\ndef get_cdn_environment(config): ...\ndef get_cdn_base_path(config): ...\ndef get_geo_lookup_path(config): ...\ndef determine_artifact_location(config): ...\ndef should_retry_http_code(status_code): ...\ndef get_http_codes_to_retry(): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_determine_artifact_location", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002538.py"} {"focal_file": "target_tools/tests/delivery_request_setup.py", "focal_class": null, "focal_method": "create_delivery_request", "tests": "import unittest\n\nclass Test_create_delivery_request(unittest.TestCase):\n @responses.activate\n def test_get_attributes_add_mbox_to_delivery_request(self):\n setup_mock('get_attributes', responses)\n opts = deepcopy(self.get_attributes_options)\n prefetch = {'mboxes': [{'name': 'feature-flag-a', 'index': 2}]}\n opts['request']['prefetch'] = prefetch\n opts['request']['execute'] = None\n opts['request'] = create_delivery_request(opts['request'])\n attributes = self.client.get_attributes(['feature-flag-b'], opts)\n self.assertTrue(attributes.get_value('feature-flag-b', 'show_feature_y'))\n self.assertDictEqual(attributes.as_object('feature-flag-b'), {'purchase_experience': 'beta2', 'show_feature_y': True, 'cart_version': 1.3, 'customer_survey_value': 102})\n", "method_code": "def create_delivery_request(request_dict):\n \"\"\"Create new DeliveryRequest from request dict\"\"\"\n _id = create_visitor_id(request_dict.get('id'))\n _property = create_property(request_dict.get('property'))\n context = create_context(request_dict.get('context'))\n experience_cloud = create_experience_cloud(request_dict.get('experienceCloud'))\n execute = create_execute(request_dict.get('execute'))\n prefetch = create_prefetch(request_dict.get('prefetch'))\n notifications = create_notifications(request_dict.get('notifications'))\n trace = create_trace(request_dict.get('trace'))\n request_id = request_dict.get('requestId')\n qa_mode = create_qa_mode(request_dict.get('qaMode'))\n preview = create_preview(request_dict.get('preview'))\n delivery_request = DeliveryRequest(id=_id, _property=_property, context=context, experience_cloud=experience_cloud, execute=execute, prefetch=prefetch, notifications=notifications, trace=trace, request_id=request_id, qa_mode=qa_mode, preview=preview)\n return delivery_request", "context": "def create_delivery_request(request_dict): ...\ndef create_customer_id(customer_id): ...\ndef create_customer_ids(customer_ids): ...\ndef create_visitor_id(_id): ...\ndef create_property(_property): ...\ndef create_mobile_platform(mobile_platform): ...\ndef create_application(application): ...\ndef create_screen(screen): ...\ndef create_window(window): ...\ndef create_browser(browser): ...\ndef create_geo(geo): ...\ndef create_address(address): ...\ndef create_context(context): ...\ndef create_analytics(analytics): ...\ndef create_audience_manager(audience_manager): ...\ndef create_experience_cloud(experience_cloud): ...\ndef create_order(order): ...\ndef create_product(product): ...\ndef create_view(view): ...\ndef create_views(views): ...\ndef create_page_load(page_load): ...\ndef create_mbox(mbox, index): ...\ndef create_mboxes(mboxes): ...\ndef create_execute(execute): ...\ndef create_prefetch(prefetch): ...\ndef create_notification(notification): ...\ndef create_notifications(notifications): ...\ndef create_trace(trace): ...\ndef create_preview(preview): ...\ndef create_qa_mode(qa_mode): ...\ndef create_delivery_request(request_dict): ...\n", "repository": "adobe/target-python-sdk", "test_name": "", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002539.py"} {"focal_file": "target_tools/attributes_provider.py", "focal_class": null, "focal_method": "get_response", "tests": "import unittest\n\nclass Test_get_response(unittest.TestCase):\n def test_get_response(self):\n self.assertDictEqual(self.attributes_provider.get_response(), GET_OFFERS_RESPONSE)\n", "method_code": " def get_response(self):\n \"\"\"\n :return (dict) returns get_offers response\n \"\"\"\n return self.offers_response\n ", "context": "class AttributesProvider():\n def get_response(self): ...\n def __init__(self, offers_response): ...\n def get_value(self, mbox_name, key): ...\n def as_object(self, mbox_name=None): ...\n\n self.offers_response = offers_response\n self.indexed = {}\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_response", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002540.py"} {"focal_file": "target_tools/attributes_provider.py", "focal_class": "AttributesProvider", "focal_method": "get_value", "tests": "import unittest\n\nclass Test_AttributesProvider_get_value(unittest.TestCase):\n def test_get_value_single_mbox(self):\n feature_a = AttributesProvider(GET_OFFERS_RESPONSE)\n self.assertEqual(feature_a.get_value('feature-flag-a', 'payment_experience'), 'legacy')\n self.assertFalse(feature_a.get_value('feature-flag-a', 'show_feature_x'))\n self.assertEqual(feature_a.get_value('feature-flag-a', 'payment_gateway_version'), 2.3)\n self.assertEqual(feature_a.get_value('feature-flag-a', 'customer_feedback_value'), 10)\n feature_b = AttributesProvider(GET_OFFERS_RESPONSE)\n self.assertEqual(feature_b.get_value('feature-flag-b', 'purchase_experience'), 'beta2')\n self.assertTrue(feature_b.get_value('feature-flag-b', 'show_feature_y'))\n self.assertEqual(feature_b.get_value('feature-flag-b', 'cart_version'), 1.3)\n self.assertEqual(feature_b.get_value('feature-flag-b', 'customer_survey_value'), 102)\n", "method_code": " def get_value(self, mbox_name, key):\n \"\"\"\n Gets value\n :param mbox_name: (str) The specified mbox name\n :param key: (str) Content dict key for the mbox content - if content is a dict\n \"\"\"\n if mbox_name not in self.indexed or key not in self.indexed.get(mbox_name):\n raise Exception(attribute_not_exist(key, mbox_name))\n return self.indexed.get(mbox_name).get(key)\n ", "context": "class AttributesProvider():\n def get_value(self, mbox_name, key): ...\n def __init__(self, offers_response): ...\n def as_object(self, mbox_name=None): ...\n def get_response(self): ...\n\n self.offers_response = offers_response\n self.indexed = {}\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_value_single_mbox", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002541.py"} {"focal_file": "target_tools/client_info.py", "focal_class": null, "focal_method": "browser_from_user_agent", "tests": "import unittest\n\nclass Test_browser_from_user_agent(unittest.TestCase):\n def test_browser_from_user_agent_no_agent(self):\n result = browser_from_user_agent()\n self.validate_browser(result, UNKNOWN, UNKNOWN_VERSION)\n\n def test_browser_from_user_agent_unknown_agent(self):\n result = browser_from_user_agent('bad secret agent')\n self.validate_browser(result, UNKNOWN, UNKNOWN_VERSION)\n\n def test_browser_from_user_agent_ie_11(self):\n result = browser_from_user_agent(IE11_WIN)\n self.validate_browser(result, 'IE', 11)\n\n def test_browser_from_user_agent_ie_7(self):\n result = browser_from_user_agent(IE11_COMPAT_WIN)\n self.validate_browser(result, 'IE', 11)\n\n def test_browser_from_user_agent_firefox_78(self):\n result = browser_from_user_agent(FIREFOX_MAC)\n self.validate_browser(result, 'Firefox', 78)\n\n def test_browser_from_user_agent_safari_13(self):\n result = browser_from_user_agent(SAFARI_MAC)\n self.validate_browser(result, 'Safari', 13)\n\n def test_browser_from_user_agent_mobile_safari_13(self):\n result = browser_from_user_agent(SAFARI_MOBILE)\n self.validate_browser(result, 'Mobile Safari', 13)\n\n def test_browser_from_user_agent_chrome_83(self):\n result = browser_from_user_agent(CHROME_MAC)\n self.validate_browser(result, 'Chrome', 83)\n\n def test_browser_from_user_agent_edge_83(self):\n result = browser_from_user_agent(EDGE_WIN)\n self.validate_browser(result, 'Edge', 83)\n", "method_code": "def browser_from_user_agent(user_agent=None):\n \"\"\"Use regex to determine browser from the user agent\n :param user_agent: (str) user agent\n :return: (dict{\"name\": str, \"version\": int})\n \"\"\"\n if not user_agent:\n user_agent = ''\n agent_obj = parse(user_agent)\n major_version = parse_int(agent_obj.browser.version_string.split('.')[0]) if agent_obj.browser.version_string else -1\n return {'name': agent_obj.browser.family if agent_obj.browser.family != OTHER else UNKNOWN, 'version': major_version}", "context": "def browser_from_user_agent(user_agent=None): ...\ndef browser_from_user_agent(user_agent=None): ...\ndef operating_system_from_user_agent(user_agent): ...\ndef device_type_from_user_agent(user_agent): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_browser_from_user_agent_no_agent", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002542.py"} {"focal_file": "target_tools/client_info.py", "focal_class": null, "focal_method": "operating_system_from_user_agent", "tests": "import unittest\n\nclass Test_operating_system_from_user_agent(unittest.TestCase):\n def test_operating_system_from_user_agent_chrome_mac(self):\n os_name = operating_system_from_user_agent(CHROME_MAC)\n self.assertEqual(os_name, 'Mac OS X')\n\n def test_operating_system_from_user_agent_ie_11(self):\n os_name = operating_system_from_user_agent(IE11_WIN)\n self.assertEqual(os_name, 'Windows')\n\n def test_operating_system_from_user_agent_ie_11_compat(self):\n os_name = operating_system_from_user_agent(IE11_COMPAT_WIN)\n self.assertEqual(os_name, 'Windows')\n\n def test_operating_system_from_user_agent_safari_mobile(self):\n os_name = operating_system_from_user_agent(SAFARI_MOBILE)\n self.assertEqual(os_name, 'iOS')\n\n def test_operating_system_from_user_agent_android(self):\n os_name = operating_system_from_user_agent(ANDROID)\n self.assertEqual(os_name, 'Android')\n\n def test_operating_system_from_user_agent_ipod(self):\n os_name = operating_system_from_user_agent(IPOD)\n self.assertEqual(os_name, 'iOS')\n\n def test_operating_system_from_user_agent_ipad(self):\n os_name = operating_system_from_user_agent(IPAD)\n self.assertEqual(os_name, 'iOS')\n", "method_code": "def operating_system_from_user_agent(user_agent):\n \"\"\"Get OS from user agent\n :param user_agent: (str) user agent\n :return: (str) OS name\n \"\"\"\n agent_obj = parse(user_agent)\n return agent_obj.os.family if agent_obj.os.family != OTHER else UNKNOWN", "context": "def operating_system_from_user_agent(user_agent): ...\ndef browser_from_user_agent(user_agent=None): ...\ndef operating_system_from_user_agent(user_agent): ...\ndef device_type_from_user_agent(user_agent): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_operating_system_from_user_agent_chrome_mac", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002543.py"} {"focal_file": "target_tools/client_info.py", "focal_class": null, "focal_method": "device_type_from_user_agent", "tests": "import unittest\n\nclass Test_device_type_from_user_agent(unittest.TestCase):\n def test_device_type_from_user_agent_safari_mobile(self):\n device_type = device_type_from_user_agent(SAFARI_MOBILE)\n self.assertEqual(device_type, 'iPhone')\n\n def test_device_type_from_user_agent_ie_11(self):\n device_type = device_type_from_user_agent(IE11_WIN)\n self.assertEqual(device_type, 'Desktop')\n\n def test_device_type_from_user_agent_chrome(self):\n device_type = device_type_from_user_agent(CHROME_MAC)\n self.assertEqual(device_type, 'Mac')\n\n def test_device_type_from_user_agent_firefox(self):\n device_type = device_type_from_user_agent(FIREFOX_MAC)\n self.assertEqual(device_type, 'Mac')\n\n def test_device_type_from_user_agent_safari(self):\n device_type = device_type_from_user_agent(SAFARI_MAC)\n self.assertEqual(device_type, 'Mac')\n\n def test_device_type_from_user_agent_edge(self):\n device_type = device_type_from_user_agent(EDGE_WIN)\n self.assertEqual(device_type, 'Desktop')\n\n def test_device_type_from_user_agent_ipod(self):\n device_type = device_type_from_user_agent(IPOD)\n self.assertEqual(device_type, 'iPod')\n\n def test_device_type_from_user_agent_ipad(self):\n device_type = device_type_from_user_agent(IPAD)\n self.assertEqual(device_type, 'iPad')\n", "method_code": "def device_type_from_user_agent(user_agent):\n \"\"\"Gets device type from user agent\n :param user_agent: (str) browser user agent\n :return: (str) user device type\n \"\"\"\n agent_obj = parse(user_agent)\n return agent_obj.device.family if agent_obj.device.family != OTHER else DESKTOP", "context": "def device_type_from_user_agent(user_agent): ...\ndef browser_from_user_agent(user_agent=None): ...\ndef operating_system_from_user_agent(user_agent): ...\ndef device_type_from_user_agent(user_agent): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_device_type_from_user_agent_safari_mobile", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002544.py"} {"focal_file": "target_tools/event_provider.py", "focal_class": "EventProvider", "focal_method": "subscribe", "tests": "import unittest\n\nclass Test_EventProvider_subscribe(unittest.TestCase):\n def test_subscribe(self):\n called = {'was_called': False}\n\n def aloha(event):\n called['was_called'] = True\n self.assertEqual(event, {'type': 'aloha'})\n event_provider = EventProvider()\n event_provider.subscribe('aloha', aloha)\n event_provider.emit('aloha')\n self.assertEqual(event_provider.subscription_count, 1)\n self.assertTrue(called['was_called'])\n", "method_code": " def subscribe(self, event_name, callback_func):\n \"\"\"Subscribe to events\n :param event_name: (str) Event name, required\n :param callback_func: (callable) Callback function, required\n :return: (str)\n \"\"\"\n self.subscription_count += 1\n if not self.subscriptions.get(event_name):\n self.subscriptions[event_name] = {}\n self.subscriptions[event_name][str(self.subscription_count)] = callback_func\n return '{}:{}'.format(event_name, self.subscription_count)\n ", "context": "class EventProvider():\n def subscribe(self, event_name, callback_func): ...\n def __init__(self, events=None): ...\n def unsubscribe(self, event_id): ...\n def emit(self, event_name, payload=None): ...\n\n self.subscriptions = {}\n self.subscription_count = 0\n", "repository": "adobe/target-python-sdk", "test_name": "test_subscribe", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002545.py"} {"focal_file": "target_tools/event_provider.py", "focal_class": "EventProvider", "focal_method": "unsubscribe", "tests": "import unittest\n\nclass Test_EventProvider_unsubscribe(unittest.TestCase):\n def test_unsubscribe(self):\n aloha = MagicMock()\n event_provider = EventProvider()\n subscription_id = event_provider.subscribe('aloha', aloha)\n self.assertEqual(event_provider.subscription_count, 1)\n event_provider.emit('aloha')\n event_provider.unsubscribe(subscription_id)\n event_provider.emit('aloha')\n event_provider.emit('aloha')\n event_provider.emit('aloha')\n self.assertEqual(aloha.call_count, 1)\n self.assertEqual(event_provider.subscription_count, 0)\n", "method_code": " def unsubscribe(self, event_id):\n \"\"\"Unsubscribe from events\n :param event_id: (str) Event Id, required\n \"\"\"\n event_name, event_id = event_id.split(':')\n if self.subscriptions.get(event_name) and self.subscriptions.get(event_name).get(event_id):\n del self.subscriptions[event_name][event_id]\n self.subscription_count -= 1\n ", "context": "class EventProvider():\n def unsubscribe(self, event_id): ...\n def __init__(self, events=None): ...\n def subscribe(self, event_name, callback_func): ...\n def emit(self, event_name, payload=None): ...\n\n self.subscriptions = {}\n self.subscription_count = 0\n", "repository": "adobe/target-python-sdk", "test_name": "test_unsubscribe", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002546.py"} {"focal_file": "target_tools/logger.py", "focal_class": null, "focal_method": "get_logger", "tests": "import unittest\n\nclass Test_get_logger(unittest.TestCase):\n def test_get_logger_default(self):\n logging.basicConfig(level=logging.INFO)\n logger = get_logger()\n self.assertIsNotNone(logger)\n self.assertEqual(logger.name, LOGGER_NAME)\n self.assertEqual(logger.level, logging.INFO)\n logger.info('Something bad happened')\n self.assertEqual(logger, get_logger())\n\n def test_get_logger_custom(self):\n custom_logger = logging.getLogger('custom')\n custom_logger.setLevel(logging.ERROR)\n logger = get_logger(logger=custom_logger)\n self.assertIsNotNone(logger)\n self.assertEqual(logger.name, 'custom')\n self.assertEqual(logger.level, logging.ERROR)\n logger.error('Something bad happened')\n self.assertEqual(logger, get_logger())\n", "method_code": "def get_logger(logger=None):\n \"\"\"Returns singleton logger for sdk. By default, propagates to root logger at INFO level\n :param logger: (Logger) User-provided logger that overrides default for entire sdk\n :return: (Logger) Singleton logger for use throughout the sdk\n \"\"\"\n if this.LOG:\n return this.LOG\n if logger:\n this.LOG = logger\n else:\n this.LOG = logging.getLogger(LOGGER_NAME)\n this.LOG.setLevel(logging.INFO)\n return this.LOG", "context": "def get_logger(logger=None): ...\ndef get_logger(logger=None): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_logger_default", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002547.py"} {"focal_file": "target_tools/utils.py", "focal_class": null, "focal_method": "get_mbox_names", "tests": "import unittest\n\nclass Test_get_mbox_names(unittest.TestCase):\n def test_get_mbox_names(self):\n opts = deepcopy(self.get_attributes_options)\n opts['request'] = create_delivery_request(opts['request'])\n result = get_mbox_names(opts['request'])\n self.assertTrue(isinstance(result, set))\n self.assertEqual(len(result), 4)\n self.assertTrue('one' in result)\n self.assertTrue('two' in result)\n self.assertTrue('three' in result)\n self.assertTrue('four' in result)\n", "method_code": "def get_mbox_names(delivery_request):\n \"\"\"\n :param delivery_request: (delivery_api_client.Model.delivery_request.DeliveryRequest)\n Target Delivery API request, required\n :return: (set) Set of mbox names\n \"\"\"\n return get_names_for_requested(MBOXES, delivery_request)", "context": "def get_mbox_names(delivery_request): ...\ndef requires_decisioning_engine(decisioning_method): ...\ndef get_property_token(_property=None): ...\ndef get_property(config, request): ...\ndef decisioning_engine_ready(decisioning_engine): ...\ndef has_requested(items_key, delivery_request): ...\ndef has_requested_views(delivery_request): ...\ndef get_names_for_requested(items_key, delivery_request): ...\ndef get_mbox_names(delivery_request): ...\ndef add_mboxes_to_request(mbox_names, request, request_type='execute'): ...\ndef get_view_names(delivery_request): ...\ndef noop(*args, **kwargs): ...\ndef memoize(func, args_resolver=None): ...\ndef compose_functions(outer, inner): ...\ndef is_string(value): ...\ndef is_int(value): ...\ndef parse_int(value): ...\ndef parse_float(value): ...\ndef is_dict(value): ...\ndef is_list(value): ...\ndef create_uuid(): ...\ndef get_epoch_time(utc_datetime=None): ...\ndef get_epoch_time_milliseconds(utc_datetime=None): ...\ndef get_timezone_offset(): ...\ndef flatten_list(_list): ...\ndef remove_empty_values(_dict): ...\ndef is_empty(val): ...\ndef to_dict(obj): ...\ndef get_value_from_object(obj, key): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_mbox_names", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002548.py"} {"focal_file": "target_tools/utils.py", "focal_class": null, "focal_method": "add_mboxes_to_request", "tests": "import unittest\n\nclass Test_add_mboxes_to_request(unittest.TestCase):\n def test_add_mboxes_to_request_adds_prefetch(self):\n opts = deepcopy(self.get_attributes_options)\n prefetch = {'mboxes': []}\n opts['request']['prefetch'] = prefetch\n opts['request']['execute'] = None\n opts['request'] = create_delivery_request(opts['request'])\n mboxes_to_add = ['mbox-foo', 'mbox-bar', 'mbox-baz']\n add_mboxes_to_request(mboxes_to_add, opts['request'], 'prefetch')\n self.assertEqual(len(opts['request'].prefetch.mboxes), 3)\n for index, mbox in enumerate(opts['request'].prefetch.mboxes):\n self.assertEqual(mbox.index, index + 1)\n self.assertEqual(mbox.name, mboxes_to_add[index])\n\n def test_add_mboxes_to_request_adds_execute(self):\n opts = deepcopy(self.get_attributes_options)\n execute = {'mboxes': []}\n opts['request']['prefetch'] = None\n opts['request']['execute'] = execute\n opts['request'] = create_delivery_request(opts['request'])\n mboxes_to_add = ['mbox-foo', 'mbox-bar', 'mbox-baz']\n add_mboxes_to_request(mboxes_to_add, opts['request'], 'execute')\n self.assertEqual(len(opts['request'].execute.mboxes), 3)\n for index, mbox in enumerate(opts['request'].execute.mboxes):\n self.assertEqual(mbox.index, index + 1)\n self.assertEqual(mbox.name, mboxes_to_add[index])\n\n def test_add_mboxes_to_request_no_duplicates_preserves_existing(self):\n opts = deepcopy(self.get_attributes_options)\n prefetch = {'mboxes': [{'name': 'mbox-foo', 'index': 6}, {'name': 'mbox-jab', 'index': 2}]}\n opts['request']['prefetch'] = prefetch\n opts['request']['execute'] = None\n opts['request'] = create_delivery_request(opts['request'])\n mboxes_to_add = ['mbox-foo', 'mbox-bar', 'mbox-baz']\n add_mboxes_to_request(mboxes_to_add, opts['request'], 'prefetch')\n self.assertEqual(len(opts['request'].prefetch.mboxes), 4)\n resulting_mboxes = opts['request'].prefetch.mboxes\n self.assertEqual(resulting_mboxes[0].index, 6)\n self.assertEqual(resulting_mboxes[0].name, 'mbox-foo')\n self.assertEqual(resulting_mboxes[1].index, 2)\n self.assertEqual(resulting_mboxes[1].name, 'mbox-jab')\n self.assertEqual(resulting_mboxes[2].index, 7)\n self.assertEqual(resulting_mboxes[2].name, 'mbox-bar')\n self.assertEqual(resulting_mboxes[3].index, 8)\n self.assertEqual(resulting_mboxes[3].name, 'mbox-baz')\n", "method_code": "def add_mboxes_to_request(mbox_names, request, request_type='execute'):\n \"\"\"Modifies request in place to add specified mboxes\n :param mbox_names: (list) A list of mbox names that contain JSON content attributes, required\n :param request: (delivery_api_client.Model.delivery_request.DeliveryRequest)\n Target View Delivery API request, required\n :param request_type: (\"execute\"|\"prefetch\")\n \"\"\"\n requested_mboxes = get_mbox_names(request)\n mboxes = []\n if not getattr(request, request_type):\n subreq_instance = REQUEST_TYPE_MAP.get(request_type)()\n setattr(request, request_type, subreq_instance)\n subreq = getattr(request, request_type)\n if subreq.mboxes:\n mboxes.extend(subreq.mboxes)\n highest_user_specified_index_mbox = max(mboxes, key=lambda mbox: mbox.index).index if mboxes else 0\n next_index = highest_user_specified_index_mbox + 1\n for mbox_name in (name for name in mbox_names if name not in requested_mboxes):\n mboxes.append(MboxRequest(name=mbox_name, index=next_index))\n next_index += 1\n subreq.mboxes = mboxes\n return request", "context": "def add_mboxes_to_request(mbox_names, request, request_type='execute'): ...\ndef requires_decisioning_engine(decisioning_method): ...\ndef get_property_token(_property=None): ...\ndef get_property(config, request): ...\ndef decisioning_engine_ready(decisioning_engine): ...\ndef has_requested(items_key, delivery_request): ...\ndef has_requested_views(delivery_request): ...\ndef get_names_for_requested(items_key, delivery_request): ...\ndef get_mbox_names(delivery_request): ...\ndef add_mboxes_to_request(mbox_names, request, request_type='execute'): ...\ndef get_view_names(delivery_request): ...\ndef noop(*args, **kwargs): ...\ndef memoize(func, args_resolver=None): ...\ndef compose_functions(outer, inner): ...\ndef is_string(value): ...\ndef is_int(value): ...\ndef parse_int(value): ...\ndef parse_float(value): ...\ndef is_dict(value): ...\ndef is_list(value): ...\ndef create_uuid(): ...\ndef get_epoch_time(utc_datetime=None): ...\ndef get_epoch_time_milliseconds(utc_datetime=None): ...\ndef get_timezone_offset(): ...\ndef flatten_list(_list): ...\ndef remove_empty_values(_dict): ...\ndef is_empty(val): ...\ndef to_dict(obj): ...\ndef get_value_from_object(obj, key): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_add_mboxes_to_request_adds_prefetch", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002549.py"} {"focal_file": "target_tools/utils.py", "focal_class": null, "focal_method": "get_epoch_time", "tests": "import unittest\n\nclass Test_get_epoch_time(unittest.TestCase):\n def test_get_epoch_time_now(self):\n with patch('target_tools.utils.datetime.datetime', Mock(wraps=datetime.datetime)) as mock_datetime:\n mock_datetime.utcnow.return_value = MOCK_DATE\n result = get_epoch_time()\n self.assertEqual(result, 1616424781)\n self.assertEqual(mock_datetime.utcnow.call_count, 1)\n\n def test_get_epoch_time_passed_datetime(self):\n with patch('target_tools.utils.datetime.datetime', Mock(wraps=datetime.datetime)) as mock_datetime:\n result = get_epoch_time(MOCK_DATE)\n self.assertEqual(result, 1616424781)\n self.assertEqual(mock_datetime.utcnow.call_count, 0)\n", "method_code": "def get_epoch_time(utc_datetime=None):\n \"\"\"Get epoch time (seconds) from either passed in UTC datetime or current datetime\"\"\"\n if not utc_datetime:\n utc_datetime = datetime.datetime.utcnow()\n return math.ceil((utc_datetime - EPOCH_START).total_seconds())", "context": "def get_epoch_time(utc_datetime=None): ...\ndef requires_decisioning_engine(decisioning_method): ...\ndef get_property_token(_property=None): ...\ndef get_property(config, request): ...\ndef decisioning_engine_ready(decisioning_engine): ...\ndef has_requested(items_key, delivery_request): ...\ndef has_requested_views(delivery_request): ...\ndef get_names_for_requested(items_key, delivery_request): ...\ndef get_mbox_names(delivery_request): ...\ndef add_mboxes_to_request(mbox_names, request, request_type='execute'): ...\ndef get_view_names(delivery_request): ...\ndef noop(*args, **kwargs): ...\ndef memoize(func, args_resolver=None): ...\ndef compose_functions(outer, inner): ...\ndef is_string(value): ...\ndef is_int(value): ...\ndef parse_int(value): ...\ndef parse_float(value): ...\ndef is_dict(value): ...\ndef is_list(value): ...\ndef create_uuid(): ...\ndef get_epoch_time(utc_datetime=None): ...\ndef get_epoch_time_milliseconds(utc_datetime=None): ...\ndef get_timezone_offset(): ...\ndef flatten_list(_list): ...\ndef remove_empty_values(_dict): ...\ndef is_empty(val): ...\ndef to_dict(obj): ...\ndef get_value_from_object(obj, key): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_epoch_time_now", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002550.py"} {"focal_file": "target_tools/utils.py", "focal_class": null, "focal_method": "get_epoch_time_milliseconds", "tests": "import unittest\n\nclass Test_get_epoch_time_milliseconds(unittest.TestCase):\n def test_get_epoch_time_milliseconds_now(self):\n with patch('target_tools.utils.datetime.datetime', Mock(wraps=datetime.datetime)) as mock_datetime:\n mock_datetime.utcnow.return_value = MOCK_DATE\n result = get_epoch_time_milliseconds()\n self.assertEqual(result, 1616424781000)\n self.assertEqual(mock_datetime.utcnow.call_count, 1)\n\n def test_get_epoch_time_milliseconds_passed_datetime(self):\n with patch('target_tools.utils.datetime.datetime', Mock(wraps=datetime.datetime)) as mock_datetime:\n result = get_epoch_time_milliseconds(MOCK_DATE)\n self.assertEqual(result, 1616424781000)\n self.assertEqual(mock_datetime.utcnow.call_count, 0)\n", "method_code": "def get_epoch_time_milliseconds(utc_datetime=None):\n \"\"\"Get epoch time (milliseconds) from either passed in UTC datetime or current datetime\"\"\"\n epoch_seconds = get_epoch_time(utc_datetime)\n return epoch_seconds * MILLISECONDS_IN_SECOND", "context": "def get_epoch_time_milliseconds(utc_datetime=None): ...\ndef requires_decisioning_engine(decisioning_method): ...\ndef get_property_token(_property=None): ...\ndef get_property(config, request): ...\ndef decisioning_engine_ready(decisioning_engine): ...\ndef has_requested(items_key, delivery_request): ...\ndef has_requested_views(delivery_request): ...\ndef get_names_for_requested(items_key, delivery_request): ...\ndef get_mbox_names(delivery_request): ...\ndef add_mboxes_to_request(mbox_names, request, request_type='execute'): ...\ndef get_view_names(delivery_request): ...\ndef noop(*args, **kwargs): ...\ndef memoize(func, args_resolver=None): ...\ndef compose_functions(outer, inner): ...\ndef is_string(value): ...\ndef is_int(value): ...\ndef parse_int(value): ...\ndef parse_float(value): ...\ndef is_dict(value): ...\ndef is_list(value): ...\ndef create_uuid(): ...\ndef get_epoch_time(utc_datetime=None): ...\ndef get_epoch_time_milliseconds(utc_datetime=None): ...\ndef get_timezone_offset(): ...\ndef flatten_list(_list): ...\ndef remove_empty_values(_dict): ...\ndef is_empty(val): ...\ndef to_dict(obj): ...\ndef get_value_from_object(obj, key): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_get_epoch_time_milliseconds_now", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002551.py"} {"focal_file": "target_tools/utils.py", "focal_class": null, "focal_method": "is_empty", "tests": "import unittest\n\nclass Test_is_empty(unittest.TestCase):\n def test_is_empty_list(self):\n self.assertTrue(is_empty(None))\n self.assertTrue(is_empty(''))\n self.assertTrue(is_empty([]))\n self.assertTrue(is_empty({}))\n self.assertTrue(is_empty(set()))\n self.assertTrue(is_empty(tuple()))\n self.assertFalse(is_empty('not empty'))\n self.assertFalse(is_empty([1]))\n self.assertFalse(is_empty({'a': 'b'}))\n self.assertFalse(is_empty(set([1, 2, 3])))\n self.assertFalse(is_empty(tuple(['x', 'y'])))\n", "method_code": "def is_empty(val):\n \"\"\"Returns True if val is Falsy, otherwise returns False\"\"\"\n return not bool(val)", "context": "def is_empty(val): ...\ndef requires_decisioning_engine(decisioning_method): ...\ndef get_property_token(_property=None): ...\ndef get_property(config, request): ...\ndef decisioning_engine_ready(decisioning_engine): ...\ndef has_requested(items_key, delivery_request): ...\ndef has_requested_views(delivery_request): ...\ndef get_names_for_requested(items_key, delivery_request): ...\ndef get_mbox_names(delivery_request): ...\ndef add_mboxes_to_request(mbox_names, request, request_type='execute'): ...\ndef get_view_names(delivery_request): ...\ndef noop(*args, **kwargs): ...\ndef memoize(func, args_resolver=None): ...\ndef compose_functions(outer, inner): ...\ndef is_string(value): ...\ndef is_int(value): ...\ndef parse_int(value): ...\ndef parse_float(value): ...\ndef is_dict(value): ...\ndef is_list(value): ...\ndef create_uuid(): ...\ndef get_epoch_time(utc_datetime=None): ...\ndef get_epoch_time_milliseconds(utc_datetime=None): ...\ndef get_timezone_offset(): ...\ndef flatten_list(_list): ...\ndef remove_empty_values(_dict): ...\ndef is_empty(val): ...\ndef to_dict(obj): ...\ndef get_value_from_object(obj, key): ...\n", "repository": "adobe/target-python-sdk", "test_name": "test_is_empty_list", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002552.py"} {"focal_file": "tadek/core/location.py", "focal_class": null, "focal_method": "getModels", "tests": "import unittest\n\nclass Test_getModels(unittest.TestCase):\n def testGetModels(self):\n location.add(_LOCATION_DIR)\n mdls = location.getModels()\n self.failUnless('model1' in mdls)\n self.failUnless('model2' in mdls)\n", "method_code": "def getModels():\n \"\"\"\n Gets a dictionary containing all currently avalaible models modules.\n\n :return: A dictionary with models modules\n :rtype: dictionary\n \"\"\"\n content = _getModuleContent(models)\n content.pop('__init__', None)\n return content", "context": "def getModels(): ...\ndef add(path, enabled=True): ...\ndef remove(path): ...\ndef get(enabled=None): ...\ndef enable(path): ...\ndef disable(path): ...\ndef clear(): ...\ndef getModels(): ...\ndef getSteps(): ...\ndef getCases(): ...\ndef getSuites(): ...\ndef _getDirContent(dir, package=None): ...\ndef _getModuleContent(module): ...\ndef _addModuleDir(module, path): ...\ndef _clearModule(module, path=None): ...\ndef _removeModuleDir(module, path): ...\n", "repository": "tadek-project/tadek-common", "test_name": "testGetModels", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002553.py"} {"focal_file": "tadek/core/location.py", "focal_class": null, "focal_method": "getSuites", "tests": "import unittest\n\nclass Test_getSuites(unittest.TestCase):\n def testGetSuites(self):\n location.add(_LOCATION_DIR)\n suites = location.getSuites()\n self.failUnless('suitespkg1' in suites)\n self.failUnless('suitespkg1.suitesmdl11' in suites)\n self.failUnless('suitespkg1.suitesmdl12' in suites)\n self.failUnless('suitespkg2' in suites)\n self.failUnless('suitespkg2.suitesmdl21' in suites)\n self.failUnless('suitespkg2.suitesmdl22' in suites)\n", "method_code": "def getSuites():\n \"\"\"\n Gets a dictionary containing all currently avalaible root test suites\n modules.\n\n :return: A dictionary with test suites modules\n :rtype: dictionary\n \"\"\"\n content = _getModuleContent(testsuites)\n content.pop('__init__', None)\n return content", "context": "def getSuites(): ...\ndef add(path, enabled=True): ...\ndef remove(path): ...\ndef get(enabled=None): ...\ndef enable(path): ...\ndef disable(path): ...\ndef clear(): ...\ndef getModels(): ...\ndef getSteps(): ...\ndef getCases(): ...\ndef getSuites(): ...\ndef _getDirContent(dir, package=None): ...\ndef _getModuleContent(module): ...\ndef _addModuleDir(module, path): ...\ndef _clearModule(module, path=None): ...\ndef _removeModuleDir(module, path): ...\n", "repository": "tadek-project/tadek-common", "test_name": "testGetSuites", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002554.py"} {"focal_file": "tadek/core/settings.py", "focal_class": null, "focal_method": "getBool", "tests": "import unittest\n\nclass Test_getBool(unittest.TestCase):\n def testGetBool(self):\n TEST_FILE_NAME = self._filenames[0]\n config.set(TEST_FILE_NAME, 'Test', settings._META_OPTION_NAME, settings._META_OPTION_VALUE)\n config.set(TEST_FILE_NAME, 'Test', 'test_1', 'True')\n item = settings.get(TEST_FILE_NAME, 'Test', 'test_1')\n self.assertEqual(True, item.getBool())\n self.assertEqual(True, bool(item))\n config.set(TEST_FILE_NAME, 'Test', 'test_1', 'False')\n self.assertEqual(False, item.getBool())\n self.assertEqual(False, bool(item))\n config.set(TEST_FILE_NAME, 'Test', 'test_1', 'Name')\n self.assertEqual(None, item.getBool())\n self.assertEqual(False, bool(item))\n", "method_code": " def getBool(self):\n \"\"\"\n Gets a value of the settings option converted to boolean. If the option\n does not exist the 'None' is returned.\n \n :return: A value of the option\n :rtype: boolean\n \"\"\"\n return config.getBool(self._name, self._section, self._option, self._default)\n ", "context": "class SettingsOption():\n def getBool(self): ...\n def __init__(self, name, section, option, default=None): ...\n def __eq__(self, value): ...\n def __ne__(self, value): ...\n def __str__(self): ...\n def __nonzero__(self): ...\n def __int__(self): ...\n def __iter__(self): ...\n def name(self): ...\n def get(self): ...\n def getInt(self): ...\n def getList(self): ...\n def set(self, value): ...\n def remove(self): ...\n\n self._name = name\n self._section = section\n self._option = option\n self._default = default\n", "repository": "tadek-project/tadek-common", "test_name": "testGetBool", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002555.py"} {"focal_file": "tadek/core/settings.py", "focal_class": null, "focal_method": "getInt", "tests": "import unittest\n\nclass Test_getInt(unittest.TestCase):\n def testGetInt(self):\n TEST_FILE_NAME = self._filenames[0]\n config.set(TEST_FILE_NAME, 'Test', settings._META_OPTION_NAME, settings._META_OPTION_VALUE)\n config.set(TEST_FILE_NAME, 'Test', 'test_1', '1')\n item = settings.get(TEST_FILE_NAME, 'Test', 'test_1')\n self.assertEqual(1, item.getInt())\n self.assertEqual(1, int(item))\n config.set(TEST_FILE_NAME, 'Test', 'test_1', 'True')\n self.assertTrue(item.getInt() is None)\n self.assertEqual(0, int(item))\n", "method_code": " def getInt(self):\n \"\"\"\n Gets a value of the settings option converted to integer. If the option\n does not exist the 'None' is returned.\n \n :return: A value of the option\n :rtype: integer\n \"\"\"\n return config.getInt(self._name, self._section, self._option, self._default)\n ", "context": "class SettingsOption():\n def getInt(self): ...\n def __init__(self, name, section, option, default=None): ...\n def __eq__(self, value): ...\n def __ne__(self, value): ...\n def __str__(self): ...\n def __nonzero__(self): ...\n def __int__(self): ...\n def __iter__(self): ...\n def name(self): ...\n def get(self): ...\n def getBool(self): ...\n def getList(self): ...\n def set(self, value): ...\n def remove(self): ...\n\n self._name = name\n self._section = section\n self._option = option\n self._default = default\n", "repository": "tadek-project/tadek-common", "test_name": "testGetInt", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002556.py"} {"focal_file": "tadek/core/settings.py", "focal_class": null, "focal_method": "remove", "tests": "import unittest\n\nclass Test_remove(unittest.TestCase):\n def testValueRemove(self):\n TEST_FILE_NAME = self._filenames[0]\n config.set(TEST_FILE_NAME, 'Test', settings._META_OPTION_NAME, settings._META_OPTION_VALUE)\n config.set(TEST_FILE_NAME, 'Test', 'test_1', '1')\n item = settings.get(TEST_FILE_NAME, 'Test', 'test_1')\n self.assertTrue('test_1' in config.get(TEST_FILE_NAME, 'Test'))\n item.remove()\n self.assertFalse('test_1' in config.get(TEST_FILE_NAME, 'Test'))\n", "method_code": " def remove(self):\n \"\"\"\n Removes the settings section.\n \"\"\"\n config.remove(self._name, self._section)\n ", "context": "class SettingsSection():\n def remove(self): ...\n def __init__(self, name, section): ...\n def __iter__(self): ...\n def __getitem__(self, option): ...\n def __setitem__(self, option, value): ...\n def get(self, option, default=None): ...\n def name(self): ...\n\n self._name = name\n self._section = section\n", "repository": "tadek-project/tadek-common", "test_name": "testValueRemove", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002557.py"} {"focal_file": "tadek/core/settings.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def testRemoveSettings(self):\n TEST_FILE_NAME = self._filenames[0]\n config.set(TEST_FILE_NAME, 'Test', settings._META_OPTION_NAME, settings._META_OPTION_VALUE)\n config.set(TEST_FILE_NAME, 'Test', 'test_1', '1')\n item_1 = settings.get(TEST_FILE_NAME, 'Test')\n item_1.remove()\n self.assertFalse('Test' in config.get(TEST_FILE_NAME))\n\n def testHaveSettings(self):\n TEST_FILE_NAME = self._filenames[0]\n config.set(TEST_FILE_NAME, 'Test', 'test_1', 'True')\n self.assertTrue(settings.get(TEST_FILE_NAME, 'Test') is None)\n self.assertTrue(settings.get(TEST_FILE_NAME, 'Test', 'test_1') is None)\n self.assertTrue(settings.get(TEST_FILE_NAME, 'Test2') is None)\n config.set(TEST_FILE_NAME, 'Test', settings._META_OPTION_NAME, settings._META_OPTION_VALUE)\n self.assertFalse(settings.get(TEST_FILE_NAME, 'Test') is None)\n self.assertFalse(settings.get(TEST_FILE_NAME, 'Test', 'test_1') is None)\n self.assertTrue(settings.get(TEST_FILE_NAME, 'Test2') is None)\n", "method_code": "def get(name=None, section=None, option=None, default=None, force=False):\n \"\"\"\n Returns different results depending on number of given arguments:\n - if settings name, section and option are given then returns\n a SettingsOption object representing the specified option,\n - if only settings name and section are given then returns\n a SettingsSection object representing the specified section,\n - if only settings name is given then returns a list of available sections\n in the configuration file,\n - if no argument is given then returns a list of available settings.\n\n :param name: A name of configuration\n :type name: string\n :param section: A name of the section\n :type section: string\n :param option: A name of the option\n :type option: string\n :param default: An optional argument that can specify a default value\n :type default: string\n :param force: Makes a configuration section to be a settings section\n :type force: boolean\n :return: A list of settings, SettingsSection or SettingsOption object\n :rtype: list or SettingsSection or SettingsOption\n \"\"\"\n if force and section:\n _setSettings(name, section)\n if option:\n if _isSettings(name, section, option):\n return SettingsOption(name, section, option, default)\n return default\n elif section:\n if _isSettings(name, section):\n return SettingsSection(name, section)\n return None\n elif name:\n sections = []\n for section in config.get(name):\n if force or _isSettings(name, section):\n sections.append(section)\n return sections\n else:\n names = []\n for name in config.get():\n if force or _isSettings(name):\n names.append(name)\n return names", "context": "def get(name=None, section=None, option=None, default=None, force=False): ...\ndef _isSettings(name, section=None, option=None): ...\ndef _setSettings(name, section): ...\ndef get(name=None, section=None, option=None, default=None, force=False): ...\ndef set(name, section, option=None, value=None, force=False): ...\n", "repository": "tadek-project/tadek-common", "test_name": "testRemoveSettings", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002558.py"} {"focal_file": "tadek/engine/loader.py", "focal_class": "TestLoader", "focal_method": "loadFromNames", "tests": "import unittest\n\nclass Test_TestLoader_loadFromNames(unittest.TestCase):\n def testLoadFromNames(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames()\n self.failUnless(tests)\n self.failIf(errors)\n\n def testLoadFromNamesPkgName(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg1')\n self.failUnlessEqual(len(tests), 4)\n self.failIf(errors)\n\n def testLoadFromNamesInvalidPkgName(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg99')\n self.failIf(tests)\n self.failUnless(errors)\n\n def testLoadFromNamesMdlName(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg2.suitesmdl21')\n self.failUnlessEqual(len(tests), 2)\n self.failIf(errors)\n\n def testLoadFromNamesInvalidMdlName(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg2.suitesmdl29')\n self.failIf(tests)\n self.failUnless(errors)\n\n def testLoadFromNamesClassName(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg1.suitesmdl11.Suite112')\n self.failUnlessEqual(len(tests), 1)\n self.failIf(errors)\n\n def testLoadFromNamesCaseName(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg2.suitesmdl22.Suite221.case2211')\n self.failUnlessEqual(len(tests), 1)\n self.failIf(errors)\n\n def testLoadFromNamesCaseNames(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg1.suitesmdl11.Suite111.case1111', 'suitespkg1.suitesmdl11.Suite112.case1122', 'suitespkg2.suitesmdl22.Suite221.case2211')\n self.failUnlessEqual(len(tests), 3)\n self.failIf(errors)\n\n def testLoadFromNamesMixedNames(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg2.suitesmdl21', 'suitespkg1.suitesmdl11.Suite111.case1112', 'suitespkg1.suitesmdl11.Suite111', 'suitespkg2.suitesmdl21.Suite212.case2121')\n self.failUnlessEqual(len(tests), 3)\n self.failIf(errors)\n\n def testLoadFromNamesSimilarNames(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg2.suitesmdl21.Suite211.case2111', 'suitespkg2.suitesmdl21.Suite211.case21112', 'suitespkg2.suitesmdl21.Suite211.case211111')\n self.failUnlessEqual(len(tests), 1)\n self.failUnlessEqual(len([case for case in tests[0]]), 3)\n self.failIf(errors)\n\n def testLoadFromNamesSameNames(self):\n loader = TestLoader()\n tests, errors = loader.loadFromNames('suitespkg1.suitesmdl12.Suite121', 'suitespkg1.suitesmdl12.', 'suitespkg1.suitesmdl12.Suite122', 'suitespkg1.suitesmdl12.Suite121', 'suitespkg1.suitesmdl12.Suite121.case1212')\n self.failUnlessEqual(len(tests), 2)\n self.failIf(errors)\n", "method_code": " def loadFromNames(self, *names):\n \"\"\"\n Loads tests of the given names.\n \"\"\"\n location.clear()\n tests = []\n errors = []\n names = names or None\n if names:\n nms = []\n for name in names:\n name = name.strip().strip('.')\n if not name:\n continue\n ok = True\n for nm in nms[:]:\n if name == nm or name.startswith(nm + '.'):\n ok = False\n break\n if nm.startswith(name + '.'):\n nms.remove(nm)\n if ok:\n nms.append(name)\n names = nms\n modules = {}\n for mdl in sorted(location.getSuites(), reverse=True):\n if names is None:\n modules[mdl] = None\n else:\n for name in names[:]:\n if mdl == name or mdl.startswith(name + '.'):\n modules[mdl] = None\n if mdl == name:\n names.remove(name)\n elif name.startswith(mdl + '.'):\n if mdl not in modules:\n modules[mdl] = []\n modules[mdl].append(name[len(mdl) + 1:])\n names.remove(name)\n if names:\n for name in names:\n modules[name] = None\n for mdl, nms in modules.iteritems():\n mtests, merrs = self.loadFromModule(mdl, nms)\n tests.extend(mtests)\n errors.extend(merrs)\n return (tests, errors)\n ", "context": "class TestLoader(object):\n def loadFromNames(self, *names): ...\n def _isTestSuite(self, mdl, obj): ...\n def loadFromModule(self, module, names=None): ...\n def loadTree(self, name=None): ...\n\n suiteClass = TestSuite\n", "repository": "tadek-project/tadek-common", "test_name": "testLoadFromNames", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002559.py"} {"focal_file": "tadek/engine/testdefs.py", "focal_class": null, "focal_method": "result", "tests": "import unittest\n\nclass Test_result(unittest.TestCase):\n def testStepTestResult(self):\n st = step()\n self.failUnless(isinstance(st, TestStep))\n result = st.result(id=1)\n self.failUnless(isinstance(result, TestStepResult))\n self.failUnlessEqual(result.status, STATUS_NO_RUN)\n devres = result.device(TestDevice())\n self.failUnless(isinstance(devres, DeviceExecResult))\n self.failUnlessEqual(devres.status, STATUS_NO_RUN)\n self.failIf(devres.date)\n self.failIf(devres.time)\n\n def testCaseTestResult(self):\n device = TestDevice()\n result = case.result(id='case')\n self.failUnless(isinstance(result, TestCaseResult))\n self.failUnlessEqual(result.status, STATUS_NO_RUN)\n devres = result.device(device)\n self.failUnless(isinstance(devres, DeviceExecResult))\n self.failUnlessEqual(devres.status, STATUS_NO_RUN)\n self.failIf(devres.date)\n self.failIf(devres.time)\n\n def testSuiteTestResult(self):\n suite = SimpleSuite()\n self.failUnless(isinstance(suite, TestSuite))\n result = suite.result()\n self.failUnless(isinstance(result, TestSuiteResult))\n self.failUnlessEqual(result.status, STATUS_NO_RUN)\n devres = result.device(TestDevice())\n self.failUnless(isinstance(devres, DeviceExecResult))\n self.failUnlessEqual(devres.status, STATUS_NO_RUN)\n self.failIf(devres.date)\n self.failIf(devres.time)\n", "method_code": " def result(self, parent=None, **kwargs):\n \"\"\"\n Returns a test execution result for the test.\n \"\"\"\n if self.resultClass is None:\n raise NotImplementedError\n return self.resultClass(attrs=self.attrs.copy(), parent=parent, **kwargs)\n ", "context": "class TestBase():\n def result(self, parent=None, **kwargs): ...\n def __init__(self, **attrs): ...\n def count(self): ...\n\n self.attrs = attrs\n\n resultClass = None\n", "repository": "tadek-project/tadek-common", "test_name": "testStepTestResult", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002560.py"} {"focal_file": "tadek/engine/testdefs.py", "focal_class": null, "focal_method": "run", "tests": "import unittest\n\nclass Test_run(unittest.TestCase):\n def testCaseRun(self):\n\n @testCase()\n def case(test, device):\n test['run'] = True\n test = TestExec()\n case.run(test, TestDevice())\n self.failUnlessEqual(test['run'], True)\n", "method_code": " def run(self, test, device, **args):\n \"\"\"\n Runs the corresponding test step function with the given arguments.\n \"\"\"\n for name, value in args.iteritems():\n args[name] = escape(value, device)\n return self.func(test, device, **args)\n ", "context": "class TestStepPrototype():\n def run(self, test, device, **args): ...\n def __init__(self, func, **attrs): ...\n def __call__(self, **kwargs): ...\n\n self.func = func\n self.attrs = attrs\n", "repository": "tadek-project/tadek-common", "test_name": "testCaseRun", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002561.py"} {"focal_file": "tadek/engine/testexec.py", "focal_class": "TestExec", "focal_method": "abort", "tests": "import unittest\n\nclass Test_TestExec_abort(unittest.TestCase):\n def testAbortExec(self):\n test = TestExec()\n try:\n test.abort(False, 'Abort test')\n except TestAbortError:\n pass\n except:\n self.failIf(True)\n else:\n self.failIf(True)\n\n def testPassAbortExec(self):\n test = TestExec()\n try:\n test.abort(True, 'Abort test')\n except:\n self.failIf(True)\n", "method_code": " def abort(self, expr, msg):\n \"\"\"\n Aborts the test with the given message unless the expression is true.\n It aborts an execution of this test and all its ancestors.\n \"\"\"\n self._assert(expr, msg, TestAbortError)\n ", "context": "class TestExec():\n def abort(self, expr, msg): ...\n def __init__(self, context=None): ...\n def __contains__(self, name): ...\n def __getitem__(self, name): ...\n def __setitem__(self, name, value): ...\n def _assert(self, expr, msg, etype): ...\n def abortIf(self, expr, msg): ...\n def fail(self, expr, msg): ...\n def failIf(self, expr, msg): ...\n def failThis(self, expr, msg): ...\n def failThisIf(self, expr, msg): ...\n def child(self): ...\n\n self._context = context or {}\n", "repository": "tadek-project/tadek-common", "test_name": "testAbortExec", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002562.py"} {"focal_file": "tadek/engine/testexec.py", "focal_class": "TestExec", "focal_method": "abortIf", "tests": "import unittest\n\nclass Test_TestExec_abortIf(unittest.TestCase):\n def testAbortIfExec(self):\n test = TestExec()\n try:\n test.abortIf(True, 'Abort test')\n except TestAbortError:\n pass\n except:\n self.failIf(True)\n else:\n self.failIf(True)\n\n def testPassAbortIfExec(self):\n test = TestExec()\n try:\n test.abortIf(False, 'Abort test')\n except:\n self.failIf(True)\n", "method_code": " def abortIf(self, expr, msg):\n \"\"\"\n Aborts the test with the given message if the expression is true.\n It aborts an execution of this test and all its ancestors.\n \"\"\"\n self._assert(not expr, msg, TestAbortError)\n ", "context": "class TestExec():\n def abortIf(self, expr, msg): ...\n def __init__(self, context=None): ...\n def __contains__(self, name): ...\n def __getitem__(self, name): ...\n def __setitem__(self, name, value): ...\n def _assert(self, expr, msg, etype): ...\n def abort(self, expr, msg): ...\n def fail(self, expr, msg): ...\n def failIf(self, expr, msg): ...\n def failThis(self, expr, msg): ...\n def failThisIf(self, expr, msg): ...\n def child(self): ...\n\n self._context = context or {}\n", "repository": "tadek-project/tadek-common", "test_name": "testAbortIfExec", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002563.py"} {"focal_file": "tadek/engine/testexec.py", "focal_class": "TestExec", "focal_method": "failIf", "tests": "import unittest\n\nclass Test_TestExec_failIf(unittest.TestCase):\n def testFailIfExec(self):\n test = TestExec()\n try:\n test.failIf(True, 'Fail test')\n except TestFailError:\n pass\n except:\n self.failIf(True)\n else:\n self.failIf(True)\n\n def testPassFailIfExec(self):\n test = TestExec()\n try:\n test.failIf(False, 'Fail test')\n except:\n self.failIf(True)\n", "method_code": " def failIf(self, expr, msg):\n \"\"\"\n Fails the test with the given message if the expression is true.\n It fails an execution of this test and its direct parent.\n \"\"\"\n self._assert(not expr, msg, TestFailError)\n ", "context": "class TestExec():\n def failIf(self, expr, msg): ...\n def __init__(self, context=None): ...\n def __contains__(self, name): ...\n def __getitem__(self, name): ...\n def __setitem__(self, name, value): ...\n def _assert(self, expr, msg, etype): ...\n def abort(self, expr, msg): ...\n def abortIf(self, expr, msg): ...\n def fail(self, expr, msg): ...\n def failThis(self, expr, msg): ...\n def failThisIf(self, expr, msg): ...\n def child(self): ...\n\n self._context = context or {}\n", "repository": "tadek-project/tadek-common", "test_name": "testFailIfExec", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002564.py"} {"focal_file": "tadek/engine/testexec.py", "focal_class": "TestExec", "focal_method": "failThis", "tests": "import unittest\n\nclass Test_TestExec_failThis(unittest.TestCase):\n def testFailThisExec(self):\n test = TestExec()\n try:\n test.failThis(False, 'Fail this test')\n except TestFailThisError:\n pass\n except:\n self.failIf(True)\n else:\n self.failIf(True)\n\n def testPassFailThisExec(self):\n test = TestExec()\n try:\n test.failThis(True, 'Fail this test')\n except:\n self.failIf(True)\n", "method_code": " def failThis(self, expr, msg):\n \"\"\"\n Fails the test with the given message unless the expression is true.\n It fails only an execution of this test, it does not affect its parent.\n \"\"\"\n self._assert(expr, msg, TestFailThisError)\n ", "context": "class TestExec():\n def failThis(self, expr, msg): ...\n def __init__(self, context=None): ...\n def __contains__(self, name): ...\n def __getitem__(self, name): ...\n def __setitem__(self, name, value): ...\n def _assert(self, expr, msg, etype): ...\n def abort(self, expr, msg): ...\n def abortIf(self, expr, msg): ...\n def fail(self, expr, msg): ...\n def failIf(self, expr, msg): ...\n def failThisIf(self, expr, msg): ...\n def child(self): ...\n\n self._context = context or {}\n", "repository": "tadek-project/tadek-common", "test_name": "testFailThisExec", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002565.py"} {"focal_file": "tadek/engine/testexec.py", "focal_class": "TestExec", "focal_method": "failThisIf", "tests": "import unittest\n\nclass Test_TestExec_failThisIf(unittest.TestCase):\n def testFailThisIfExec(self):\n test = TestExec()\n try:\n test.failThisIf(True, 'Fail this test')\n except TestFailThisError:\n pass\n except:\n self.failIf(True)\n else:\n self.failIf(True)\n\n def testPassFailThisIfExec(self):\n test = TestExec()\n try:\n test.failThisIf(False, 'Fail this test')\n except:\n self.failIf(True)\n", "method_code": " def failThisIf(self, expr, msg):\n \"\"\"\n Fails the test with the given message if the expression is true.\n It fails only an execution of this test, it does not affect its parent.\n \"\"\"\n self._assert(not expr, msg, TestFailThisError)\n ", "context": "class TestExec():\n def failThisIf(self, expr, msg): ...\n def __init__(self, context=None): ...\n def __contains__(self, name): ...\n def __getitem__(self, name): ...\n def __setitem__(self, name, value): ...\n def _assert(self, expr, msg, etype): ...\n def abort(self, expr, msg): ...\n def abortIf(self, expr, msg): ...\n def fail(self, expr, msg): ...\n def failIf(self, expr, msg): ...\n def failThis(self, expr, msg): ...\n def child(self): ...\n\n self._context = context or {}\n", "repository": "tadek-project/tadek-common", "test_name": "testFailThisIfExec", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002566.py"} {"focal_file": "tadek/engine/channels/streamchannel.py", "focal_class": "tadek.engine.channels.streamchannel.StreamChannel", "focal_method": "startTest", "tests": "import unittest\n\nclass Test_tadek_engine_channels_streamchannel_StreamChannel_startTest(unittest.TestCase):\n def testStartTestStep(self):\n output = '%s -------------------- START --------------------\\n\\t%s: [%s] %s\\n\\tTest step ID: %s\\n\\tFunction: %s(%s)\\n\\tPath: %s\\n\\t\\t%s\\n'\n result = helpers.stepResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult()\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=True)\n output %= (helpers.deviceDateTime(device), device.name, _deviceAddress(device), device.description, result.id, result.func, _stepArgs(result), result.path, _resultAttrs(result))\n channel.start(None)\n channel.startTest(result, device)\n channel.stop()\n helpers.assertOutput(self, output, string)\n\n def testStartStopTestStep(self):\n output = '%s -------------------- START --------------------\\n\\t%s: [%s] %s\\n\\tTest step ID: %s\\n\\tFunction: %s(%s)\\n\\tPath: %s\\n\\t\\t%s\\n%s -------------------- STOP -------------------- [%s]\\n\\t%s: [%s] %s\\n\\tTest step ID: %s\\n\\tFunction: %s(%s)\\n\\tPath: %s\\n\\t\\t%s\\n'\n result = helpers.stepResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult()\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=True)\n channel.start(None)\n channel.startTest(result, device)\n device.time = 5.1\n device.status = testexec.STATUS_FAILED\n channel.stopTest(result, device)\n channel.stop()\n output %= (helpers.deviceDateTime(device), device.name, _deviceAddress(device), device.description, result.id, result.func, _stepArgs(result), result.path, _resultAttrs(result), helpers.deviceDateTime(device, True), device.status, device.name, _deviceAddress(device), device.description, result.id, result.func, _stepArgs(result), result.path, _resultAttrs(result))\n helpers.assertOutput(self, output, string)\n\n def testStartTestCase(self):\n output = '%s -------------------- START --------------------\\n\\t%s: [%s] %s\\n\\tTest case ID: %s\\n\\tPath: %s\\n\\t\\t%s\\n'\n result = helpers.caseResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult()\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=True)\n output %= (helpers.deviceDateTime(device), device.name, _deviceAddress(device), device.description, result.id, result.path, _resultAttrs(result))\n channel.start(None)\n channel.startTest(result, device)\n channel.stop()\n helpers.assertOutput(self, output, string)\n\n def testStartStopTestCase(self):\n output = '%s -------------------- START --------------------\\n\\t%s: [%s] %s\\n\\tTest case ID: %s\\n\\tPath: %s\\n\\t\\t%s\\n%s -------------------- STOP -------------------- [%s]\\n\\t%s: [%s] %s\\n\\tTest case ID: %s\\n\\tPath: %s\\n\\t\\t%s\\n'\n result = helpers.caseResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult()\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=True)\n channel.start(None)\n channel.startTest(result, device)\n device.time = 6.5\n device.status = testexec.STATUS_ERROR\n channel.stopTest(result, device)\n channel.stop()\n output %= (helpers.deviceDateTime(device), device.name, _deviceAddress(device), device.description, result.id, result.path, _resultAttrs(result), helpers.deviceDateTime(device, True), device.status, device.name, _deviceAddress(device), device.description, result.id, result.path, _resultAttrs(result))\n helpers.assertOutput(self, output, string)\n\n def testStartTestSuite(self):\n output = '%s -------------------- START --------------------\\n\\t%s: [%s] %s\\n\\tTest suite ID: %s\\n\\tPath: %s\\n\\t\\t%s\\n'\n result = helpers.suiteResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult()\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=True)\n output %= (helpers.deviceDateTime(device), device.name, _deviceAddress(device), device.description, result.id, result.path, _resultAttrs(result))\n channel.start(None)\n channel.startTest(result, device)\n channel.stop()\n helpers.assertOutput(self, output, string)\n\n def testStartStopTestSuite(self):\n output = '%s -------------------- START --------------------\\n\\t%s: [%s] %s\\n\\tTest suite ID: %s\\n\\tPath: %s\\n\\t\\t%s\\n%s -------------------- STOP -------------------- [%s]\\n\\t%s: [%s] %s\\n\\tTest suite ID: %s\\n\\tPath: %s\\n\\t\\t%s\\n'\n result = helpers.suiteResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult()\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=True)\n channel.start(None)\n channel.startTest(result, device)\n device.time = 4.3\n device.status = testexec.STATUS_PASSED\n channel.stopTest(result, device)\n channel.stop()\n output %= (helpers.deviceDateTime(device), device.name, _deviceAddress(device), device.description, result.id, result.path, _resultAttrs(result), helpers.deviceDateTime(device, True), device.status, device.name, _deviceAddress(device), device.description, result.id, result.path, _resultAttrs(result))\n helpers.assertOutput(self, output, string)\n\n def testStartTestErrors(self):\n output = '%s [%s] START %s\\n%s [%s] START %s\\n%s [%s] START %s\\n'\n string = cStringIO.StringIO()\n suites, cases, steps = helpers.structResult(1, 1, 1)\n suite, case, step = (suites[0], cases[0], steps[0])\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=False)\n self.device.errors = self.errors\n channel.start(None)\n channel.startTest(suite, self.device)\n channel.startTest(case, self.device)\n channel.startTest(step, self.device)\n channel.stop()\n output %= (_deviceDateTime(self.device)[1], self.device.name, suite.id, _deviceDateTime(self.device)[1], self.device.name, case.id, _deviceDateTime(self.device)[1], self.device.name, step.id)\n helpers.assertOutput(self, output, string)\n\n def testStartTestCores(self):\n output = '%s [%s] START %s\\n%s [%s] START %s\\n%s [%s] START %s\\n'\n string = cStringIO.StringIO()\n suites, cases, steps = helpers.structResult(1, 1, 1)\n suite, case, step = (suites[0], cases[0], steps[0])\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=False)\n self.device.cores = self.cores\n channel.start(None)\n channel.startTest(suite, self.device)\n channel.startTest(case, self.device)\n channel.startTest(step, self.device)\n channel.stop()\n output %= (_deviceDateTime(self.device)[1], self.device.name, suite.id, _deviceDateTime(self.device)[1], self.device.name, case.id, _deviceDateTime(self.device)[1], self.device.name, step.id)\n helpers.assertOutput(self, output, string)\n\n def testStartStopTestCores(self):\n output = '%(deviceTime)s [%(deviceName)s] START %(suiteId)s\\n%(deviceTime)s [%(deviceName)s] START %(caseId)s\\n%(deviceTime)s [%(deviceName)s] START %(stepId)s\\n%(deviceTimeEnd)s [%(deviceName)s] STOP %(stepId)s [%(deviceStatus)s]\\n\\tCore dump: %(core1Path)s\\n\\tCore dump: %(core2Path)s\\n\\tCore dump: %(core3Path)s\\n%(deviceTimeEnd)s [%(deviceName)s] STOP %(caseId)s [%(deviceStatus)s]\\n\\tCore dump: %(core1Path)s\\n\\tCore dump: %(core2Path)s\\n%(deviceTimeEnd)s [%(deviceName)s] STOP %(suiteId)s [%(deviceStatus)s]\\n\\tCore dump: %(core1Path)s\\n'\n string = cStringIO.StringIO()\n suites, cases, steps = helpers.structResult(1, 1, 1)\n suite, case, step = (suites[0], cases[0], steps[0])\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=False)\n channel.start(None)\n channel.startTest(suite, self.device)\n channel.startTest(case, self.device)\n channel.startTest(step, self.device)\n self.device.time = 3.75\n self.device.cores = self.cores\n channel.stopTest(step, self.device)\n self.device.cores = self.cores[:2]\n channel.stopTest(case, self.device)\n self.device.cores = self.cores[:1]\n channel.stopTest(suite, self.device)\n channel.stop()\n output %= {'suiteId': suite.id, 'caseId': case.id, 'stepId': step.id, 'deviceName': self.device.name, 'deviceStatus': self.device.status, 'deviceTime': _deviceDateTime(self.device)[1], 'deviceTimeEnd': _deviceDateTime(self.device, True)[1], 'core1Path': self.cores[0].path, 'core2Path': self.cores[1].path, 'core3Path': self.cores[2].path}\n helpers.assertOutput(self, output, string)\n", "method_code": " def startTest(self, result, device):\n \"\"\"\n Processes a test start execution for the stream channel.\n \"\"\"\n TestResultChannel.startTest(self, result, device)\n formatters = self._verboseFormats if self.isVerbose() else self._simpleFormats\n self.write(self._format(result, formatters['start'], formatters, self._deviceAttrs(device)))\n self.write(self._formatResult(result, formatters, self._deviceAttrs(device)))\n ", "context": "class StreamChannel(TestResultChannel):\n def startTest(self, result, device): ...\n def __init__(self, name, stream=None, encoding=None, **params): ...\n def _basicAttrs(self, device): ...\n def _deviceAttrs(self, device): ...\n def _format(self, source, formatter, formatters, kwargs): ...\n def _formatResult(self, result, formatters, attrs): ...\n def stopTest(self, result, device): ...\n def write(self, data): ...\n\n self._stream = stream or sys.stderr\n self._encoding = encoding or getattr(self._stream, 'encoding', None)\n\n SEPARATOR = 20 * u'-'\n _conversionTypes = {}\n _simpleFormats = {'start': u'%(date)T [%(device.name)U] START %(id)s\\n', 'step': u'', 'case': u'', 'suite': u'', 'stop': u'%(date)T [%(device.name)U] STOP %(id)s [%(device.status)s]\\n', 'cores': (u'Core dump: %(path)s', u'\\n\\t', u'\\t', u'\\n'), 'errors': (u'%s', u'\\n', u'', u'\\n')}\n _verboseFormats = {'start': u'%(date)D %(separator)s START %(separator)s\\n\\t%(device.name)U: [%(device.address)s] %(device.description)U\\n', 'step': u'\\tTest step ID: %(id)s\\n\\tFunction: %(func)s%(args)s\\n\\tPath: %(path)s%(attrs)s\\n', 'case': u'\\tTest case ID: %(id)s\\n\\tPath: %(path)s%(attrs)s\\n', 'suite': u'\\tTest suite ID: %(id)s\\n\\tPath: %(path)s%(attrs)s\\n', 'attrs': (u'%(' + MAPPING_KEY_SYMBOL + u')s: %(' + MAPPING_VALUE_SYMBOL + u')r', u'\\n\\t\\t', u'\\n\\t\\t', u''), 'args': (u'%(' + MAPPING_KEY_SYMBOL + u')s=%(' + MAPPING_VALUE_SYMBOL + u')r', u', ', u'(', u')'), 'stop': u'%(date)D %(separator)s STOP %(separator)s [%(device.status)s]\\n\\t%(device.name)U: [%(device.address)s] %(device.description)U\\n', 'cores': (u'Core dump: %(mtime)D [%(path)s] %(size)S', u'\\n\\t', u'\\t', u'\\n'), 'errors': (u'%s', u'\\n', u'', u'\\n')}\n", "repository": "tadek-project/tadek-common", "test_name": "testStartTestStep", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002567.py"} {"focal_file": "tadek/engine/channels/streamchannel.py", "focal_class": "tadek.engine.channels.streamchannel.StreamChannel", "focal_method": "stopTest", "tests": "import unittest\n\nclass Test_tadek_engine_channels_streamchannel_StreamChannel_stopTest(unittest.TestCase):\n def testStopTestStep(self):\n output = '%s [%s] STOP %s [%s]\\n'\n result = helpers.stepResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult(time=2.6, status=testexec.STATUS_PASSED)\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=False)\n channel.start(None)\n self.failIf(channel.isActive())\n channel.stopTest(result, device)\n self.failUnless(channel.isActive())\n channel.stop()\n output %= (_deviceDateTime(device, True)[1], device.name, result.id, device.status)\n helpers.assertOutput(self, output, string)\n\n def testStopTestCase(self):\n output = '%s [%s] STOP %s [%s]\\n'\n result = helpers.caseResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult(time=5.6, status=testexec.STATUS_PASSED)\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=False)\n channel.start(None)\n self.failIf(channel.isActive())\n channel.stopTest(result, device)\n self.failUnless(channel.isActive())\n channel.stop()\n output %= (_deviceDateTime(device, True)[1], device.name, result.id, device.status)\n helpers.assertOutput(self, output, string)\n\n def testStopTestSuite(self):\n output = '%s [%s] STOP %s [%s]\\n'\n result = helpers.suiteResult()\n string = cStringIO.StringIO()\n device = helpers.deviceResult(time=3.4, status=testexec.STATUS_FAILED)\n channel = streamchannel.StreamChannel('Test', stream=string, verbose=False)\n channel.start(None)\n self.failIf(channel.isActive())\n channel.stopTest(result, device)\n self.failUnless(channel.isActive())\n channel.stop()\n output %= (_deviceDateTime(device, True)[1], device.name, result.id, device.status)\n helpers.assertOutput(self, output, string)\n", "method_code": " def stopTest(self, result, device):\n \"\"\"\n Processes a test stop execution for the stream channel.\n \"\"\"\n TestResultChannel.stopTest(self, result, device)\n formatters = self._verboseFormats if self.isVerbose() else self._simpleFormats\n self.write(self._format(result, formatters['stop'], formatters, self._deviceAttrs(device)))\n self.write(self._formatResult(result, formatters, self._deviceAttrs(device)))\n self.write(self._format(device.cores, formatters['cores'], formatters, self._basicAttrs(device)))\n self.write(self._format(device.errors, formatters['errors'], formatters, self._basicAttrs(device)))\n ", "context": "class StreamChannel(TestResultChannel):\n def stopTest(self, result, device): ...\n def __init__(self, name, stream=None, encoding=None, **params): ...\n def _basicAttrs(self, device): ...\n def _deviceAttrs(self, device): ...\n def _format(self, source, formatter, formatters, kwargs): ...\n def _formatResult(self, result, formatters, attrs): ...\n def startTest(self, result, device): ...\n def write(self, data): ...\n\n self._stream = stream or sys.stderr\n self._encoding = encoding or getattr(self._stream, 'encoding', None)\n\n SEPARATOR = 20 * u'-'\n _conversionTypes = {}\n _simpleFormats = {'start': u'%(date)T [%(device.name)U] START %(id)s\\n', 'step': u'', 'case': u'', 'suite': u'', 'stop': u'%(date)T [%(device.name)U] STOP %(id)s [%(device.status)s]\\n', 'cores': (u'Core dump: %(path)s', u'\\n\\t', u'\\t', u'\\n'), 'errors': (u'%s', u'\\n', u'', u'\\n')}\n _verboseFormats = {'start': u'%(date)D %(separator)s START %(separator)s\\n\\t%(device.name)U: [%(device.address)s] %(device.description)U\\n', 'step': u'\\tTest step ID: %(id)s\\n\\tFunction: %(func)s%(args)s\\n\\tPath: %(path)s%(attrs)s\\n', 'case': u'\\tTest case ID: %(id)s\\n\\tPath: %(path)s%(attrs)s\\n', 'suite': u'\\tTest suite ID: %(id)s\\n\\tPath: %(path)s%(attrs)s\\n', 'attrs': (u'%(' + MAPPING_KEY_SYMBOL + u')s: %(' + MAPPING_VALUE_SYMBOL + u')r', u'\\n\\t\\t', u'\\n\\t\\t', u''), 'args': (u'%(' + MAPPING_KEY_SYMBOL + u')s=%(' + MAPPING_VALUE_SYMBOL + u')r', u', ', u'(', u')'), 'stop': u'%(date)D %(separator)s STOP %(separator)s [%(device.status)s]\\n\\t%(device.name)U: [%(device.address)s] %(device.description)U\\n', 'cores': (u'Core dump: %(mtime)D [%(path)s] %(size)S', u'\\n\\t', u'\\t', u'\\n'), 'errors': (u'%s', u'\\n', u'', u'\\n')}\n", "repository": "tadek-project/tadek-common", "test_name": "testStopTestStep", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002568.py"} {"focal_file": "tadek/engine/channels/summarychannel.py", "focal_class": "SummaryChannel", "focal_method": "startTest", "tests": "import unittest\n\nclass Test_SummaryChannel_startTest(unittest.TestCase):\n def testStartStop3Tests(self):\n channel = SummaryChannel('summary')\n channel.start(self.suiteResult)\n channel.startTest(self.caseResult, self.deviceResult)\n channel.stopTest(self.caseResult, self.deviceResult)\n channel.startTest(self.caseResult1, self.deviceResult1)\n channel.stopTest(self.caseResult1, self.deviceResult1)\n channel.startTest(self.caseResult2, self.deviceResult)\n channel.stopTest(self.caseResult2, self.deviceResult)\n channel.stop()\n summary = channel.getSummary()\n self.assertEqual(3, summary[COUNTER_N_TESTS])\n self.assertEqual(3, summary[COUNTER_TESTS_RUN])\n self.assertEqual(2, summary[STATUS_PASSED])\n self.assertEqual(1, summary[STATUS_FAILED])\n self.assertEqual(0, summary[STATUS_ERROR])\n self.assertEqual(0, summary[STATUS_NOT_COMPLETED])\n self.assertEqual(0, summary[COUNTER_CORE_DUMPS])\n", "method_code": " def startTest(self, result, device):\n \"\"\"\n Processes a test start execution for the summary channel.\n \"\"\"\n TestResultChannel.startTest(self, result, device)\n if isinstance(result, TestCaseResult):\n self._counters[STATUS_NOT_COMPLETED] += 1\n self._counters[COUNTER_TESTS_RUN] += 1\n ", "context": "class SummaryChannel(TestResultChannel):\n def startTest(self, result, device): ...\n def __init__(self, name, enabled=True, verbose=False, **params): ...\n def start(self, result): ...\n def stopTest(self, result, device): ...\n def getSummary(self): ...\n\n self._counters = {}\n", "repository": "tadek-project/tadek-common", "test_name": "testStartStop3Tests", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002569.py"} {"focal_file": "src/konfiger.py", "focal_class": null, "focal_method": "lazy_size", "tests": "import unittest\n\nclass Test_lazy_size(unittest.TestCase):\n def test_lazy_size(self):\n kon = from_string('One=111,Two=222,Three=333', True, '=', ',')\n self.assertEqual(kon.lazy_size(), 0)\n self.assertNotEqual(kon.lazy_size(), 3)\n self.assertEqual(kon.get('One'), '111')\n self.assertEqual(kon.lazy_size(), 1)\n self.assertEqual(kon.get('Two'), '222')\n self.assertEqual(kon.lazy_size(), 2)\n self.assertEqual(kon.get('Three'), '333')\n self.assertEqual(kon.lazy_size(), 3)\n self.assertEqual(kon.lazy_size(), len(kon))\n\n def test_remove_entry_and_lazy_size(self):\n kon = from_string('One=111,Two=222,Three=333', True, '=', ',')\n self.assertEqual(kon.lazy_size(), 0)\n self.assertNotEqual(kon.lazy_size(), 3)\n self.assertNotEqual(kon.get('Two'), None)\n self.assertEqual(kon.lazy_size(), 2)\n self.assertEqual(kon.remove('Two'), '222')\n self.assertNotEqual(kon.lazy_size(), 2)\n self.assertEqual(kon.lazy_size(), 1)\n self.assertEqual(kon.get('Two'), None)\n self.assertEqual(kon.lazy_size(), 2)\n self.assertEqual(kon.remove(0), '111')\n self.assertEqual(kon.lazy_size(), 1)\n self.assertEqual(kon.get('Three'), '333')\n self.assertEqual(kon.lazy_size(), 1)\n", "method_code": " def lazy_size(self):\n return len(self.konfiger_objects)\n ", "context": "class Konfiger():\n def lazy_size(self): ...\n def __init__(self, stream, lazy_load): ...\n def put(self, key, value): ...\n def put_string(self, key, value): ...\n def put_boolean(self, key, value): ...\n def put_long(self, key, value): ...\n def put_int(self, key, value): ...\n def put_float(self, key, value): ...\n def put_double(self, key, value): ...\n def put_comment(self, the_comment): ...\n def get(self, key, default_value=None): ...\n def get_string(self, key, default_value=''): ...\n def get_boolean(self, key, default_value=False): ...\n def get_long(self, key, default_value=0): ...\n def get_int(self, key, default_value=0): ...\n def get_float(self, key, default_value=0.0): ...\n def get_double(self, key, default_value=0.0): ...\n def shift_cache(self, key, value): ...\n def enable_cache(self, enable_cache_): ...\n def contains(self, key): ...\n def keys(self): ...\n def values(self): ...\n def entries(self): ...\n def clear(self): ...\n def remove(self, key_index): ...\n def update_at(self, index, value): ...\n def __len__(self): ...\n def is_empty(self): ...\n def get_seperator(self): ...\n def set_seperator(self, separator): ...\n def get_separator(self): ...\n def set_separator(self, separator): ...\n def get_delimeter(self): ...\n def set_delimeter(self, delimiter): ...\n def get_delimiter(self): ...\n def set_delimiter(self, delimiter): ...\n def is_case_sensitive(self): ...\n def set_case_sensitivity(self, case_sensitive): ...\n def hash_code(self): ...\n def __str__(self): ...\n def lazy_loader(self): ...\n def save(self, file_path=None): ...\n def append_string(self, raw_string, delimiter=None, separator=None): ...\n def append_file(self, file_path, delimiter=None, separator=None): ...\n def resolve(self, obj): ...\n def dissolve(self, obj): ...\n def attach(self, obj): ...\n def detach(self): ...\n\n self.hashcode = 0\n self.stream = stream\n self.loading_ends = False\n self.lazy_load = lazy_load\n self.konfiger_objects = {}\n self.delimiter = stream.delimiter\n self.separator = stream.separator\n self.case_sensitive = True\n self.changes_occur = True\n self.string_value = ''\n self.read_index = 0\n self.file_path = None\n self.attached_resolve_obj = None\n self.enable_cache_ = True\n self.prev_cache_object = {'ckey': '', 'cvalue': None}\n self.current_cache_object = {'ckey': '', 'cvalue': None}\n", "repository": "konfiger/konfiger-python", "test_name": "test_lazy_size", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002570.py"} {"focal_file": "src/konfiger.py", "focal_class": null, "focal_method": "save", "tests": "import unittest\n\nclass Test_save(unittest.TestCase):\n def test_escaping_and_unescaping_entries_and_save(self):\n ks = file_stream('test/test.config.ini')\n ks1 = file_stream('test/test.txt', ':', ',')\n kon = from_stream(ks)\n kon1 = from_stream(ks1)\n self.assertEqual(kon.get('Hobby'), \"i don't know\")\n self.assertEqual(kon1.get('Hobby'), kon.get('Hobby'))\n self.assertEqual(kon1.get('Hobby'), \"i don't know\")\n kon.save('test/test.config.ini')\n new_ks = file_stream('test/test.config.ini')\n new_kon = from_stream(new_ks, True)\n new_kon1 = from_file('test/test.txt', True, ':', ',')\n self.assertEqual(str(kon), str(kon))\n self.assertEqual(str(kon1), str(kon1))\n", "method_code": " def save(self, file_path=None):\n if self.file_path is None and file_path is None:\n raise TypeError('io.github.thecarisma.Konfiger: The entries cannot be saved you need to specify the file_path as parameter or load Konfiger from a file')\n if file_path is None:\n file_path = self.file_path\n with open(file_path, 'w') as file:\n file.write(self.__str__())\n ", "context": "class Konfiger():\n def save(self, file_path=None): ...\n def __init__(self, stream, lazy_load): ...\n def put(self, key, value): ...\n def put_string(self, key, value): ...\n def put_boolean(self, key, value): ...\n def put_long(self, key, value): ...\n def put_int(self, key, value): ...\n def put_float(self, key, value): ...\n def put_double(self, key, value): ...\n def put_comment(self, the_comment): ...\n def get(self, key, default_value=None): ...\n def get_string(self, key, default_value=''): ...\n def get_boolean(self, key, default_value=False): ...\n def get_long(self, key, default_value=0): ...\n def get_int(self, key, default_value=0): ...\n def get_float(self, key, default_value=0.0): ...\n def get_double(self, key, default_value=0.0): ...\n def shift_cache(self, key, value): ...\n def enable_cache(self, enable_cache_): ...\n def contains(self, key): ...\n def keys(self): ...\n def values(self): ...\n def entries(self): ...\n def clear(self): ...\n def remove(self, key_index): ...\n def update_at(self, index, value): ...\n def __len__(self): ...\n def lazy_size(self): ...\n def is_empty(self): ...\n def get_seperator(self): ...\n def set_seperator(self, separator): ...\n def get_separator(self): ...\n def set_separator(self, separator): ...\n def get_delimeter(self): ...\n def set_delimeter(self, delimiter): ...\n def get_delimiter(self): ...\n def set_delimiter(self, delimiter): ...\n def is_case_sensitive(self): ...\n def set_case_sensitivity(self, case_sensitive): ...\n def hash_code(self): ...\n def __str__(self): ...\n def lazy_loader(self): ...\n def append_string(self, raw_string, delimiter=None, separator=None): ...\n def append_file(self, file_path, delimiter=None, separator=None): ...\n def resolve(self, obj): ...\n def dissolve(self, obj): ...\n def attach(self, obj): ...\n def detach(self): ...\n\n self.hashcode = 0\n self.stream = stream\n self.loading_ends = False\n self.lazy_load = lazy_load\n self.konfiger_objects = {}\n self.delimiter = stream.delimiter\n self.separator = stream.separator\n self.case_sensitive = True\n self.changes_occur = True\n self.string_value = ''\n self.read_index = 0\n self.file_path = None\n self.attached_resolve_obj = None\n self.enable_cache_ = True\n self.prev_cache_object = {'ckey': '', 'cvalue': None}\n self.current_cache_object = {'ckey': '', 'cvalue': None}\n", "repository": "konfiger/konfiger-python", "test_name": "test_escaping_and_unescaping_entries_and_save", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], "pynose_source_file": "test_002571.py"} {"focal_file": "src/konfiger.py", "focal_class": null, "focal_method": "set_case_sensitivity", "tests": "import unittest\n\nclass Test_set_case_sensitivity(unittest.TestCase):\n def test_validate_konfiger_entries_with_case_sensitivity(self):\n kon = from_string('\\nString=This is a string\\nNumber=215415245\\n', False)\n kon.set_case_sensitivity(True)\n self.assertEqual(kon.is_case_sensitive(), True)\n kon.set_case_sensitivity(False)\n self.assertEqual(kon.is_case_sensitive(), False)\n self.assertEqual(kon.get('STRING'), 'This is a string')\n self.assertEqual(kon.get('NUMBER'), '215415245')\n self.assertEqual(kon.get('strING'), 'This is a string')\n self.assertEqual(kon.get('nuMBer'), '215415245')\n self.assertEqual(kon.get('STRiNg'), 'This is a string')\n self.assertEqual(kon.get('nUMbeR'), '215415245')\n self.assertEqual(kon.get('string'), 'This is a string')\n self.assertEqual(kon.get('number'), '215415245')\n", "method_code": " def set_case_sensitivity(self, case_sensitive):\n if not is_bool(case_sensitive):\n raise TypeError('io.github.thecarisma.konfiger: Invalid argument, case_sensitive must be a bool found ' + str(type(case_sensitive)))\n self.case_sensitive = case_sensitive\n ", "context": "class Konfiger():\n def set_case_sensitivity(self, case_sensitive): ...\n def __init__(self, stream, lazy_load): ...\n def put(self, key, value): ...\n def put_string(self, key, value): ...\n def put_boolean(self, key, value): ...\n def put_long(self, key, value): ...\n def put_int(self, key, value): ...\n def put_float(self, key, value): ...\n def put_double(self, key, value): ...\n def put_comment(self, the_comment): ...\n def get(self, key, default_value=None): ...\n def get_string(self, key, default_value=''): ...\n def get_boolean(self, key, default_value=False): ...\n def get_long(self, key, default_value=0): ...\n def get_int(self, key, default_value=0): ...\n def get_float(self, key, default_value=0.0): ...\n def get_double(self, key, default_value=0.0): ...\n def shift_cache(self, key, value): ...\n def enable_cache(self, enable_cache_): ...\n def contains(self, key): ...\n def keys(self): ...\n def values(self): ...\n def entries(self): ...\n def clear(self): ...\n def remove(self, key_index): ...\n def update_at(self, index, value): ...\n def __len__(self): ...\n def lazy_size(self): ...\n def is_empty(self): ...\n def get_seperator(self): ...\n def set_seperator(self, separator): ...\n def get_separator(self): ...\n def set_separator(self, separator): ...\n def get_delimeter(self): ...\n def set_delimeter(self, delimiter): ...\n def get_delimiter(self): ...\n def set_delimiter(self, delimiter): ...\n def is_case_sensitive(self): ...\n def hash_code(self): ...\n def __str__(self): ...\n def lazy_loader(self): ...\n def save(self, file_path=None): ...\n def append_string(self, raw_string, delimiter=None, separator=None): ...\n def append_file(self, file_path, delimiter=None, separator=None): ...\n def resolve(self, obj): ...\n def dissolve(self, obj): ...\n def attach(self, obj): ...\n def detach(self): ...\n\n self.hashcode = 0\n self.stream = stream\n self.loading_ends = False\n self.lazy_load = lazy_load\n self.konfiger_objects = {}\n self.delimiter = stream.delimiter\n self.separator = stream.separator\n self.case_sensitive = True\n self.changes_occur = True\n self.string_value = ''\n self.read_index = 0\n self.file_path = None\n self.attached_resolve_obj = None\n self.enable_cache_ = True\n self.prev_cache_object = {'ckey': '', 'cvalue': None}\n self.current_cache_object = {'ckey': '', 'cvalue': None}\n", "repository": "konfiger/konfiger-python", "test_name": "test_validate_konfiger_entries_with_case_sensitivity", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002572.py"} {"focal_file": "src/html_parser.py", "focal_class": null, "focal_method": "get_links", "tests": "import unittest\n\nclass Test_get_links(unittest.TestCase):\n def test_get_links(self):\n \"\"\"\n Tests get_links method\n \"\"\"\n file_util = FileUtil()\n expected_links = file_util.get_file_contents('links_test_data.txt')\n html_parser = HtmlParser()\n html_test_data = file_util.get_file_contents('html_test_data.html')\n actual_links = html_parser.get_links(html_test_data)\n self.assertEqual(expected_links, actual_links)\n", "method_code": " def get_links(self, html):\n \"\"\"\n Extracts and returns the links in the parameter HTML\n \"\"\"\n links = []\n link_prefixes = ['href=\"', 'src=\"']\n for line in html:\n link_found = True\n while link_found:\n link_found = False\n start = len(line)\n end = len(line)\n for link_prefix in link_prefixes:\n if link_prefix in line:\n link_found = True\n link_prefix_start = line.index(link_prefix) + len(link_prefix)\n link_prefix_end = line.index('\"', link_prefix_start)\n if link_prefix_start < start:\n start = link_prefix_start\n end = link_prefix_end\n if link_found:\n links.append(line[start:end])\n line = line[end:]\n return links\n ", "context": "class HtmlParser():\n def get_links(self, html): ...\n def __init__(self): ...\n def get_same_hostname_urls(self, hostname, links): ...\n def get_assets(self, urls): ...\n def get_web_pages(self, urls): ...\n def get_asset_extensions(self): ...\n\n self.url_util = UrlUtil()\n", "repository": "kitlawes/web-crawler", "test_name": "test_get_links", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002573.py"} {"focal_file": "src/html_parser.py", "focal_class": null, "focal_method": "get_same_hostname_urls", "tests": "import unittest\n\nclass Test_get_same_hostname_urls(unittest.TestCase):\n def test_get_same_hostname_urls(self):\n \"\"\"\n Tests get_same_hostname_urls method\n \"\"\"\n file_util = FileUtil()\n expected_same_hostname_urls = file_util.get_file_contents('same_hostname_urls_test_data.txt')\n html_parser = HtmlParser()\n hostname = 'http://www.domain.com/'\n links = file_util.get_file_contents('links_test_data.txt')\n actual_same_hostname_urls = html_parser.get_same_hostname_urls(hostname, links)\n self.assertEqual(expected_same_hostname_urls, actual_same_hostname_urls)\n", "method_code": " def get_same_hostname_urls(self, hostname, links):\n \"\"\"\n Returns the links from the parameter links that have the same hostname as the parameter hostname\n The links returned are converted into absolute urls.\n \"\"\"\n hostname = self.url_util.normalise_url(hostname)\n same_hostname_urls = []\n for link in links:\n if link.endswith('/'):\n link = link.rstrip('/')\n if link.startswith('https://'):\n link = link.lstrip('https://')\n link = 'http://' + link\n if link.startswith('//'):\n link = 'http:' + link\n if link.startswith(hostname):\n same_hostname_urls.append(link)\n elif not link.startswith('http://'):\n if link != '' and (not link.startswith('/')):\n link = '/' + link\n same_hostname_urls.append(hostname + link)\n return same_hostname_urls\n ", "context": "class HtmlParser():\n def get_same_hostname_urls(self, hostname, links): ...\n def __init__(self): ...\n def get_links(self, html): ...\n def get_assets(self, urls): ...\n def get_web_pages(self, urls): ...\n def get_asset_extensions(self): ...\n\n self.url_util = UrlUtil()\n", "repository": "kitlawes/web-crawler", "test_name": "test_get_same_hostname_urls", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002574.py"} {"focal_file": "src/html_parser.py", "focal_class": null, "focal_method": "get_assets", "tests": "import unittest\n\nclass Test_get_assets(unittest.TestCase):\n def test_get_assets(self):\n \"\"\"\n Tests get_file_contents method\n \"\"\"\n file_util = FileUtil()\n expected_assets = file_util.get_file_contents('assets_test_data.txt')\n html_parser = HtmlParser()\n urls = file_util.get_file_contents('same_hostname_urls_test_data.txt')\n actual_assets = html_parser.get_assets(urls)\n self.assertEqual(expected_assets, actual_assets)\n", "method_code": " def get_assets(self, urls):\n \"\"\"\n Returns the urls from the parameter urls that refer to assets\n \"\"\"\n assets = []\n asset_extensions = self.get_asset_extensions()\n for url in urls:\n for asset_extension in asset_extensions:\n if url.endswith(asset_extension):\n if url not in assets:\n assets.append(url)\n break\n return assets\n ", "context": "class HtmlParser():\n def get_assets(self, urls): ...\n def __init__(self): ...\n def get_links(self, html): ...\n def get_same_hostname_urls(self, hostname, links): ...\n def get_web_pages(self, urls): ...\n def get_asset_extensions(self): ...\n\n self.url_util = UrlUtil()\n", "repository": "kitlawes/web-crawler", "test_name": "test_get_assets", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002575.py"} {"focal_file": "src/html_parser.py", "focal_class": null, "focal_method": "get_web_pages", "tests": "import unittest\n\nclass Test_get_web_pages(unittest.TestCase):\n def test_get_web_pages(self):\n \"\"\"\n Tests get_web_pages method\n \"\"\"\n file_util = FileUtil()\n expected_web_pages = file_util.get_file_contents('web_pages_test_data.txt')\n html_parser = HtmlParser()\n same_hostname_urls = file_util.get_file_contents('same_hostname_urls_test_data.txt')\n actual_web_pages = html_parser.get_web_pages(same_hostname_urls)\n self.assertEqual(expected_web_pages, actual_web_pages)\n", "method_code": " def get_web_pages(self, urls):\n \"\"\"\n Returns the urls from the parameter urls that refer to web pages\n \"\"\"\n web_pages = []\n asset_extensions = self.get_asset_extensions()\n for url in urls:\n is_web_page = True\n for asset_extension in asset_extensions:\n if url.endswith(asset_extension):\n is_web_page = False\n break\n if is_web_page and url not in web_pages:\n web_pages.append(url)\n return web_pages\n ", "context": "class HtmlParser():\n def get_web_pages(self, urls): ...\n def __init__(self): ...\n def get_links(self, html): ...\n def get_same_hostname_urls(self, hostname, links): ...\n def get_assets(self, urls): ...\n def get_asset_extensions(self): ...\n\n self.url_util = UrlUtil()\n", "repository": "kitlawes/web-crawler", "test_name": "test_get_web_pages", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002576.py"} {"focal_file": "src/html_requester.py", "focal_class": null, "focal_method": "get_html", "tests": "import unittest\n\nclass Test_get_html(unittest.TestCase):\n def test_get_html(self):\n \"\"\"\n Tests get_html method\n \"\"\"\n file_util = FileUtil()\n expected_html = file_util.get_file_contents('example.html')\n html_requester = HtmlRequester()\n actual_html = html_requester.get_html('http://example.org')\n self.assertEqual(expected_html, actual_html)\n", "method_code": " def get_html(self, url):\n \"\"\"\n Requests and returns the online HTML for the parameter URL\n \"\"\"\n html = []\n try:\n for line in urllib2.urlopen(url):\n html.append(line.rstrip('\\n'))\n except (urllib2.HTTPError, urllib2.URLError) as err:\n pass\n return html\n ", "context": "class HtmlRequester():\n def get_html(self, url): ...", "repository": "kitlawes/web-crawler", "test_name": "test_get_html", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002577.py"} {"focal_file": "src/url_util.py", "focal_class": null, "focal_method": "get_hostname", "tests": "import unittest\n\nclass Test_get_hostname(unittest.TestCase):\n def test_get_hostname(self):\n \"\"\"\n Tests get_hostname method\n \"\"\"\n url_util = UrlUtil()\n expected_result = 'http://www.domain.com'\n actual_result = url_util.get_hostname('http://www.domain.com')\n self.assertEqual(expected_result, actual_result)\n expected_result = 'http://www.domain.com'\n actual_result = url_util.get_hostname('http://www.domain.com/page')\n self.assertEqual(expected_result, actual_result)\n", "method_code": " def get_hostname(self, url):\n \"\"\"\n Extracts and returns the hostname from the parameter URL\n \"\"\"\n hostname = url\n end = hostname.find('/', len('http://'))\n if end != -1:\n hostname = hostname[:end]\n return hostname\n ", "context": "class UrlUtil():\n def get_hostname(self, url): ...\n def normalise_url(self, url): ...\n", "repository": "kitlawes/web-crawler", "test_name": "test_get_hostname", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002578.py"} {"focal_file": "src/url_util.py", "focal_class": null, "focal_method": "normalise_url", "tests": "import unittest\n\nclass Test_normalise_url(unittest.TestCase):\n def test_normalise_url(self):\n \"\"\"\n Tests normalise_url method\n \"\"\"\n url_util = UrlUtil()\n expected_result = 'http://www.domain.com'\n actual_result = url_util.normalise_url('http://www.domain.com')\n self.assertEqual(expected_result, actual_result)\n expected_result = 'http://www.domain.com/page'\n actual_result = url_util.normalise_url('http://www.domain.com/page')\n self.assertEqual(expected_result, actual_result)\n expected_result = 'http://www.domain.com'\n actual_result = url_util.normalise_url('https://www.domain.com')\n self.assertEqual(expected_result, actual_result)\n expected_result = 'http://www.domain.com'\n actual_result = url_util.normalise_url('www.domain.com')\n self.assertEqual(expected_result, actual_result)\n expected_result = 'http://www.domain.com'\n actual_result = url_util.normalise_url('domain.com')\n self.assertEqual(expected_result, actual_result)\n expected_result = 'http://www.domain.com'\n actual_result = url_util.normalise_url('http://www.domain.com/')\n self.assertEqual(expected_result, actual_result)\n", "method_code": " def normalise_url(self, url):\n \"\"\"\n Returns a normalised version of the parameter URL\n \"\"\"\n if url.startswith('https://'):\n url = url.lstrip('https://')\n if not url.startswith('http://'):\n url = 'http://' + url\n if not url.startswith('http://www.'):\n url = 'http://www.' + url.lstrip('http://')\n if url.endswith('/'):\n url = url.rstrip('/')\n return url\n ", "context": "class UrlUtil():\n def normalise_url(self, url): ...\n def get_hostname(self, url): ...\n", "repository": "kitlawes/web-crawler", "test_name": "test_normalise_url", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002579.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/address.py", "focal_class": null, "focal_method": "from_public_key", "tests": "import unittest\n\nclass Test_from_public_key(unittest.TestCase):\n def test_from_public_key(self):\n public_key = '0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'\n hex_pk = a2b_hex(public_key)\n address = Address.from_public_key(hex_pk)\n self.assertEqual(address.address, '16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM')\n address_hash = '010966776006953D5567439E5E39F86A0D273BEE'\n self.assertEqual(address.hash, a2b_hex(address_hash))\n", "method_code": " def from_public_key(cls, public_key):\n \"\"\"Constructs an Address object from a public key\"\"\"\n return cls(None, public_key, None, 'normal')\n ", "context": "class Address(object):\n @classmethod\n def from_public_key(cls, public_key): ...\n def __init__(self, hash, public_key, address, type): ...\n def __repr__(self): ...\n def from_ripemd160(cls, hash, type='normal'): ...\n def hash(self): ...\n def address(self): ...\n def is_p2sh(self): ...\n\n self._hash = hash\n self.public_key = public_key\n self._address = address\n self.type = type\n", "repository": "0x-genesys/Blockchain-explorer", "test_name": "test_from_public_key", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002580.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/address.py", "focal_class": null, "focal_method": "from_ripemd160", "tests": "import unittest\n\nclass Test_from_ripemd160(unittest.TestCase):\n def test_from_ripemd160(self):\n ripemd160 = '010966776006953D5567439E5E39F86A0D273BEE'\n address = Address.from_ripemd160(a2b_hex(ripemd160))\n self.assertEqual(address.address, '16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM')\n", "method_code": " def from_ripemd160(cls, hash, type='normal'):\n \"\"\"Constructs an Address object from a RIPEMD-160 hash, it may be a\n normal address or a P2SH address, the latter is indicated by setting\n type to 'p2sh'\"\"\"\n return cls(hash, None, None, type)\n ", "context": "class Address(object):\n @classmethod\n def from_ripemd160(cls, hash, type='normal'): ...\n def __init__(self, hash, public_key, address, type): ...\n def __repr__(self): ...\n def from_public_key(cls, public_key): ...\n def hash(self): ...\n def address(self): ...\n def is_p2sh(self): ...\n\n self._hash = hash\n self.public_key = public_key\n self._address = address\n self.type = type\n", "repository": "0x-genesys/Blockchain-explorer", "test_name": "test_from_ripemd160", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002581.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/block.py", "focal_class": null, "focal_method": "from_hex", "tests": "import unittest\n\nclass Test_from_hex(unittest.TestCase):\n def test_from_hex(self):\n block_str = '0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000'\n block_hex = a2b_hex(block_str)\n block = Block.from_hex(block_hex)\n self.assertEqual(1, block.n_transactions)\n block_hash = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'\n self.assertEqual(block_hash, block.hash)\n self.assertEqual(486604799, block.header.bits)\n merkle_root = '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b'\n self.assertEqual(merkle_root, block.header.merkle_root)\n self.assertEqual(2083236893, block.header.nonce)\n self.assertEqual(1, block.header.version)\n self.assertEqual(1, block.header.difficulty)\n self.assertEqual(285, block.size)\n self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp)\n self.assertEqual('0' * 64, block.header.previous_block_hash)\n for tx in block.transactions:\n self.assertEqual(1, tx.version)\n tx_hash = '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b'\n self.assertEqual(tx_hash, tx.hash)\n self.assertEqual(204, tx.size)\n self.assertEqual(0, tx.locktime)\n self.assertEqual(4294967295, tx.inputs[0].transaction_index)\n self.assertEqual(4294967295, tx.inputs[0].sequence_number)\n self.assertTrue('ffff001d' in tx.inputs[0].script.value)\n self.assertEqual('0' * 64, tx.inputs[0].transaction_hash)\n self.assertEqual(50 * 100000000, tx.outputs[0].value)\n", "method_code": " def from_hex(cls, raw_hex):\n \"\"\"Builds a block object from its bytes representation\"\"\"\n return cls(raw_hex)\n ", "context": "class Block(object):\n @classmethod\n def from_hex(cls, raw_hex): ...\n def __init__(self, raw_hex, height=None): ...\n def __repr__(self): ...\n def hash(self): ...\n def n_transactions(self): ...\n def transactions(self): ...\n def header(self): ...\n\n self.hex = raw_hex\n self._hash = None\n self._transactions = None\n self._header = None\n self._n_transactions = None\n self.size = len(raw_hex)\n self.height = height\n", "repository": "0x-genesys/Blockchain-explorer", "test_name": "test_from_hex", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002582.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/script.py", "focal_class": null, "focal_method": "from_hex", "tests": "import unittest\n\nclass Test_from_hex(unittest.TestCase):\n def test_from_hex(self):\n case1 = '6a'\n script = Script.from_hex(a2b_hex(case1))\n self.assertEqual('OP_RETURN', script.value)\n", "method_code": " def from_hex(cls, hex_):\n return cls(hex_)\n ", "context": "class Script(object):\n @classmethod\n def from_hex(cls, hex_): ...\n def __init__(self, raw_hex): ...\n def __repr__(self): ...\n def script(self): ...\n def operations(self): ...\n def value(self): ...\n def is_return(self): ...\n def is_p2sh(self): ...\n def is_pubkey(self): ...\n def is_pubkeyhash(self): ...\n def is_multisig(self): ...\n def is_unknown(self): ...\n\n self.hex = raw_hex\n self._script = None\n self._type = None\n self._value = None\n self._operations = None\n self._addresses = None\n", "repository": "0x-genesys/Blockchain-explorer", "test_name": "test_from_hex", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002583.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/script.py", "focal_class": null, "focal_method": "is_public_key", "tests": "import unittest\n\nclass Test_is_public_key(unittest.TestCase):\n def test_is_public_key(self):\n case1 = '010000000000000017a91471c5c3727fac8dbace94bd38cf8ac16a034a794787'\n self.assertFalse(is_public_key(a2b_hex(case1)))\n self.assertFalse(is_public_key(None))\n case3 = '02c0993f639534d348e1dca30566491e6cb11c14afa13ec244c05396a9839aeb17'\n self.assertTrue(is_public_key(a2b_hex(case3)))\n", "method_code": "def is_public_key(hex_data):\n \"\"\"Given a bytes string, returns whether its is probably a bitcoin\n public key or not. It doesn't actually ensures that the data is a valid\n public key, justs that it looks like one\n \"\"\"\n if type(hex_data) != bytes:\n return False\n if len(hex_data) == 65 and int(hex_data[0]) == 4:\n return True\n if len(hex_data) == 33 and int(hex_data[0]) in [2, 3]:\n return True\n return False", "context": "def is_public_key(hex_data): ...\ndef is_public_key(hex_data): ...\n", "repository": "0x-genesys/Blockchain-explorer", "test_name": "test_is_public_key", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002584.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/transaction.py", "focal_class": "Transaction", "focal_method": "uses_bip69", "tests": "import unittest\n\nclass Test_Transaction_uses_bip69(unittest.TestCase):\n def test_bip69(self):\n noncompliant = 'bip69_false.txt'\n with open(os.path.join(dir_path, noncompliant)) as f:\n data = a2b_hex(f.read().strip())\n tx = Transaction(data)\n self.assertFalse(tx.uses_bip69())\n compliant = 'bip69_true.txt'\n with open(os.path.join(dir_path, compliant)) as f:\n data = a2b_hex(f.read().strip())\n tx = Transaction(data)\n self.assertTrue(tx.uses_bip69())\n", "method_code": " def uses_bip69(self):\n \"\"\"Returns whether the transaction complies to BIP-69,\n lexicographical ordering of inputs and outputs\"\"\"\n if self.n_inputs == 1 and self.n_outputs == 1:\n return True\n input_keys = [(i.transaction_hash, i.transaction_index) for i in self.inputs]\n if bip69_sort(input_keys) != input_keys:\n return False\n output_keys = [(o.value, o.script.value) for o in self.outputs]\n return bip69_sort(output_keys) == output_keys\n ", "context": "class Transaction(object):\n def uses_bip69(self): ...\n def __init__(self, raw_hex): ...\n def __repr__(self): ...\n def from_hex(cls, hex): ...\n def version(self): ...\n def locktime(self): ...\n def hash(self): ...\n def hash(self): ...\n def txid(self): ...\n def is_coinbase(self): ...\n def uses_replace_by_fee(self): ...\n\n self._hash = None\n self._txid = None\n self.inputs = None\n self.outputs = None\n self._version = None\n self._locktime = None\n self.n_inputs = 0\n self.n_outputs = 0\n self.is_segwit = False\n self.n_inputs, varint_size = decode_varint(raw_hex[offset:])\n self.inputs = []\n self.n_outputs, varint_size = decode_varint(raw_hex[offset:])\n self.outputs = []\n self.size = offset + 4\n self.hex = raw_hex[:self.size]\n", "repository": "0x-genesys/Blockchain-explorer", "test_name": "test_bip69", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002585.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/utils.py", "focal_class": null, "focal_method": "btc_ripemd160", "tests": "import unittest\n\nclass Test_btc_ripemd160(unittest.TestCase):\n def test_btc_ripemd160(self):\n data = a2b_hex('02218AD6CDC632E7AE7D04472374311CEBBBBF0AB540D2D08C3400BB844C654231')\n ripe = utils.btc_ripemd160(data)\n expected = b'5238c71458e464d9ff90299abca4a1d7b9cb76ab'\n self.assertEqual(b2a_hex(ripe), expected)\n", "method_code": "def btc_ripemd160(data):\n h1 = hashlib.sha256(data).digest()\n r160 = hashlib.new('ripemd160')\n r160.update(h1)\n return r160.digest()", "context": "def btc_ripemd160(data): ...\ndef btc_ripemd160(data): ...\ndef double_sha256(data): ...\ndef format_hash(hash_): ...\ndef decode_uint32(data): ...\ndef decode_uint64(data): ...\ndef decode_varint(data): ...\n", "repository": "0x-genesys/Blockchain-explorer", "test_name": "test_btc_ripemd160", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002586.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/utils.py", "focal_class": null, "focal_method": "format_hash", "tests": "import unittest\n\nclass Test_format_hash(unittest.TestCase):\n def test_format_hash(self):\n data = a2b_hex('deadbeef')\n self.assertEqual(utils.format_hash(data), 'efbeadde')\n", "method_code": "def format_hash(hash_):\n return str(hexlify(hash_[::-1]).decode('utf-8'))", "context": "def format_hash(hash_): ...\ndef btc_ripemd160(data): ...\ndef double_sha256(data): ...\ndef format_hash(hash_): ...\ndef decode_uint32(data): ...\ndef decode_uint64(data): ...\ndef decode_varint(data): ...\n", "repository": "0x-genesys/Blockchain-explorer", "test_name": "test_format_hash", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002587.py"} {"focal_file": "python-bitcoin-blockchain-parser/blockchain_parser/utils.py", "focal_class": null, "focal_method": "decode_uint32", "tests": "import unittest\n\nclass Test_decode_uint32(unittest.TestCase):\n def test_decode_uint32(self):\n uint32_dict = {'01000000': 1, '000000ff': 4278190080}\n for uint32, value in uint32_dict.items():\n self.assertEqual(utils.decode_uint32(a2b_hex(uint32)), value)\n", "method_code": "def decode_uint32(data):\n assert len(data) == 4\n return struct.unpack(' 0\n size = int(data[0])\n assert size <= 255\n if size < 253:\n return (size, 1)\n if size == 253:\n format_ = ''\n self.conversation_client = conversation_client\n self.workspace_id = self.setup_conversation_workspace(conversation_client, os.environ)\n self.cloudant_online_store = cloudant_online_store\n self.discovery_client = discovery_client\n self.discovery_data_source = os.environ.get('DISCOVERY_DATA_SOURCE', DISCOVERY_IBM_STORE)\n self.discovery_environment_id, self.discovery_collection_id = self.setup_discovery_collection(discovery_client, self.discovery_data_source, os.environ)\n self.context = {}\n self.customer = None\n self.response_tuple = None\n self.delay = 0.5\n", "repository": "MBakker69/WOS", "test_name": "test_init_customer_slack_fail", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002605.py"} {"focal_file": "watsononlinestore/watson_online_store.py", "focal_class": null, "focal_method": "parse_slack_output", "tests": "import unittest\n\nclass Test_parse_slack_output(unittest.TestCase):\n @ddt.data(([{'text': '<@UBOTID> suFFix', 'channel': 'C', 'user': 'U'}], ('suffix', 'C', 'U')), ([{'text': 'prefix <@UBOTID> Suffix', 'channel': 'C', 'user': 'U'}], ('prefix suffix', 'C', 'U')), ([{'text': 'prefix <@UBOTID> Suffix<@UBOTID>Tail', 'channel': 'C', 'user': 'U'}], ('prefix suffixtail', 'C', 'U')), ([{'text': 'prefix <@UBOTID> suffix', 'channel': 'DXXX', 'user': 'U'}], ('prefix suffix', 'DXXX', 'U')), ([{'text': 'this is a dm', 'channel': 'DXXX', 'user': 'U'}], ('this is a dm', 'DXXX', 'U')))\n @ddt.unpack\n def test_parse_slack_output(self, output_list, expected):\n actual = self.wos.parse_slack_output(output_list)\n self.assertEqual(expected, actual)\n\n @ddt.data([{}, {'text': '<@UBOTID> hi', 'user_profile': 'x'}, {'text': 'hello world', 'channel': 'NOTDM'}])\n def test_parse_slack_output_to_skip(self, output_list):\n expected = (None, None, None)\n actual = self.wos.parse_slack_output(output_list)\n self.assertEqual(expected, actual)\n", "method_code": " def parse_slack_output(self, output_dict):\n \"\"\"Prepare output when using Slack as UI.\n \n :param dict output_dict: text, channel, user, etc from slack posting\n :returns: text, channel, user\n :rtype: str, str, str\n \"\"\"\n if output_dict and len(output_dict) > 0:\n for output in output_dict:\n if output and 'text' in output and ('user' in output) and ('user_profile' not in output):\n if self.at_bot in output['text']:\n return (''.join(output['text'].split(self.at_bot)).strip().lower(), output['channel'], output['user'])\n elif output['channel'].startswith('D') and output['user'] != self.bot_id:\n return (output['text'].strip().lower(), output['channel'], output['user'])\n return (None, None, None)\n ", "context": "class WatsonOnlineStore():\n def parse_slack_output(self, output_dict): ...\n def __init__(self, bot_id, slack_client, conversation_client, discovery_client, cloudant_online_store): ...\n def setup_conversation_workspace(conversation_client, environ): ...\n def setup_discovery_collection(discovery_client, data_source, environ): ...\n def get_workspace_json(): ...\n def context_merge(self, dict1, dict2): ...\n def post_to_slack(self, response, channel): ...\n def add_customer_to_context(self): ...\n def customer_from_db(self, user_data): ...\n def create_user_from_ui(self, user_json): ...\n def init_customer(self, user_id): ...\n def get_fake_discovery_response(self): ...\n def handle_discovery_query(self): ...\n def get_watson_response(self, message): ...\n def format_discovery_response(response, data_source): ...\n def get_discovery_response(self, input_text): ...\n def handle_list_shopping_cart(self): ...\n def clear_shopping_cart(self): ...\n def handle_delete_from_cart(self): ...\n def handle_add_to_cart(self): ...\n def handle_message(self, message, sender): ...\n def run(self): ...\n\n self.bot_id = bot_id\n self.slack_client = slack_client\n self.at_bot = '<@' + bot_id + '>'\n self.conversation_client = conversation_client\n self.workspace_id = self.setup_conversation_workspace(conversation_client, os.environ)\n self.cloudant_online_store = cloudant_online_store\n self.discovery_client = discovery_client\n self.discovery_data_source = os.environ.get('DISCOVERY_DATA_SOURCE', DISCOVERY_IBM_STORE)\n self.discovery_environment_id, self.discovery_collection_id = self.setup_discovery_collection(discovery_client, self.discovery_data_source, os.environ)\n self.context = {}\n self.customer = None\n self.response_tuple = None\n self.delay = 0.5\n", "repository": "MBakker69/WOS", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002606.py"} {"focal_file": "watsononlinestore/watson_online_store.py", "focal_class": null, "focal_method": "setup_conversation_workspace", "tests": "import unittest\n\nclass Test_setup_conversation_workspace(unittest.TestCase):\n def test_setup_conversation_workspace_by_name_default(self):\n test_environ = {}\n expected_workspace_id = 'this is the one'\n self.conv_client.list_workspaces = mock.Mock(return_value={'workspaces': [{'workspace_id': 'other', 'name': 'foo'}, {'workspace_id': expected_workspace_id, 'name': 'watson-online-store'}]})\n wos = watson_online_store.WatsonOnlineStore\n actual = wos.setup_conversation_workspace(self.conv_client, test_environ)\n self.conv_client.list_workspaces.assert_called_once()\n self.assertEqual(expected_workspace_id, actual)\n\n def test_setup_conversation_workspace_by_name_env(self):\n test_environ = {'WORKSPACE_NAME': 'foo name'}\n expected_workspace_id = 'this is the one'\n self.conv_client.list_workspaces = mock.Mock(return_value={'workspaces': [{'workspace_id': 'other', 'name': 'foo'}, {'workspace_id': expected_workspace_id, 'name': test_environ['WORKSPACE_NAME']}]})\n wos = watson_online_store.WatsonOnlineStore\n actual = wos.setup_conversation_workspace(self.conv_client, test_environ)\n self.conv_client.list_workspaces.assert_called_once()\n self.assertEqual(expected_workspace_id, actual)\n\n def test_setup_conversation_workspace_by_id(self):\n expected_workspace_id = 'testing with a ws ID'\n test_environ = {'WORKSPACE_ID': expected_workspace_id}\n self.conv_client.list_workspaces = mock.Mock(return_value={'workspaces': [{'workspace_id': 'other'}, {'workspace_id': expected_workspace_id, 'name': 'foo'}]})\n wos = watson_online_store.WatsonOnlineStore\n actual = wos.setup_conversation_workspace(self.conv_client, test_environ)\n self.conv_client.list_workspaces.assert_called_once()\n self.assertEqual(expected_workspace_id, actual)\n\n def test_setup_conversation_workspace_create(self):\n expected_workspace_id = 'this was created'\n expected_workspace_name = 'and this was its name'\n test_environ = {'WORKSPACE_NAME': expected_workspace_name}\n self.conv_client.list_workspaces = mock.Mock(return_value={'workspaces': [{'workspace_id': 'other', 'name': 'any'}]})\n self.conv_client.create_workspace = mock.Mock(return_value={'workspace_id': expected_workspace_id})\n wos = watson_online_store.WatsonOnlineStore\n ws_json = {'counterexamples': 'c', 'intents': 'i', 'entities': 'e', 'dialog_nodes': 'd', 'metadata': 'm', 'language': 'en'}\n wos.get_workspace_json = mock.Mock(return_value=ws_json)\n actual = wos.setup_conversation_workspace(self.conv_client, test_environ)\n self.conv_client.list_workspaces.assert_called_once()\n self.conv_client.create_workspace.assert_called_once_with(expected_workspace_name, 'Conversation workspace created by watson-online-store.', ws_json['language'], intents=ws_json['intents'], entities=ws_json['entities'], dialog_nodes=ws_json['dialog_nodes'], counterexamples=ws_json['counterexamples'], metadata=ws_json['metadata'])\n self.assertEqual(expected_workspace_id, actual)\n", "method_code": " def setup_conversation_workspace(conversation_client, environ):\n \"\"\"Verify and/or initialize the conversation workspace.\n \n If a WORKSPACE_ID is specified in the runtime environment,\n make sure that workspace exists. If no WORKSTATION_ID is\n specified then try to find it using a lookup by name.\n Name will be 'watson-online-store' unless overridden\n using the WORKSPACE_NAME environment variable.\n \n If a workspace is not found by ID or name, then try to\n create one from the JSON in data/workspace.json. Use the\n name as mentioned above so future lookup will find what\n was created.\n \n :param conversation_client: Conversation service client\n :param object environ: runtime environment variables\n :return: ID of conversation workspace to use\n :rtype: str\n :raise Exception: When workspace is not found and cannot be created\n \"\"\"\n workspaces = conversation_client.list_workspaces()['workspaces']\n env_workspace_id = environ.get('WORKSPACE_ID')\n if env_workspace_id:\n LOG.debug('Using WORKSPACE_ID=%s' % env_workspace_id)\n for workspace in workspaces:\n if workspace['workspace_id'] == env_workspace_id:\n ret = env_workspace_id\n break\n else:\n raise Exception('WORKSPACE_ID=%s is specified in a runtime environment variable, but that workspace does not exist.' % env_workspace_id)\n else:\n name = environ.get('WORKSPACE_NAME', 'watson-online-store')\n for workspace in workspaces:\n if workspace['name'] == name:\n ret = workspace['workspace_id']\n LOG.debug('Found WORKSPACE_ID=%(id)s using lookup by name=%(name)s' % {'id': ret, 'name': name})\n break\n else:\n LOG.debug('Creating workspace from data/workspace.json...')\n workspace = WatsonOnlineStore.get_workspace_json()\n created = conversation_client.create_workspace(name, 'Conversation workspace created by watson-online-store.', workspace['language'], intents=workspace['intents'], entities=workspace['entities'], dialog_nodes=workspace['dialog_nodes'], counterexamples=workspace['counterexamples'], metadata=workspace['metadata'])\n ret = created['workspace_id']\n LOG.debug('Created WORKSPACE_ID=%(id)s with name=%(name)s' % {'id': ret, 'name': name})\n return ret\n ", "context": "class WatsonOnlineStore():\n @staticmethod\n def setup_conversation_workspace(conversation_client, environ): ...\n def __init__(self, bot_id, slack_client, conversation_client, discovery_client, cloudant_online_store): ...\n def setup_discovery_collection(discovery_client, data_source, environ): ...\n def get_workspace_json(): ...\n def context_merge(self, dict1, dict2): ...\n def parse_slack_output(self, output_dict): ...\n def post_to_slack(self, response, channel): ...\n def add_customer_to_context(self): ...\n def customer_from_db(self, user_data): ...\n def create_user_from_ui(self, user_json): ...\n def init_customer(self, user_id): ...\n def get_fake_discovery_response(self): ...\n def handle_discovery_query(self): ...\n def get_watson_response(self, message): ...\n def format_discovery_response(response, data_source): ...\n def get_discovery_response(self, input_text): ...\n def handle_list_shopping_cart(self): ...\n def clear_shopping_cart(self): ...\n def handle_delete_from_cart(self): ...\n def handle_add_to_cart(self): ...\n def handle_message(self, message, sender): ...\n def run(self): ...\n\n self.bot_id = bot_id\n self.slack_client = slack_client\n self.at_bot = '<@' + bot_id + '>'\n self.conversation_client = conversation_client\n self.workspace_id = self.setup_conversation_workspace(conversation_client, os.environ)\n self.cloudant_online_store = cloudant_online_store\n self.discovery_client = discovery_client\n self.discovery_data_source = os.environ.get('DISCOVERY_DATA_SOURCE', DISCOVERY_IBM_STORE)\n self.discovery_environment_id, self.discovery_collection_id = self.setup_discovery_collection(discovery_client, self.discovery_data_source, os.environ)\n self.context = {}\n self.customer = None\n self.response_tuple = None\n self.delay = 0.5\n", "repository": "MBakker69/WOS", "test_name": "test_setup_conversation_workspace_by_name_default", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002607.py"} {"focal_file": "watsononlinestore/watson_online_store.py", "focal_class": null, "focal_method": "setup_discovery_collection", "tests": "import unittest\n\nclass Test_setup_discovery_collection(unittest.TestCase):\n def test_setup_discovery_environment_by_id(self):\n expected_environment_id = 'testing with a env ID'\n expected_collection_id = 'testing with a coll ID'\n test_environ = {'DISCOVERY_ENVIRONMENT_ID': expected_environment_id, self.fake_data_source + '_DISCO_COLLECTION_ID': expected_collection_id}\n self.discovery_client.get_environment = mock.Mock(return_value={'environment_id': expected_environment_id})\n self.discovery_client.get_collection = mock.Mock(return_value={'collection_id': expected_collection_id})\n wos = watson_online_store.WatsonOnlineStore\n actual_env, actual_coll = wos.setup_discovery_collection(self.discovery_client, self.fake_data_source, test_environ)\n self.discovery_client.get_environment.assert_called_once()\n self.discovery_client.get_collection.assert_called_once()\n self.assertEqual(expected_environment_id, actual_env)\n self.assertEqual(expected_collection_id, actual_coll)\n\n def test_setup_discovery_environment_by_name_default(self):\n test_environ = {}\n expected_environment_id = 'this is the env'\n expected_collection_id = 'this is the coll'\n self.discovery_client.get_environments = mock.Mock(return_value={'environments': [{'environment_id': 'other', 'name': 'foo'}, {'environment_id': expected_environment_id, 'name': 'watson-online-store'}]})\n self.discovery_client.list_collections = mock.Mock(return_value={'collections': [{'collection_id': 'other', 'name': 'foo'}, {'collection_id': expected_collection_id, 'name': 'ibm-logo-store'}]})\n wos = watson_online_store.WatsonOnlineStore\n actual_env, actual_coll = wos.setup_discovery_collection(self.discovery_client, self.fake_data_source, test_environ)\n self.discovery_client.get_environments.assert_called_once()\n self.discovery_client.list_collections.assert_called_once()\n self.assertEqual(expected_environment_id, actual_env)\n self.assertEqual(expected_collection_id, actual_coll)\n", "method_code": " def setup_discovery_collection(discovery_client, data_source, environ):\n \"\"\" Ensure that the collection exists in the Watson Discovery service.\n \n :param discovery_client: discovery service client\n :param str data_source: name of the discovery data source\n :param object environ: runtime environment variables\n :return: ID of discovery environment and collection to use\n :rtype: str\n :raise Exception: When collection is not found and cannot be created\n \"\"\"\n environment_id = environ.get('DISCOVERY_ENVIRONMENT_ID')\n if environment_id:\n try:\n LOG.debug('Using DISCOVERY_ENVIRONMENT_ID=%s' % environment_id)\n discovery_client.get_environment(environment_id)\n except Exception:\n raise Exception('Environment with DISCOVERY_ENVIRONMENT_ID=%s does not exist.' % environment_id)\n else:\n name = environ.get('DISCOVERY_ENVIRONMENT_NAME', 'watson-online-store')\n reserved_name = 'Watson News Environment'\n environments = discovery_client.get_environments()['environments']\n for environment in environments:\n if environment['name'] == name:\n environment_id = environment['environment_id']\n LOG.debug('Found DISCOVERY_ENVIRONMENT_ID=%(id)s using lookup by name=%(name)s' % {'id': environment_id, 'name': name})\n break\n elif environment['name'] != reserved_name:\n environment_id = environment['environment_id']\n if not environment_id:\n try:\n LOG.debug('Creating discovery environment...')\n created = discovery_client.create_environment(name, 'Discovery environment created by watson-online-store.', size=0)\n environment_id = created['environment_id']\n LOG.debug('Created DISCOVERY_ENVIRONMENT_ID=%(id)s with name=%(name)s' % {'id': environment_id, 'name': name})\n except Exception as e:\n raise Exception('Error creating Discovery Error: %s' % repr(e))\n collection_id = environ.get(data_source + '_DISCO_COLLECTION_ID')\n if collection_id:\n try:\n LOG.debug('Using DISCOVERY_COLLECTION_ID=%s' % collection_id)\n discovery_client.get_collection(environment_id, collection_id)\n return (environment_id, collection_id)\n except Exception:\n raise Exception('Collection with DISCOVERY_COLLECTION_ID=%s does not exist.' % collection_id)\n else:\n amazon_collection_name = 'amazon-shopping'\n ibm_collection_name = 'ibm-logo-store'\n amazon_data_path = 'data/amazon_data_html/'\n ibm_data_path = 'data/ibm_store_html/'\n collections = discovery_client.list_collections(environment_id)['collections']\n for coll in collections:\n if data_source == DISCOVERY_AMAZON_STORE and coll['name'] == amazon_collection_name or (data_source == DISCOVERY_IBM_STORE and coll['name'] == ibm_collection_name):\n return (environment_id, coll['collection_id'])\n LOG.debug('Creating collection from html files...')\n try:\n if data_source == DISCOVERY_AMAZON_STORE:\n name = amazon_collection_name\n path = amazon_data_path\n elif data_source == DISCOVERY_IBM_STORE:\n name = ibm_collection_name\n path = ibm_data_path\n if name:\n collection = discovery_client.create_collection(environment_id, name)\n if collection:\n collection_id = collection['collection_id']\n for _, _, files in os.walk(path):\n for file in files:\n if file.endswith('.html'):\n with open(os.path.join(path, file), 'r') as f:\n data = f.read()\n discovery_client.add_document(environment_id, collection_id, file_data=data)\n except Exception as e:\n raise Exception('Discovery Collection could not be created. Error: %s' % repr(e))\n if not collection_id:\n raise Exception('Discovery Collection could not be found or created.')\n return (environment_id, collection_id)\n ", "context": "class WatsonOnlineStore():\n @staticmethod\n def setup_discovery_collection(discovery_client, data_source, environ): ...\n def __init__(self, bot_id, slack_client, conversation_client, discovery_client, cloudant_online_store): ...\n def setup_conversation_workspace(conversation_client, environ): ...\n def get_workspace_json(): ...\n def context_merge(self, dict1, dict2): ...\n def parse_slack_output(self, output_dict): ...\n def post_to_slack(self, response, channel): ...\n def add_customer_to_context(self): ...\n def customer_from_db(self, user_data): ...\n def create_user_from_ui(self, user_json): ...\n def init_customer(self, user_id): ...\n def get_fake_discovery_response(self): ...\n def handle_discovery_query(self): ...\n def get_watson_response(self, message): ...\n def format_discovery_response(response, data_source): ...\n def get_discovery_response(self, input_text): ...\n def handle_list_shopping_cart(self): ...\n def clear_shopping_cart(self): ...\n def handle_delete_from_cart(self): ...\n def handle_add_to_cart(self): ...\n def handle_message(self, message, sender): ...\n def run(self): ...\n\n self.bot_id = bot_id\n self.slack_client = slack_client\n self.at_bot = '<@' + bot_id + '>'\n self.conversation_client = conversation_client\n self.workspace_id = self.setup_conversation_workspace(conversation_client, os.environ)\n self.cloudant_online_store = cloudant_online_store\n self.discovery_client = discovery_client\n self.discovery_data_source = os.environ.get('DISCOVERY_DATA_SOURCE', DISCOVERY_IBM_STORE)\n self.discovery_environment_id, self.discovery_collection_id = self.setup_discovery_collection(discovery_client, self.discovery_data_source, os.environ)\n self.context = {}\n self.customer = None\n self.response_tuple = None\n self.delay = 0.5\n", "repository": "MBakker69/WOS", "test_name": "test_setup_discovery_environment_by_id", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002608.py"} {"focal_file": "reed_solomon.py", "focal_class": null, "focal_method": "add_polynomials", "tests": "import unittest\n\nclass Test_add_polynomials(unittest.TestCase):\n def test_add_known_polynomials(self):\n addition = add_polynomials([1, 0, 2], [1, 3, 2, 5])\n self.assertSequenceEqual([2, 3, 4, 5], addition)\n", "method_code": "def add_polynomials(P, Q):\n n = max(len(P), len(Q))\n return [get_coefficient(P, i) + get_coefficient(Q, i) for i in range(n)]", "context": "def add_polynomials(P, Q): ...\ndef pad(message, chunk_size): ...\ndef unpad(message): ...\ndef chunkify(message, chunk_size): ...\ndef unchunkify(chunks): ...\ndef convert(string): ...\ndef deconvert(sequence): ...\ndef evaluate_polynomial(coefficients, x): ...\ndef encode(chunk, n): ...\ndef get_coefficient(P, i): ...\ndef add_polynomials(P, Q): ...\ndef scale_polynomial(P, a): ...\ndef multiply_polynomials(P, Q): ...\ndef lagrange_basis_denominator(xs, j): ...\ndef lagrange_basis_element(xs, j): ...\ndef interpolate(points): ...\ndef erasure_code(message, chunk_size, encoded_chunk_size): ...\ndef erasure_decode(encoded_chunks, chunk_size, encoded_chunk_size): ...\ndef disperse(encoded_chunks): ...\ndef retrieve(*nodes): ...\n", "repository": "zackmdavis/Standard_Algorithms", "test_name": "test_add_known_polynomials", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002609.py"} {"focal_file": "reed_solomon.py", "focal_class": null, "focal_method": "scale_polynomial", "tests": "import unittest\n\nclass Test_scale_polynomial(unittest.TestCase):\n def test_scale_known_polynomial(self):\n self.assertSequenceEqual([5, 5, 5], scale_polynomial([1, 1, 1], 5))\n", "method_code": "def scale_polynomial(P, a):\n return [a * c for c in P]", "context": "def scale_polynomial(P, a): ...\ndef pad(message, chunk_size): ...\ndef unpad(message): ...\ndef chunkify(message, chunk_size): ...\ndef unchunkify(chunks): ...\ndef convert(string): ...\ndef deconvert(sequence): ...\ndef evaluate_polynomial(coefficients, x): ...\ndef encode(chunk, n): ...\ndef get_coefficient(P, i): ...\ndef add_polynomials(P, Q): ...\ndef scale_polynomial(P, a): ...\ndef multiply_polynomials(P, Q): ...\ndef lagrange_basis_denominator(xs, j): ...\ndef lagrange_basis_element(xs, j): ...\ndef interpolate(points): ...\ndef erasure_code(message, chunk_size, encoded_chunk_size): ...\ndef erasure_decode(encoded_chunks, chunk_size, encoded_chunk_size): ...\ndef disperse(encoded_chunks): ...\ndef retrieve(*nodes): ...\n", "repository": "zackmdavis/Standard_Algorithms", "test_name": "test_scale_known_polynomial", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002610.py"} {"focal_file": "reed_solomon.py", "focal_class": null, "focal_method": "multiply_polynomials", "tests": "import unittest\n\nclass Test_multiply_polynomials(unittest.TestCase):\n def test_multiply_known_polynomials(self):\n product = multiply_polynomials([0, 1, 3, 4], [1, 4])\n self.assertSequenceEqual([0, 1, 7, 16, 16], strip_trailing_zeros(product))\n", "method_code": "def multiply_polynomials(P, Q):\n maximum_terms = len(P) + len(Q)\n R = [0 for _ in range(maximum_terms)]\n for i, c in enumerate(P):\n for j, d in enumerate(Q):\n R[i + j] += c * d\n return R", "context": "def multiply_polynomials(P, Q): ...\ndef pad(message, chunk_size): ...\ndef unpad(message): ...\ndef chunkify(message, chunk_size): ...\ndef unchunkify(chunks): ...\ndef convert(string): ...\ndef deconvert(sequence): ...\ndef evaluate_polynomial(coefficients, x): ...\ndef encode(chunk, n): ...\ndef get_coefficient(P, i): ...\ndef add_polynomials(P, Q): ...\ndef scale_polynomial(P, a): ...\ndef multiply_polynomials(P, Q): ...\ndef lagrange_basis_denominator(xs, j): ...\ndef lagrange_basis_element(xs, j): ...\ndef interpolate(points): ...\ndef erasure_code(message, chunk_size, encoded_chunk_size): ...\ndef erasure_decode(encoded_chunks, chunk_size, encoded_chunk_size): ...\ndef disperse(encoded_chunks): ...\ndef retrieve(*nodes): ...\n", "repository": "zackmdavis/Standard_Algorithms", "test_name": "test_multiply_known_polynomials", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002611.py"} {"focal_file": "reed_solomon.py", "focal_class": null, "focal_method": "lagrange_basis_denominator", "tests": "import unittest\n\nclass Test_lagrange_basis_denominator(unittest.TestCase):\n def test_known_lagrange_basis_denominator(self):\n xs = [0, 1, 2]\n expected_denominators = [2, -1, 2]\n for j, x, d in zip(range(len(xs)), xs, expected_denominators):\n self.assertEqual(d, lagrange_basis_denominator(xs, j))\n", "method_code": "def lagrange_basis_denominator(xs, j):\n denominator = 1\n for i, x in enumerate(xs):\n if i == j:\n continue\n denominator *= xs[j] - xs[i]\n return denominator", "context": "def lagrange_basis_denominator(xs, j): ...\ndef pad(message, chunk_size): ...\ndef unpad(message): ...\ndef chunkify(message, chunk_size): ...\ndef unchunkify(chunks): ...\ndef convert(string): ...\ndef deconvert(sequence): ...\ndef evaluate_polynomial(coefficients, x): ...\ndef encode(chunk, n): ...\ndef get_coefficient(P, i): ...\ndef add_polynomials(P, Q): ...\ndef scale_polynomial(P, a): ...\ndef multiply_polynomials(P, Q): ...\ndef lagrange_basis_denominator(xs, j): ...\ndef lagrange_basis_element(xs, j): ...\ndef interpolate(points): ...\ndef erasure_code(message, chunk_size, encoded_chunk_size): ...\ndef erasure_decode(encoded_chunks, chunk_size, encoded_chunk_size): ...\ndef disperse(encoded_chunks): ...\ndef retrieve(*nodes): ...\n", "repository": "zackmdavis/Standard_Algorithms", "test_name": "test_known_lagrange_basis_denominator", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002612.py"} {"focal_file": "reed_solomon.py", "focal_class": null, "focal_method": "lagrange_basis_element", "tests": "import unittest\n\nclass Test_lagrange_basis_element(unittest.TestCase):\n def test_known_lagrange_basis_element(self):\n xs = [0, 1, 2]\n expected_elements = [[1, -3 / 2, 1 / 2], [0, 2, -1], [0, -1 / 2, 1 / 2]]\n for j, x, b in zip(range(len(xs)), xs, expected_elements):\n result = strip_trailing_zeros(lagrange_basis_element(xs, j))\n self.assertSequenceEqual(b, result)\n", "method_code": "def lagrange_basis_element(xs, j):\n element = [1]\n for i in range(len(xs)):\n if i == j:\n continue\n element = multiply_polynomials(element, [-xs[i], 1])\n scaling_factor = 1 / lagrange_basis_denominator(xs, j)\n return scale_polynomial(element, scaling_factor)", "context": "def lagrange_basis_element(xs, j): ...\ndef pad(message, chunk_size): ...\ndef unpad(message): ...\ndef chunkify(message, chunk_size): ...\ndef unchunkify(chunks): ...\ndef convert(string): ...\ndef deconvert(sequence): ...\ndef evaluate_polynomial(coefficients, x): ...\ndef encode(chunk, n): ...\ndef get_coefficient(P, i): ...\ndef add_polynomials(P, Q): ...\ndef scale_polynomial(P, a): ...\ndef multiply_polynomials(P, Q): ...\ndef lagrange_basis_denominator(xs, j): ...\ndef lagrange_basis_element(xs, j): ...\ndef interpolate(points): ...\ndef erasure_code(message, chunk_size, encoded_chunk_size): ...\ndef erasure_decode(encoded_chunks, chunk_size, encoded_chunk_size): ...\ndef disperse(encoded_chunks): ...\ndef retrieve(*nodes): ...\n", "repository": "zackmdavis/Standard_Algorithms", "test_name": "test_known_lagrange_basis_element", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002613.py"} {"focal_file": "reed_solomon.py", "focal_class": null, "focal_method": "interpolate", "tests": "import unittest\n\nclass Test_interpolate(unittest.TestCase):\n def test_lagrange_interpolation(self):\n for m in range(2, MAX_TESTED_CHUNK_SIZE):\n for n in range(m + 1, 2 * MAX_TESTED_CHUNK_SIZE):\n polynomial = strip_trailing_zeros(arbitrary_polynomial(m))\n points = [(x, evaluate_polynomial(polynomial, x)) for x in range(n)]\n interpolated = strip_trailing_zeros(interpolate(sample(points, m + 1)))\n self.assertSequenceEqual(polynomial, interpolated)\n", "method_code": "def interpolate(points):\n result = [0]\n xs, ys = zip(*points)\n for j in range(len(points)):\n result = add_polynomials(result, scale_polynomial(lagrange_basis_element(xs, j), ys[j]))\n return [round(i) for i in result]", "context": "def interpolate(points): ...\ndef pad(message, chunk_size): ...\ndef unpad(message): ...\ndef chunkify(message, chunk_size): ...\ndef unchunkify(chunks): ...\ndef convert(string): ...\ndef deconvert(sequence): ...\ndef evaluate_polynomial(coefficients, x): ...\ndef encode(chunk, n): ...\ndef get_coefficient(P, i): ...\ndef add_polynomials(P, Q): ...\ndef scale_polynomial(P, a): ...\ndef multiply_polynomials(P, Q): ...\ndef lagrange_basis_denominator(xs, j): ...\ndef lagrange_basis_element(xs, j): ...\ndef interpolate(points): ...\ndef erasure_code(message, chunk_size, encoded_chunk_size): ...\ndef erasure_decode(encoded_chunks, chunk_size, encoded_chunk_size): ...\ndef disperse(encoded_chunks): ...\ndef retrieve(*nodes): ...\n", "repository": "zackmdavis/Standard_Algorithms", "test_name": "test_lagrange_interpolation", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002614.py"} {"focal_file": "reed_solomon.py", "focal_class": null, "focal_method": "erasure_code", "tests": "import unittest\n\nclass Test_erasure_code(unittest.TestCase):\n def test_erasure_coding(self):\n for length in range(10, MAX_TESTED_MESSAGE_LENGTH):\n for chunk_size in range(1, MAX_TESTED_CHUNK_SIZE):\n for encoded_chunk_size in range(chunk_size, chunk_size + 10):\n message = arbitrary_message(length)\n retrieved = erasure_decode(erasure_code(message, chunk_size, encoded_chunk_size), chunk_size, encoded_chunk_size)\n self.assertEqual(message, retrieved)\n", "method_code": "def erasure_code(message, chunk_size, encoded_chunk_size):\n chunks = chunkify(pad(message, chunk_size), chunk_size)\n converted_chunks = [convert(chunk) for chunk in chunks]\n return [[(i, evaluate_polynomial(chunk, i)) for i in range(encoded_chunk_size)] for chunk in converted_chunks]", "context": "def erasure_code(message, chunk_size, encoded_chunk_size): ...\ndef pad(message, chunk_size): ...\ndef unpad(message): ...\ndef chunkify(message, chunk_size): ...\ndef unchunkify(chunks): ...\ndef convert(string): ...\ndef deconvert(sequence): ...\ndef evaluate_polynomial(coefficients, x): ...\ndef encode(chunk, n): ...\ndef get_coefficient(P, i): ...\ndef add_polynomials(P, Q): ...\ndef scale_polynomial(P, a): ...\ndef multiply_polynomials(P, Q): ...\ndef lagrange_basis_denominator(xs, j): ...\ndef lagrange_basis_element(xs, j): ...\ndef interpolate(points): ...\ndef erasure_code(message, chunk_size, encoded_chunk_size): ...\ndef erasure_decode(encoded_chunks, chunk_size, encoded_chunk_size): ...\ndef disperse(encoded_chunks): ...\ndef retrieve(*nodes): ...\n", "repository": "zackmdavis/Standard_Algorithms", "test_name": "test_erasure_coding", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002615.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/build_ext.py", "focal_class": "build_ext", "focal_method": "get_ext_filename", "tests": "import unittest\n\nclass Test_build_ext_get_ext_filename(unittest.TestCase):\n def test_get_ext_filename(self):\n dist = Distribution()\n cmd = build_ext(dist)\n cmd.ext_map['foo/bar'] = ''\n res = cmd.get_ext_filename('foo')\n wanted = distutils_build_ext.get_ext_filename(cmd, 'foo')\n assert res == wanted\n", "method_code": " def get_ext_filename(self, fullname):\n filename = _build_ext.get_ext_filename(self, fullname)\n if fullname in self.ext_map:\n ext = self.ext_map[fullname]\n if isinstance(ext, Library):\n fn, ext = os.path.splitext(filename)\n return self.shlib_compiler.library_filename(fn, libtype)\n elif use_stubs and ext._links_to_dynamic:\n d, fn = os.path.split(filename)\n return os.path.join(d, 'dl-' + fn)\n return filename\n ", "context": "class build_ext(_build_ext):\n def get_ext_filename(self, fullname): ...\n def run(self): ...\n def copy_extensions_to_source(self): ...\n def initialize_options(self): ...\n def finalize_options(self): ...\n def setup_shlib_compiler(self): ...\n def get_export_symbols(self, ext): ...\n def build_extension(self, ext): ...\n def links_to_dynamic(self, ext): ...\n def get_outputs(self): ...\n def write_stub(self, output_dir, ext, compile=False): ...\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_get_ext_filename", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002616.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/easy_install.py", "focal_class": "easy_install", "focal_method": "install_site_py", "tests": "import unittest\n\nclass Test_easy_install_install_site_py(unittest.TestCase):\n def test_install_site_py(self):\n dist = Distribution()\n cmd = easy_install(dist)\n cmd.sitepy_installed = False\n cmd.install_dir = tempfile.mkdtemp()\n try:\n cmd.install_site_py()\n sitepy = os.path.join(cmd.install_dir, 'site.py')\n self.assertTrue(os.path.exists(sitepy))\n finally:\n shutil.rmtree(cmd.install_dir)\n", "method_code": " def install_site_py(self):\n \"\"\"Make sure there's a site.py in the target dir, if needed\"\"\"\n if self.sitepy_installed:\n return\n sitepy = os.path.join(self.install_dir, 'site.py')\n source = resource_string('setuptools', 'site-patch.py')\n current = ''\n if os.path.exists(sitepy):\n log.debug('Checking existing site.py in %s', self.install_dir)\n f = open(sitepy, 'rb')\n current = f.read()\n if sys.version_info >= (3,):\n current = current.decode()\n f.close()\n if not current.startswith('def __boot():'):\n raise DistutilsError('%s is not a setuptools-generated site.py; please remove it.' % sitepy)\n if current != source:\n log.info('Creating %s', sitepy)\n if not self.dry_run:\n ensure_directory(sitepy)\n f = open(sitepy, 'wb')\n f.write(source)\n f.close()\n self.byte_compile([sitepy])\n self.sitepy_installed = True\n ", "context": "class easy_install(Command):\n def install_site_py(self): ...\n def initialize_options(self): ...\n def delete_blockers(self, blockers): ...\n def finalize_options(self): ...\n def _expand_attrs(self, attrs): ...\n def expand_basedirs(self): ...\n def expand_dirs(self): ...\n def run(self): ...\n def pseudo_tempname(self): ...\n def warn_deprecated_options(self): ...\n def check_site_dir(self): ...\n def cant_write_to_target(self): ...\n def check_pth_processing(self): ...\n def install_egg_scripts(self, dist): ...\n def add_output(self, path): ...\n def not_editable(self, spec): ...\n def check_editable(self, spec): ...\n def easy_install(self, spec, deps=False): ...\n def install_item(self, spec, download, tmpdir, deps, install_needed=False): ...\n def select_scheme(self, name): ...\n def process_distribution(self, requirement, dist, deps=True, *info): ...\n def should_unzip(self, dist): ...\n def maybe_move(self, spec, dist_filename, setup_base): ...\n def install_wrapper_scripts(self, dist): ...\n def install_script(self, dist, script_name, script_text, dev_path=None): ...\n def write_script(self, script_name, contents, mode='t', blockers=()): ...\n def install_eggs(self, spec, dist_filename, tmpdir): ...\n def egg_distribution(self, egg_path): ...\n def install_egg(self, egg_path, tmpdir): ...\n def install_exe(self, dist_filename, tmpdir): ...\n def exe_to_egg(self, dist_filename, egg_tmp): ...\n def installation_report(self, req, dist, what='Installed'): ...\n def report_editable(self, spec, setup_script): ...\n def run_setup(self, setup_script, setup_base, args): ...\n def build_and_install(self, setup_script, setup_base): ...\n def _set_fetcher_options(self, base): ...\n def update_pth(self, dist): ...\n def unpack_progress(self, src, dst): ...\n def unpack_and_compile(self, egg_path, destination): ...\n def byte_compile(self, to_compile): ...\n def no_default_version_msg(self): ...\n def create_home_path(self): ...\n def _expand(self, *attrs): ...\n\n description = 'Find/get/install Python packages'\n command_consumes_arguments = True\n user_options = [('prefix=', None, 'installation prefix'), ('zip-ok', 'z', 'install package as a zipfile'), ('multi-version', 'm', 'make apps have to require() a version'), ('upgrade', 'U', 'force upgrade (searches PyPI for latest versions)'), ('install-dir=', 'd', 'install package to DIR'), ('script-dir=', 's', 'install scripts to DIR'), ('exclude-scripts', 'x', \"Don't install scripts\"), ('always-copy', 'a', 'Copy all needed packages to install dir'), ('index-url=', 'i', 'base URL of Python Package Index'), ('find-links=', 'f', 'additional URL(s) to search for packages'), ('build-directory=', 'b', 'download/extract/build in DIR; keep the results'), ('optimize=', 'O', 'also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable [default: -O0]'), ('record=', None, 'filename in which to record list of installed files'), ('always-unzip', 'Z', \"don't install as a zipfile, no matter what\"), ('site-dirs=', 'S', 'list of directories where .pth files work'), ('editable', 'e', 'Install specified packages in editable form'), ('no-deps', 'N', \"don't install dependencies\"), ('allow-hosts=', 'H', 'pattern(s) that hostnames must match'), ('local-snapshots-ok', 'l', 'allow building eggs from local checkouts'), ('version', None, 'print version information and exit'), ('install-layout=', None, 'installation layout to choose (known values: deb)'), ('force-installation-into-system-dir', '0', 'force installation into /usr'), ('no-find-links', None, \"Don't load find-links defined in packages being installed\")]\n boolean_options = ['zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version', 'force-installation-into-system-dir']\n negative_opt = {'always-unzip': 'zip-ok'}\n create_index = PackageIndex\n INSTALL_SCHEMES = dict(posix=dict(install_dir='$base/lib/python$py_version_short/site-packages', script_dir='$base/bin'), unix_local=dict(install_dir='$base/local/lib/python$py_version_short/%s' % sitedir_name, script_dir='$base/local/bin'), posix_local=dict(install_dir='$base/local/lib/python$py_version_short/%s' % sitedir_name, script_dir='$base/local/bin'), deb_system=dict(install_dir='$base/lib/python3/%s' % sitedir_name, script_dir='$base/bin'))\n DEFAULT_SCHEME = dict(install_dir='$base/Lib/site-packages', script_dir='$base/Scripts')\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_install_site_py", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002617.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/easy_install.py", "focal_class": null, "focal_method": "get_script_args", "tests": "import unittest\n\nclass Test_get_script_args(unittest.TestCase):\n def test_get_script_args(self):\n dist = FakeDist()\n old_platform = sys.platform\n try:\n name, script = [i for i in next(get_script_args(dist))][0:2]\n finally:\n sys.platform = old_platform\n self.assertEqual(script, WANTED)\n", "method_code": " def get_script_args(cls, dist, executable=sys_executable, wininst=False):\n \"\"\"\n Yield write_script() argument tuples for a distribution's entrypoints\n \"\"\"\n gen_class = cls.get_writer(wininst)\n spec = str(dist.as_requirement())\n header = get_script_header('', executable, wininst)\n for type_ in ('console', 'gui'):\n group = type_ + '_scripts'\n for name, ep in dist.get_entry_map(group).items():\n script_text = gen_class.template % locals()\n for res in gen_class._get_script_args(type_, name, header, script_text):\n yield res\n ", "context": "class ScriptWriter(object):\n @classmethod\n def get_script_args(cls, dist, executable=sys_executable, wininst=False): ...\n def get_writer(cls, force_windows): ...\n def _get_script_args(cls, type_, name, header, script_text): ...\n\n template = textwrap.dedent(\"\\n # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\\n __requires__ = %(spec)r\\n import sys\\n from pkg_resources import load_entry_point\\n\\n if __name__ == '__main__':\\n sys.exit(\\n load_entry_point(%(spec)r, %(group)r, %(name)r)()\\n )\\n \").lstrip()\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_get_script_args", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002618.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/easy_install.py", "focal_class": "easy_install", "focal_method": "easy_install", "tests": "import unittest\n\nclass Test_easy_install_easy_install(unittest.TestCase):\n def test_user_install_implied(self):\n site.ENABLE_USER_SITE = True\n dist = Distribution()\n dist.script_name = 'setup.py'\n cmd = easy_install(dist)\n cmd.args = ['py']\n cmd.ensure_finalized()\n self.assertTrue(cmd.user, 'user should be implied')\n", "method_code": " def easy_install(self, spec, deps=False):\n tmpdir = tempfile.mkdtemp(prefix='easy_install-')\n download = None\n if not self.editable:\n self.install_site_py()\n try:\n if not isinstance(spec, Requirement):\n if URL_SCHEME(spec):\n self.not_editable(spec)\n download = self.package_index.download(spec, tmpdir)\n return self.install_item(None, download, tmpdir, deps, True)\n elif os.path.exists(spec):\n self.not_editable(spec)\n return self.install_item(None, spec, tmpdir, deps, True)\n else:\n spec = parse_requirement_arg(spec)\n self.check_editable(spec)\n dist = self.package_index.fetch_distribution(spec, tmpdir, self.upgrade, self.editable, not self.always_copy, self.local_index)\n if dist is None:\n msg = 'Could not find suitable distribution for %r' % spec\n if self.always_copy:\n msg += ' (--always-copy skips system and development eggs)'\n raise DistutilsError(msg)\n elif dist.precedence == DEVELOP_DIST:\n self.process_distribution(spec, dist, deps, 'Using')\n return dist\n else:\n return self.install_item(spec, dist.location, tmpdir, deps)\n finally:\n if os.path.exists(tmpdir):\n rmtree(tmpdir)\n ", "context": "class easy_install(Command):\n def easy_install(self, spec, deps=False): ...\n def initialize_options(self): ...\n def delete_blockers(self, blockers): ...\n def finalize_options(self): ...\n def _expand_attrs(self, attrs): ...\n def expand_basedirs(self): ...\n def expand_dirs(self): ...\n def run(self): ...\n def pseudo_tempname(self): ...\n def warn_deprecated_options(self): ...\n def check_site_dir(self): ...\n def cant_write_to_target(self): ...\n def check_pth_processing(self): ...\n def install_egg_scripts(self, dist): ...\n def add_output(self, path): ...\n def not_editable(self, spec): ...\n def check_editable(self, spec): ...\n def install_item(self, spec, download, tmpdir, deps, install_needed=False): ...\n def select_scheme(self, name): ...\n def process_distribution(self, requirement, dist, deps=True, *info): ...\n def should_unzip(self, dist): ...\n def maybe_move(self, spec, dist_filename, setup_base): ...\n def install_wrapper_scripts(self, dist): ...\n def install_script(self, dist, script_name, script_text, dev_path=None): ...\n def write_script(self, script_name, contents, mode='t', blockers=()): ...\n def install_eggs(self, spec, dist_filename, tmpdir): ...\n def egg_distribution(self, egg_path): ...\n def install_egg(self, egg_path, tmpdir): ...\n def install_exe(self, dist_filename, tmpdir): ...\n def exe_to_egg(self, dist_filename, egg_tmp): ...\n def installation_report(self, req, dist, what='Installed'): ...\n def report_editable(self, spec, setup_script): ...\n def run_setup(self, setup_script, setup_base, args): ...\n def build_and_install(self, setup_script, setup_base): ...\n def _set_fetcher_options(self, base): ...\n def update_pth(self, dist): ...\n def unpack_progress(self, src, dst): ...\n def unpack_and_compile(self, egg_path, destination): ...\n def byte_compile(self, to_compile): ...\n def no_default_version_msg(self): ...\n def install_site_py(self): ...\n def create_home_path(self): ...\n def _expand(self, *attrs): ...\n\n description = 'Find/get/install Python packages'\n command_consumes_arguments = True\n user_options = [('prefix=', None, 'installation prefix'), ('zip-ok', 'z', 'install package as a zipfile'), ('multi-version', 'm', 'make apps have to require() a version'), ('upgrade', 'U', 'force upgrade (searches PyPI for latest versions)'), ('install-dir=', 'd', 'install package to DIR'), ('script-dir=', 's', 'install scripts to DIR'), ('exclude-scripts', 'x', \"Don't install scripts\"), ('always-copy', 'a', 'Copy all needed packages to install dir'), ('index-url=', 'i', 'base URL of Python Package Index'), ('find-links=', 'f', 'additional URL(s) to search for packages'), ('build-directory=', 'b', 'download/extract/build in DIR; keep the results'), ('optimize=', 'O', 'also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable [default: -O0]'), ('record=', None, 'filename in which to record list of installed files'), ('always-unzip', 'Z', \"don't install as a zipfile, no matter what\"), ('site-dirs=', 'S', 'list of directories where .pth files work'), ('editable', 'e', 'Install specified packages in editable form'), ('no-deps', 'N', \"don't install dependencies\"), ('allow-hosts=', 'H', 'pattern(s) that hostnames must match'), ('local-snapshots-ok', 'l', 'allow building eggs from local checkouts'), ('version', None, 'print version information and exit'), ('install-layout=', None, 'installation layout to choose (known values: deb)'), ('force-installation-into-system-dir', '0', 'force installation into /usr'), ('no-find-links', None, \"Don't load find-links defined in packages being installed\")]\n boolean_options = ['zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version', 'force-installation-into-system-dir']\n negative_opt = {'always-unzip': 'zip-ok'}\n create_index = PackageIndex\n INSTALL_SCHEMES = dict(posix=dict(install_dir='$base/lib/python$py_version_short/site-packages', script_dir='$base/bin'), unix_local=dict(install_dir='$base/local/lib/python$py_version_short/%s' % sitedir_name, script_dir='$base/local/bin'), posix_local=dict(install_dir='$base/local/lib/python$py_version_short/%s' % sitedir_name, script_dir='$base/local/bin'), deb_system=dict(install_dir='$base/lib/python3/%s' % sitedir_name, script_dir='$base/bin'))\n DEFAULT_SCHEME = dict(install_dir='$base/Lib/site-packages', script_dir='$base/Scripts')\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_user_install_implied", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002619.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "url_ok", "tests": "import unittest\n\nclass Test_url_ok(unittest.TestCase):\n def test_url_ok(self):\n index = setuptools.package_index.PackageIndex(hosts=('www.example.com',))\n url = 'file:///tmp/test_package_index'\n self.assertTrue(index.url_ok(url, True))\n", "method_code": " def url_ok(self, url, fatal=False):\n s = URL_SCHEME(url)\n if s and s.group(1).lower() == 'file' or self.allows(urlparse(url)[1]):\n return True\n msg = '\\nNote: Bypassing %s (disallowed host; see http://bit.ly/1dg9ijs for details).\\n'\n if fatal:\n raise DistutilsError(msg % url)\n else:\n self.warn(msg, url)\n ", "context": "class PackageIndex(Environment):\n def url_ok(self, url, fatal=False): ...\n def __init__(self, index_url='https://pypi.python.org/simple', hosts=('*',), ca_bundle=None, verify_ssl=True, *args, **kw): ...\n def process_url(self, url, retrieve=False): ...\n def process_filename(self, fn, nested=False): ...\n def scan_egg_links(self, search_path): ...\n def scan_egg_link(self, path, entry): ...\n def process_index(self, url, page): ...\n def need_version_info(self, url): ...\n def scan_all(self, msg=None, *args): ...\n def find_packages(self, requirement): ...\n def obtain(self, requirement, installer=None): ...\n def check_hash(self, checker, filename, tfp): ...\n def add_find_links(self, urls): ...\n def prescan(self): ...\n def not_found_in_index(self, requirement): ...\n def download(self, spec, tmpdir): ...\n def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None): ...\n def fetch(self, requirement, tmpdir, force_scan=False, source=False): ...\n def gen_setup(self, filename, fragment, tmpdir): ...\n def _download_to(self, url, filename): ...\n def reporthook(self, url, filename, blocknum, blksize, size): ...\n def open_url(self, url, warning=None): ...\n def _download_url(self, scheme, url, tmpdir): ...\n def scan_url(self, url): ...\n def _attempt_download(self, url, filename): ...\n def _download_html(self, url, headers, filename): ...\n def _download_svn(self, url, filename): ...\n def _vcs_split_rev_from_url(url, pop_prefix=False): ...\n def _download_git(self, url, filename): ...\n def _download_hg(self, url, filename): ...\n def debug(self, msg, *args): ...\n def info(self, msg, *args): ...\n def warn(self, msg, *args): ...\n\n self.index_url = index_url + '/'[:not index_url.endswith('/')]\n self.scanned_urls = {}\n self.fetched_urls = {}\n self.package_pages = {}\n self.allows = re.compile('|'.join(map(translate, hosts))).match\n self.to_scan = []\n\n dl_blocksize = 8192\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_url_ok", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002620.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "parse_bdist_wininst", "tests": "import unittest\n\nclass Test_parse_bdist_wininst(unittest.TestCase):\n def test_parse_bdist_wininst(self):\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win32-py2.4.exe'), ('reportlab-2.5', '2.4', 'win32'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win32.exe'), ('reportlab-2.5', None, 'win32'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win-amd64-py2.7.exe'), ('reportlab-2.5', '2.7', 'win-amd64'))\n self.assertEqual(setuptools.package_index.parse_bdist_wininst('reportlab-2.5.win-amd64.exe'), ('reportlab-2.5', None, 'win-amd64'))\n", "method_code": "def parse_bdist_wininst(name):\n \"\"\"Return (base,pyversion) or (None,None) for possible .exe name\"\"\"\n lower = name.lower()\n base, py_ver, plat = (None, None, None)\n if lower.endswith('.exe'):\n if lower.endswith('.win32.exe'):\n base = name[:-10]\n plat = 'win32'\n elif lower.startswith('.win32-py', -16):\n py_ver = name[-7:-4]\n base = name[:-16]\n plat = 'win32'\n elif lower.endswith('.win-amd64.exe'):\n base = name[:-14]\n plat = 'win-amd64'\n elif lower.startswith('.win-amd64-py', -20):\n py_ver = name[-7:-4]\n base = name[:-20]\n plat = 'win-amd64'\n return (base, py_ver, plat)", "context": "def parse_bdist_wininst(name): ...\ndef parse_bdist_wininst(name): ...\ndef egg_info_for_url(url): ...\ndef distros_for_url(url, metadata=None): ...\ndef distros_for_location(location, basename, metadata=None): ...\ndef distros_for_filename(filename, metadata=None): ...\ndef interpret_distro_name(location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None): ...\ndef unique_everseen(iterable, key=None): ...\ndef unique_values(func): ...\ndef find_external_links(url, page): ...\ndef uchr(c): ...\ndef decode_entity(match): ...\ndef htmldecode(text): ...\ndef socket_timeout(timeout=15): ...\ndef _encode_auth(auth): ...\ndef open_with_auth(url, opener=urllib2.urlopen): ...\ndef fix_sf_url(url): ...\ndef local_open(url): ...\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_parse_bdist_wininst", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002621.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/package_index.py", "focal_class": null, "focal_method": "report", "tests": "import unittest\n\nclass Test_report(unittest.TestCase):\n def test_report(self):\n checker = setuptools.package_index.HashChecker.from_url('http://foo/bar#md5=f12895fdffbd45007040d2e44df98478')\n rep = checker.report(lambda x: x, 'My message about %s')\n self.assertEqual(rep, 'My message about md5')\n", "method_code": " def report(self, reporter, template):\n \"\"\"\n Call reporter with information about the checker (hash name)\n substituted into the template.\n \"\"\"\n return\n ", "context": "class ContentChecker(object):\n def report(self, reporter, template): ...\n def feed(self, block): ...\n def is_valid(self): ...\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_report", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002622.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/easy_install.py", "focal_class": null, "focal_method": "get_script_header", "tests": "import unittest\n\nclass Test_get_script_header(unittest.TestCase):\n def test_get_script_header(self):\n if not sys.platform.startswith('java') or not is_sh(sys.executable):\n expected = '#!%s\\n' % nt_quote_arg(os.path.normpath(sys.executable))\n self.assertEqual(get_script_header('#!/usr/local/bin/python'), expected)\n expected = '#!%s -x\\n' % nt_quote_arg(os.path.normpath(sys.executable))\n self.assertEqual(get_script_header('#!/usr/bin/python -x'), expected)\n self.assertEqual(get_script_header('#!/usr/bin/python', executable=self.non_ascii_exe), '#!%s -x\\n' % self.non_ascii_exe)\n candidate = get_script_header('#!/usr/bin/python', executable=self.exe_with_spaces)\n self.assertEqual(candidate, '#!\"%s\"\\n' % self.exe_with_spaces)\n\n def test_get_script_header_jython_workaround(self):\n if sys.version_info >= (3,) and os.environ.get('LC_CTYPE') in (None, 'C', 'POSIX'):\n return\n\n class java:\n\n class lang:\n\n class System:\n\n @staticmethod\n def getProperty(property):\n return ''\n sys.modules['java'] = java\n platform = sys.platform\n sys.platform = 'java1.5.0_13'\n stdout, stderr = (sys.stdout, sys.stderr)\n try:\n exe = os.path.normpath(os.path.splitext(__file__)[0] + '.py')\n self.assertEqual(get_script_header('#!/usr/local/bin/python', executable=exe), '#!/usr/bin/env %s\\n' % exe)\n sys.stdout = sys.stderr = StringIO()\n self.assertEqual(get_script_header('#!/usr/bin/python -x', executable=exe), '#!%s -x\\n' % exe)\n self.assertTrue('Unable to adapt shebang line' in sys.stdout.getvalue())\n sys.stdout = sys.stderr = StringIO()\n self.assertEqual(get_script_header('#!/usr/bin/python', executable=self.non_ascii_exe), '#!%s -x\\n' % self.non_ascii_exe)\n self.assertTrue('Unable to adapt shebang line' in sys.stdout.getvalue())\n finally:\n del sys.modules['java']\n sys.platform = platform\n sys.stdout, sys.stderr = (stdout, stderr)\n", "method_code": "def get_script_header(script_text, executable=sys_executable, wininst=False):\n \"\"\"Create a #! line, getting options (if any) from script_text\"\"\"\n from distutils.command.build_scripts import first_line_re\n if not isinstance(first_line_re.pattern, str):\n first_line_re = re.compile(first_line_re.pattern.decode())\n first = (script_text + '\\n').splitlines()[0]\n match = first_line_re.match(first)\n options = ''\n if match:\n options = match.group(1) or ''\n if options:\n options = ' ' + options\n if wininst:\n executable = 'python.exe'\n else:\n executable = nt_quote_arg(executable)\n hdr = '#!%(executable)s%(options)s\\n' % locals()\n if not isascii(hdr):\n if options:\n if options.strip().startswith('-'):\n options = ' -x' + options.strip()[1:]\n else:\n options = ' -x'\n executable = fix_jython_executable(executable, options)\n hdr = '#!%(executable)s%(options)s\\n' % locals()\n return hdr", "context": "def get_script_header(script_text, executable=sys_executable, wininst=False): ...\ndef is_64bit(): ...\ndef samefile(p1, p2): ...\ndef get_site_dirs(): ...\ndef expand_paths(inputs): ...\ndef extract_wininst_cfg(dist_filename): ...\ndef get_exe_prefixes(exe_filename): ...\ndef parse_requirement_arg(spec): ...\ndef get_script_header(script_text, executable=sys_executable, wininst=False): ...\ndef auto_chmod(func, arg, exc): ...\ndef uncache_zipdir(path): ...\ndef _uncache(path, cache): ...\ndef is_python(text, filename=''): ...\ndef is_sh(executable): ...\ndef nt_quote_arg(arg): ...\ndef is_python_script(script_text, filename): ...\ndef chmod(path, mode): ...\ndef fix_jython_executable(executable, options): ...\ndef get_win_launcher(type): ...\ndef load_launcher_manifest(name): ...\ndef rmtree(path, ignore_errors=False, onerror=auto_chmod): ...\ndef current_umask(): ...\ndef bootstrap(): ...\ndef main(argv=None, **kw): ...\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_get_script_header", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002623.py"} {"focal_file": "myvenv/lib/python3.4/site-packages/setuptools/command/upload_docs.py", "focal_class": "upload_docs", "focal_method": "create_zipfile", "tests": "import unittest\n\nclass Test_upload_docs_create_zipfile(unittest.TestCase):\n def test_create_zipfile(self):\n dist = Distribution()\n cmd = upload_docs(dist)\n cmd.upload_dir = self.upload_dir\n cmd.target_dir = self.upload_dir\n tmp_dir = tempfile.mkdtemp()\n tmp_file = os.path.join(tmp_dir, 'foo.zip')\n try:\n zip_file = cmd.create_zipfile(tmp_file)\n assert zipfile.is_zipfile(tmp_file)\n zip_file = zipfile.ZipFile(tmp_file)\n assert zip_file.namelist() == ['index.html']\n zip_file.close()\n finally:\n shutil.rmtree(tmp_dir)\n", "method_code": " def create_zipfile(self, filename):\n zip_file = zipfile.ZipFile(filename, 'w')\n try:\n self.mkpath(self.target_dir)\n for root, dirs, files in os.walk(self.target_dir):\n if root == self.target_dir and (not files):\n raise DistutilsOptionError(\"no files found in upload directory '%s'\" % self.target_dir)\n for name in files:\n full = os.path.join(root, name)\n relative = root[len(self.target_dir):].lstrip(os.path.sep)\n dest = os.path.join(relative, name)\n zip_file.write(full, dest)\n finally:\n zip_file.close()\n ", "context": "class upload_docs(upload):\n def create_zipfile(self, filename): ...\n def has_sphinx(self): ...\n def initialize_options(self): ...\n def finalize_options(self): ...\n def run(self): ...\n def upload_file(self, filename): ...\n\n description = 'Upload documentation to PyPI'\n user_options = [('repository=', 'r', 'url of repository [default: %s]' % upload.DEFAULT_REPOSITORY), ('show-response', None, 'display full response text from server'), ('upload-dir=', None, 'directory to upload')]\n boolean_options = upload.boolean_options\n sub_commands = [('build_sphinx', has_sphinx)]\n", "repository": "Sagar-Madke/my-first-blog", "test_name": "test_create_zipfile", "smells": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002624.py"} {"focal_file": "server/src/Database_Layer/dbController.py", "focal_class": null, "focal_method": "saveRequest", "tests": "import unittest\n\nclass Test_saveRequest(unittest.TestCase):\n def test_saveRequest(self):\n self.controller.saveRequest(self.ride_id, self.event_id, self.username, self.status)\n self.cur.execute(' SELECT RIDE_ID, EVENT_ID, USERNAME, STATUS FROM RIDES_REQUESTED WHERE RIDE_ID=%s AND EVENT_ID=%s AND USERNAME=%s', (self.ride_id, self.event_id, self.username))\n result = self.cur.fetchall()[0]\n self.assertEqual(result[0], self.ride_id)\n self.assertEqual(result[1], self.event_id)\n self.assertEqual(result[2], self.username)\n self.assertEqual(result[3], self.status)\n self.cur.execute(' SELECT COUNT(*) FROM RIDES_REQUESTED WHERE RIDE_ID=%s AND EVENT_ID=%s AND USERNAME=%s', (self.ride_id, self.event_id, self.username))\n result = self.cur.fetchall()[0]\n self.assertEqual(result[0], 1)\n self.cur.execute(' DELETE FROM RIDES_REQUESTED WHERE RIDE_ID=%s AND EVENT_ID=%s AND USERNAME=%s', (self.ride_id, self.event_id, self.username))\n self.db.commit()\n\n def test_updateRequest(self):\n self.cur.execute(' SELECT STATUS FROM RIDES_REQUESTED WHERE REQUEST_ID=%s', self.request_id)\n before_status = self.cur.fetchall()[0][0]\n self.assertEqual(self.status, before_status)\n self.controller.saveRequest(self.request_id, self.status)\n self.cur.execute(' SELECT REQUEST_ID, STATUS FROM RIDES_REQUESTED WHERE REQUEST_ID=%s AND STATUS=%s', (self.request_id, self.status))\n result = self.cur.fetchall()[0]\n self.assertEqual(result[0], self.request_id)\n self.assertEqual(result[1], self.status)\n self.assertEqual(before_status, result)\n self.cur.execute(' SELECT COUNT(*) FROM RIDES_REQUESTED WHERE REQUEST_ID=%s AND STATUS=%s ', (self.request_id, self.status))\n result = self.cur.fetchall()[0]\n self.assertEqual(result[0], 1)\n self.cur.execute(' DELETE FROM RIDES_REQUESTED WHERE REQUEST_ID=%s AND STATUS=%s', (self.request_id, self.status))\n self.db.commit()\n", "method_code": " def saveRequest(self, RideID, eventID, userID, status):\n self.cursor.execute('INSERT INTO RIDES_REQUESTED (RIDE_ID,EVENT_ID,USERNAME,STATUS) VALUES(%s,%s,%s,%s)', (RideID, eventID, userID, status))\n self.mysql.commit()\n print('Data Saved!')\n ", "context": "class DBController():\n def saveRequest(self, RideID, eventID, userID, status): ...\n def __init__(self, cursor, mysql): ...\n def getUser(self, username): ...\n def updateRequest(self, requestId, status): ...\n def getrides_wo_username(self, eventId): ...\n def getrides_username(self, eventId, userId): ...\n def enterUser(self, data): ...\n def saveOfferRide(self, data): ...\n def Userlogin(self, email, password): ...\n\n self.cursor = cursor\n self.mysql = mysql\n", "repository": "SaurabhJ93/Event-Based-Carpooling", "test_name": "test_saveRequest", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002625.py"} {"focal_file": "server/src/Database_Layer/dbController.py", "focal_class": null, "focal_method": "saveOfferRide", "tests": "import unittest\n\nclass Test_saveOfferRide(unittest.TestCase):\n def test_saveOfferRide(self):\n response = self.controller.saveOfferRide(self.offerData)\n print(response)\n self.cur.execute('SELECT * FROM RIDES_OFFERED WHERE EVENT_ID=%s AND USERNAME=%s', (self.offerData['eventId'], self.offerData['username']))\n result = self.cur.fetchall()[0]\n print('result is:', result)\n self.assertEqual(result[0], self.offerData['eventId'])\n self.assertEqual(result[2], self.offerData['username'])\n self.assertEqual(result[3], self.offerData['carModel'])\n self.assertEqual(result[4], self.offerData['noOfSeats'])\n self.assertEqual(result[6], self.offerData['address1'])\n self.assertEqual(result[7], self.offerData['address2'])\n self.assertEqual(result[8], self.offerData['city'])\n self.assertEqual(result[9], self.offerData['state'])\n self.assertEqual(result[10], self.offerData['zipCode'])\n self.cur.execute(' DELETE FROM RIDES_OFFERED WHERE EVENT_ID=%s AND USERNAME=%s', (self.offerData['eventId'], self.offerData['username']))\n self.db.commit()\n", "method_code": " def saveOfferRide(self, data):\n try:\n event = SGE.Seat_Geek_Api()\n eventdata = event.getEvent(data['eventId'])\n print('data', data)\n eventDate = datetime.datetime.strptime(data['eventDate'], '%Y-%m-%d %H:%M:%S')\n temp_start_datetime = str(eventDate.date()) + ' ' + data['startTime'] + ':00'\n start_datetime = datetime.datetime.strptime(temp_start_datetime, '%Y-%m-%d %H:%M:%S')\n self.cursor.execute('select * from EVENTS where EVENT_ID =\"%s\"' % data['eventId'])\n response = self.cursor.fetchall()\n if not response:\n self.cursor.execute('INSERT INTO EVENTS (EVENT_ID,EVENT_NAME,FULL_ADDRESS,DESCRIPTION,PERFORMERS_NAMES,PERFORMERS_ID,VENUE_ID,DATE_TIME_LOCAL\\n ) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)', (eventdata['id'], eventdata['title'], eventdata['full_address'], eventdata['description'], eventdata['performers_names'], eventdata['performers_ids'], eventdata['venue_id'], eventdata['datetime_local']))\n self.cursor.execute('INSERT INTO RIDES_OFFERED (EVENT_ID,USERNAME,CAR_MODEL,NO_OF_SEATS,START_TIME,START_ADDRESS_LINE1,START_ADDRESS_LINE2,START_CITY,START_STATE,START_ZIP_CODE\\n ) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)', (data['eventId'], data['username'], data['carModel'], data['noOfSeats'], start_datetime, data['address1'], data['address2'], data['city'], data['state'], data['zipCode']))\n self.mysql.commit()\n print('Data Saved!')\n return 'Success'\n except Exception as e:\n return 'error:' + str(e)\n ", "context": "class DBController():\n def saveOfferRide(self, data): ...\n def __init__(self, cursor, mysql): ...\n def getUser(self, username): ...\n def saveRequest(self, RideID, eventID, userID, status): ...\n def updateRequest(self, requestId, status): ...\n def getrides_wo_username(self, eventId): ...\n def getrides_username(self, eventId, userId): ...\n def enterUser(self, data): ...\n def Userlogin(self, email, password): ...\n\n self.cursor = cursor\n self.mysql = mysql\n", "repository": "SaurabhJ93/Event-Based-Carpooling", "test_name": "test_saveOfferRide", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_002626.py"} {"focal_file": "ebdata/ebdata/nlp/tests/datelines.py", "focal_class": null, "focal_method": "assertDatelines", "tests": "import unittest\n\nclass Test_assertDatelines(unittest.TestCase):\n def test_start_of_line1(self):\n self.assertDatelines('blah blah\\nCHICAGO -- Something happened', ['CHICAGO'])\n\n def test_start_of_line2(self):\n self.assertDatelines('blah blah\\nCHICAGO -- Something happened', ['CHICAGO'])\n", "method_code": " def assertDatelines(self, text, expected):\n self.assertEqual(guess_datelines(text), expected)\n ", "context": "class DatelineTestCase(unittest.TestCase):\n def assertDatelines(self, text, expected): ...\n def test_basic1(self): ...\n def test_basic2(self): ...\n def test_basic3(self): ...\n def test_basic4(self): ...\n def test_lowercase1(self): ...\n def test_lowercase2(self): ...\n def test_emdash1(self): ...\n def test_emdash2(self): ...\n def test_emdash3(self): ...\n def test_emdash4(self): ...\n def test_emdash5(self): ...\n def test_emdash6(self): ...\n def test_html_entity_dash1(self): ...\n def test_html_entity_dash2(self): ...\n def test_html_entity_dash3(self): ...\n def test_multi_word_dateline1(self): ...\n def test_multi_word_dateline2(self): ...\n def test_comma_periods(self): ...\n def test_comma_no_space(self): ...\n def test_lowercase(self): ...\n def test_start_of_line1(self): ...\n def test_start_of_line2(self): ...\n def test_start_of_line_p(self): ...\n def test_start_of_line_div(self): ...\n def test_start_of_line_div_then_more1(self): ...\n def test_start_of_line_div_then_more2(self): ...\n def test_start_of_line_div_then_more3(self): ...\n def test_second_word_lowercase(self): ...\n def test_news_outlet_1(self): ...\n def test_news_outlet_2(self): ...\n def test_news_outlet_3(self): ...\n def test_news_outlet_4(self): ...\n def test_news_outlet_5(self): ...\n def test_news_outlet_6(self): ...\n def test_news_outlet_7(self): ...\n def test_news_outlet_8(self): ...\n def test_news_outlet_9(self): ...\n def test_news_outlet_10(self): ...\n def test_news_outlet_11(self): ...\n def test_news_outlet_12(self): ...\n def test_timestamp_prefix1(self): ...\n def test_timestamp_prefix2(self): ...\n def test_timestamp_prefix3(self): ...\n def test_timestamp_prefix4(self): ...\n def test_timestamp_prefix5(self): ...\n def test_timestamp_prefix6(self): ...\n def test_timestamp_prefix7(self): ...\n def test_timestamp_prefix8(self): ...\n", "repository": "goody/everyblock", "test_name": "test_start_of_line1", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002627.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "pensize", "tests": "import unittest\n\nclass Test_pensize(unittest.TestCase):\n def test_pensize(self):\n self.o.pensize(2)\n self.assertEqual(self.o.worker.pensize(), 2)\n self.o.pensize(4)\n self.assertEqual(self.o.worker.pensize(), 4)\n\n def test_pen_size(self):\n self.o.pensize(5)\n self.assertTrue(self.o.worker.pensize() == 5)\n", "method_code": " def pensize(self, size):\n self.worker.pensize(size)\n debug(f'pen size is {size}')\n ", "context": "class Drawer(AbstractDrawer):\n def pensize(self, size): ...\n def __init__(self, worker): ...\n def select_pen(self, pen): ...\n def pen_down(self): ...\n def pen_up(self): ...\n def pencolor(self, color): ...\n def go_along(self, along): ...\n def go_down(self, down): ...\n def goto(self, x, y): ...\n def forward(self, distance): ...\n def draw_line(self, direction, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_pensize", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002628.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "select_pen", "tests": "import unittest\n\nclass Test_select_pen(unittest.TestCase):\n def test_select_pen(self):\n self.o.select_pen(1)\n self.assertTrue(self.o.worker.pencolor() == 'black')\n self.assertTrue(self.o.worker.pensize() == 1)\n self.o.select_pen(2)\n self.assertTrue(self.o.worker.pencolor() == 'black')\n self.assertTrue(self.o.worker.pensize() == 2)\n r = self.o.select_pen(100)\n self.assertFalse(r)\n", "method_code": " def select_pen(self, pen):\n \"\"\"pen should be a integer from 1 to 9, every pen has a pencolor and pensize attribute\n \"\"\"\n pen = int(pen)\n if pen < 1 or pen > 9:\n debug(f'invalid pen: {pen}, should be a integer between 1 and 9')\n return False\n self.pensize(self.pen_list[pen - 1]['pensize'])\n self.pencolor(self.pen_list[pen - 1]['pencolor'])\n ", "context": "class Drawer(AbstractDrawer):\n def select_pen(self, pen): ...\n def __init__(self, worker): ...\n def pen_down(self): ...\n def pen_up(self): ...\n def pencolor(self, color): ...\n def pensize(self, size): ...\n def go_along(self, along): ...\n def go_down(self, down): ...\n def goto(self, x, y): ...\n def forward(self, distance): ...\n def draw_line(self, direction, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_select_pen", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002629.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "pen_down", "tests": "import unittest\n\nclass Test_pen_down(unittest.TestCase):\n def test_pen_down(self):\n self.o.pen_down()\n self.assertTrue(self.o.worker.isdown())\n", "method_code": " def pen_down(self):\n self.worker.pendown()\n debug('pen is down')\n ", "context": "class Drawer(AbstractDrawer):\n def pen_down(self): ...\n def __init__(self, worker): ...\n def select_pen(self, pen): ...\n def pen_up(self): ...\n def pencolor(self, color): ...\n def pensize(self, size): ...\n def go_along(self, along): ...\n def go_down(self, down): ...\n def goto(self, x, y): ...\n def forward(self, distance): ...\n def draw_line(self, direction, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_pen_down", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002630.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "pen_up", "tests": "import unittest\n\nclass Test_pen_up(unittest.TestCase):\n def test_pen_up(self):\n self.o.pen_up()\n self.assertFalse(self.o.worker.isdown())\n", "method_code": " def pen_up(self):\n self.worker.penup()\n debug('pen is up')\n ", "context": "class Drawer(AbstractDrawer):\n def pen_up(self): ...\n def __init__(self, worker): ...\n def select_pen(self, pen): ...\n def pen_down(self): ...\n def pencolor(self, color): ...\n def pensize(self, size): ...\n def go_along(self, along): ...\n def go_down(self, down): ...\n def goto(self, x, y): ...\n def forward(self, distance): ...\n def draw_line(self, direction, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_pen_up", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002631.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "pencolor", "tests": "import unittest\n\nclass Test_pencolor(unittest.TestCase):\n def test_pen_color(self):\n self.o.pencolor('blue')\n self.assertTrue(self.o.worker.pencolor() == 'blue')\n", "method_code": " def pencolor(self, color):\n self.worker.pencolor(color)\n debug(f'pen color is {color}')\n ", "context": "class Drawer(AbstractDrawer):\n def pencolor(self, color): ...\n def __init__(self, worker): ...\n def select_pen(self, pen): ...\n def pen_down(self): ...\n def pen_up(self): ...\n def pensize(self, size): ...\n def go_along(self, along): ...\n def go_down(self, down): ...\n def goto(self, x, y): ...\n def forward(self, distance): ...\n def draw_line(self, direction, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_pen_color", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002632.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "go_along", "tests": "import unittest\n\nclass Test_go_along(unittest.TestCase):\n def test_go_along(self):\n self.o.worker.setposition(400, 300)\n self.o.worker.setheading(90)\n self.o.go_along(100)\n self.assertTrue(self.o.worker.pos() == (500, 300))\n", "method_code": " def go_along(self, along):\n self.worker.go_along(int(along))\n debug(f'go along X: {along}')\n ", "context": "class Drawer(AbstractDrawer):\n def go_along(self, along): ...\n def __init__(self, worker): ...\n def select_pen(self, pen): ...\n def pen_down(self): ...\n def pen_up(self): ...\n def pencolor(self, color): ...\n def pensize(self, size): ...\n def go_down(self, down): ...\n def goto(self, x, y): ...\n def forward(self, distance): ...\n def draw_line(self, direction, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_go_along", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002633.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "go_down", "tests": "import unittest\n\nclass Test_go_down(unittest.TestCase):\n def test_go_down(self):\n self.o.worker.setposition(400, 300)\n self.o.go_down(100)\n self.assertTrue(self.o.worker.pos() == (400, 200))\n", "method_code": " def go_down(self, down):\n self.worker.go_down(int(down))\n debug(f'go along Y: {down}')\n ", "context": "class Drawer(AbstractDrawer):\n def go_down(self, down): ...\n def __init__(self, worker): ...\n def select_pen(self, pen): ...\n def pen_down(self): ...\n def pen_up(self): ...\n def pencolor(self, color): ...\n def pensize(self, size): ...\n def go_along(self, along): ...\n def goto(self, x, y): ...\n def forward(self, distance): ...\n def draw_line(self, direction, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_go_down", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002634.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "forward", "tests": "import unittest\n\nclass Test_forward(unittest.TestCase):\n def test_forward(self):\n self.o.worker.setposition(400, 300)\n self.o.worker.setheading(0)\n self.o.forward(100)\n self.assertTrue(self.o.worker.pos() == (500, 300))\n", "method_code": " def forward(self, distance):\n self.worker.forward(distance)\n debug(f'go along {distance} with direction {self.worker.heading}')\n ", "context": "class Drawer(AbstractDrawer):\n def forward(self, distance): ...\n def __init__(self, worker): ...\n def select_pen(self, pen): ...\n def pen_down(self): ...\n def pen_up(self): ...\n def pencolor(self, color): ...\n def pensize(self, size): ...\n def go_along(self, along): ...\n def go_down(self, down): ...\n def goto(self, x, y): ...\n def draw_line(self, direction, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_forward", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002635.py"} {"focal_file": "tigr/drawer/drawer.py", "focal_class": null, "focal_method": "draw_line", "tests": "import unittest\n\nclass Test_draw_line(unittest.TestCase):\n def test_draw_line(self):\n self.o.pen_up()\n self.o.draw_line(270, 100)\n self.assertTrue(self.o.worker.isdown())\n self.o.pen_up()\n self.o.draw_line(90, 100)\n self.assertTrue(self.o.worker.isdown())\n", "method_code": " def draw_line(self, direction, distance):\n self.worker.draw_line(int(direction), int(distance))\n debug(f'draw a line with length: {distance}, direction: {direction} degree.')\n ", "context": "class Drawer(AbstractDrawer):\n def draw_line(self, direction, distance): ...\n def __init__(self, worker): ...\n def select_pen(self, pen): ...\n def pen_down(self): ...\n def pen_up(self): ...\n def pencolor(self, color): ...\n def pensize(self, size): ...\n def go_along(self, along): ...\n def go_down(self, down): ...\n def goto(self, x, y): ...\n def forward(self, distance): ...\n def reset(self): ...\n def bye(self): ...\n\n self.worker = worker\n\n pen_list = [{'pencolor': 'black', 'pensize': 1}, {'pencolor': 'black', 'pensize': 2}, {'pencolor': 'black', 'pensize': 3}, {'pencolor': 'red', 'pensize': 1}, {'pencolor': 'red', 'pensize': 2}, {'pencolor': 'red', 'pensize': 3}, {'pencolor': 'blue', 'pensize': 1}, {'pencolor': 'blue', 'pensize': 2}, {'pencolor': 'blue', 'pensize': 3}]\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_draw_line", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002636.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "pencolor", "tests": "import unittest\n\nclass Test_pencolor(unittest.TestCase):\n def test_pencolor(self):\n self.o.pencolor('red')\n self.assertEqual(self.o._pencolor, 'red')\n self.o.pencolor('black')\n self.assertEqual(self.o._pencolor, 'black')\n", "method_code": " def pencolor(self, pencolor):\n self._pencolor = pencolor\n ", "context": "class TkinterWorker(tk.Tk):\n def pencolor(self, pencolor): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_pencolor", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002637.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "pensize", "tests": "import unittest\n\nclass Test_pensize(unittest.TestCase):\n def test_pensize(self):\n self.o.pensize(4)\n self.assertEqual(self.o._pensize, 4)\n self.o.pensize(6)\n self.assertEqual(self.o._pensize, 6)\n", "method_code": " def pensize(self, size):\n self._pensize = int(size)\n ", "context": "class TkinterWorker(tk.Tk):\n def pensize(self, size): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_pensize", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002638.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "draw_line", "tests": "import unittest\n\nclass Test_draw_line(unittest.TestCase):\n def test_draw_line(self):\n self.o.penup()\n self.o.draw_line(45, 100)\n self.assertFalse(self.o._pendown)\n self.o.pendown()\n self.o.draw_line(90, 100)\n self.assertTrue(self.o._pendown)\n", "method_code": " def draw_line(self, direction, distance):\n self._heading = direction + 90\n x, y = self._calc_target_pos(self._heading, distance)\n if not self._pendown:\n self.pendown()\n self._draw_line(x, y)\n self.penup()\n else:\n self._draw_line(x, y)\n ", "context": "class TkinterWorker(tk.Tk):\n def draw_line(self, direction, distance): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_draw_line", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002639.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "goto", "tests": "import unittest\n\nclass Test_goto(unittest.TestCase):\n def test_goto(self):\n self.o.goto(200, 100)\n self.assertTrue(self.o.pos['x'] == 200)\n self.assertTrue(self.o.pos['y'] == 100)\n", "method_code": " def goto(self, x, y):\n self.pos['x'] = x\n self.pos['y'] = y\n self.update()\n self.debug()\n ", "context": "class TkinterWorker(tk.Tk):\n def goto(self, x, y): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_goto", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002640.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "reset", "tests": "import unittest\n\nclass Test_reset(unittest.TestCase):\n def test_reset(self):\n self.o.goto(*self.o.home_pos)\n self.o.setheading(0)\n self.o.forward(100)\n self.o.reset()\n self.assertTrue(self.o.pos['x'] == 400)\n self.assertTrue(self.o.pos['y'] == 300)\n", "method_code": " def reset(self):\n for id in self.draw_history:\n self.canvas.after(0, self.canvas.delete, id)\n self.draw_history = []\n self._pencolor = self.init_config['pencolor']\n self._pensize = int(self.init_config['pensize'])\n self.speed(int(self.init_config['speed']))\n self.goto(*self.home_pos)\n self.update()\n ", "context": "class TkinterWorker(tk.Tk):\n def reset(self): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_reset", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002641.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "pendown", "tests": "import unittest\n\nclass Test_pendown(unittest.TestCase):\n def test_pendown(self):\n self.o.penup()\n self.assertFalse(self.o._pendown)\n self.o.pendown()\n self.assertTrue(self.o._pendown)\n", "method_code": " def pendown(self):\n self._pendown = True\n self.debug()\n ", "context": "class TkinterWorker(tk.Tk):\n def pendown(self): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_pendown", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002642.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "forward", "tests": "import unittest\n\nclass Test_forward(unittest.TestCase):\n def test_forward(self):\n self.o.goto(*self.o.home_pos)\n self.o.setheading(0)\n self.o.forward(100)\n self.assertTrue(int(self.o.pos['x']) == self.o.home_pos[0] + 100)\n self.o.setheading(90)\n self.o.forward(100)\n self.assertTrue(int(self.o.pos['y']) == self.o.home_pos[1] - 100)\n self.o.goto(*self.o.home_pos)\n self.o.penup()\n self.o.forward(-100)\n self.assertTrue(int(self.o.pos['y']) == self.o.home_pos[1] + 100)\n", "method_code": " def forward(self, length):\n x, y = self._calc_target_pos(self._heading, length)\n if self._pendown:\n self._draw_line(x, y)\n else:\n self.goto(x, y)\n self.update()\n self.debug()\n ", "context": "class TkinterWorker(tk.Tk):\n def forward(self, length): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_forward", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002643.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "setheading", "tests": "import unittest\n\nclass Test_setheading(unittest.TestCase):\n def test_setheading(self):\n self.o.setheading(100)\n self.assertTrue(self.o.heading == 100)\n", "method_code": " def setheading(self, direction):\n self._heading = direction + 90\n ", "context": "class TkinterWorker(tk.Tk):\n def setheading(self, direction): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_setheading", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002644.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "go_down", "tests": "import unittest\n\nclass Test_go_down(unittest.TestCase):\n def test_godown(self):\n self.o.goto(*self.o.home_pos)\n self.o.go_down(100)\n self.assertTrue(int(self.o.pos['y']) == self.o.home_pos[1] + 100)\n self.o.goto(*self.o.home_pos)\n self.o.go_down(-100)\n self.assertTrue(int(self.o.pos['y']) == self.o.home_pos[1] - 100)\n", "method_code": " def go_down(self, length):\n if length > 0:\n self._heading = 0\n else:\n self._heading = 180\n self.forward(abs(length))\n self.debug()\n ", "context": "class TkinterWorker(tk.Tk):\n def go_down(self, length): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_godown", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002645.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "speed", "tests": "import unittest\n\nclass Test_speed(unittest.TestCase):\n def test_speed(self):\n self.o.speed(3)\n wait_1 = self.o.wait\n self.o.speed(4)\n wait_2 = self.o.wait\n self.assertTrue(wait_1 > wait_2)\n", "method_code": " def speed(self, speed):\n wait = 1 / speed\n if speed <= 0:\n wait = 1\n self.wait = wait\n ", "context": "class TkinterWorker(tk.Tk):\n def speed(self, speed): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def go_along(self, along): ...\n def bye(self): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_speed", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002646.py"} {"focal_file": "tigr/drawer/tkinter_worker.py", "focal_class": null, "focal_method": "go_along", "tests": "import unittest\n\nclass Test_go_along(unittest.TestCase):\n def test_go_along(self):\n self.o.goto(*self.o.home_pos)\n self.o.go_along(100)\n self.assertTrue(tuple(self.o.pos.values()) == (500, 300))\n self.o.go_along(-100)\n self.assertTrue(tuple(self.o.pos.values()) == (400, 300))\n", "method_code": " def go_along(self, along):\n if along > 0:\n self._heading = 90\n else:\n self._heading = 270\n self.forward(abs(along))\n ", "context": "class TkinterWorker(tk.Tk):\n def go_along(self, along): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def reset(self): ...\n def setheading(self, direction): ...\n def penup(self): ...\n def pendown(self): ...\n def pensize(self, size): ...\n def go_down(self, length): ...\n def forward(self, length): ...\n def goto(self, x, y): ...\n def bye(self): ...\n def speed(self, speed): ...\n def pencolor(self, pencolor): ...\n def debug(self): ...\n def update(self): ...\n def draw_line(self, direction, distance): ...\n def _draw_line(self, x, y): ...\n def _calc_target_pos(self, direction, length): ...\n def heading(self): ...\n\n self.init_config = {'speed': speed, 'pencolor': pencolor, 'pensize': pensize}\n self._pencolor = str(pencolor)\n self._pensize = int(pensize)\n self.canvas = tk.Canvas(self, width=800, height=600)\n self.home_pos = (400, 300)\n self.pos = {'x': 400, 'y': 300}\n self._pendown = True\n self.draw_history = []\n\n name = 'tkinter'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_go_along", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002647.py"} {"focal_file": "tigr/drawer/turtle_worker.py", "focal_class": null, "focal_method": "go_down", "tests": "import unittest\n\nclass Test_go_down(unittest.TestCase):\n def test_go_down(self):\n self.o.setposition(400, 300)\n self.o.go_down(100)\n self.assertTrue(self.o.pos() == (400, 200))\n self.o.go_down(-100)\n self.assertTrue(self.o.pos() == (400, 300))\n", "method_code": " def go_down(self, length):\n if length > 0:\n heading = 270\n else:\n heading = 90\n self.setheading(heading)\n self.forward(abs(length))\n ", "context": "class TurtleWorker(Turtle):\n def go_down(self, length): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def go_along(self, along): ...\n def draw_line(self, direction, distance): ...\n def goto(self, x, y): ...\n def speed(self, speed): ...\n def bye(self): ...\n def pos(self): ...\n\n self.__name__ = 'turtle'\n\n name = 'turtle'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_go_down", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002648.py"} {"focal_file": "tigr/drawer/turtle_worker.py", "focal_class": null, "focal_method": "go_along", "tests": "import unittest\n\nclass Test_go_along(unittest.TestCase):\n def test_go_along(self):\n self.o.setposition(400, 300)\n self.o.go_along(100)\n self.assertTrue(self.o.pos() == (500, 300))\n self.o.go_along(-100)\n self.assertTrue(self.o.pos() == (400, 300))\n", "method_code": " def go_along(self, along):\n if along > 0:\n heading = 0\n else:\n heading = 180\n self.setheading(heading)\n self.forward(abs(along))\n ", "context": "class TurtleWorker(Turtle):\n def go_along(self, along): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def go_down(self, length): ...\n def draw_line(self, direction, distance): ...\n def goto(self, x, y): ...\n def speed(self, speed): ...\n def bye(self): ...\n def pos(self): ...\n\n self.__name__ = 'turtle'\n\n name = 'turtle'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_go_along", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002649.py"} {"focal_file": "tigr/drawer/turtle_worker.py", "focal_class": null, "focal_method": "draw_line", "tests": "import unittest\n\nclass Test_draw_line(unittest.TestCase):\n def test_draw_line(self):\n self.o.penup()\n self.o.draw_line(270, 100)\n self.assertTrue(self.o.isdown())\n self.o.penup()\n self.o.draw_line(90, 100)\n self.assertTrue(self.o.isdown())\n", "method_code": " def draw_line(self, direction, distance):\n self.pendown()\n self.setheading(direction)\n self.forward(distance)\n ", "context": "class TurtleWorker(Turtle):\n def draw_line(self, direction, distance): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def go_down(self, length): ...\n def go_along(self, along): ...\n def goto(self, x, y): ...\n def speed(self, speed): ...\n def bye(self): ...\n def pos(self): ...\n\n self.__name__ = 'turtle'\n\n name = 'turtle'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_draw_line", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002650.py"} {"focal_file": "tigr/drawer/turtle_worker.py", "focal_class": null, "focal_method": "goto", "tests": "import unittest\n\nclass Test_goto(unittest.TestCase):\n def test_goto(self):\n self.o.pendown()\n self.o.goto(400, 200)\n self.assertTrue(self.o.pos() == (0, 100))\n self.o.penup()\n self.o.goto(400, 400)\n self.assertTrue(self.o.pos() == (0, -100))\n", "method_code": " def goto(self, x, y):\n x -= 400\n if y > 300:\n y -= 2 * y - 300\n else:\n y = 300 - y\n if self.pen()['pendown']:\n self.penup()\n super().goto(x, y)\n self.pendown()\n else:\n super().goto(x, y)\n ", "context": "class TurtleWorker(Turtle):\n def goto(self, x, y): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def go_down(self, length): ...\n def go_along(self, along): ...\n def draw_line(self, direction, distance): ...\n def speed(self, speed): ...\n def bye(self): ...\n def pos(self): ...\n\n self.__name__ = 'turtle'\n\n name = 'turtle'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_goto", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002651.py"} {"focal_file": "tigr/drawer/turtle_worker.py", "focal_class": null, "focal_method": "speed", "tests": "import unittest\n\nclass Test_speed(unittest.TestCase):\n def test_speed(self):\n self.o.speed(3)\n self.assertEqual(self.o.pen()['speed'], 3)\n self.o.speed(100)\n self.assertEqual(self.o.pen()['speed'], 0)\n self.o.speed(-100)\n self.assertEqual(self.o.pen()['speed'], 1)\n", "method_code": " def speed(self, speed):\n speed = int(speed)\n if speed > 10:\n speed = 0\n elif speed <= 0:\n speed = 1\n super().speed(speed)\n ", "context": "class TurtleWorker(Turtle):\n def speed(self, speed): ...\n def __init__(self, speed=6, pencolor='black', pensize=2): ...\n def go_down(self, length): ...\n def go_along(self, along): ...\n def draw_line(self, direction, distance): ...\n def goto(self, x, y): ...\n def bye(self): ...\n def pos(self): ...\n\n self.__name__ = 'turtle'\n\n name = 'turtle'\n", "repository": "shukebeta/BCPR301-A1", "test_name": "test_speed", "smells": [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002652.py"} {"focal_file": "tasks/copy_files_to_archive/copy_files_to_archive.py", "focal_class": null, "focal_method": "get_files_from_records", "tests": "import unittest\n\nclass Test_get_files_from_records(unittest.TestCase):\n @patch('copy_files_to_archive.LOGGER')\n def test_get_files_from_records_adds_success_key(self, mock_logger: MagicMock):\n \"\"\"\n Function should transform json into file dict, and add 'success' key.\n \"\"\"\n file0 = {'job_id': uuid.uuid4().__str__(), 'granule_id': uuid.uuid4().__str__(), 'filename': uuid.uuid4().__str__(), 'source_key': uuid.uuid4().__str__(), 'target_key': uuid.uuid4().__str__(), 'restore_destination': uuid.uuid4().__str__(), 'source_bucket': uuid.uuid4().__str__()}\n file1 = {'job_id': uuid.uuid4().__str__(), 'granule_id': uuid.uuid4().__str__(), 'filename': uuid.uuid4().__str__(), 'source_key': uuid.uuid4().__str__(), 'target_key': uuid.uuid4().__str__(), 'restore_destination': uuid.uuid4().__str__(), 'source_bucket': uuid.uuid4().__str__()}\n result = copy_files_to_archive.get_files_from_records([{'body': json.dumps(file0.copy(), indent=4)}, {'body': json.dumps(file1.copy(), indent=4)}])\n file0[copy_files_to_archive.FILE_SUCCESS_KEY] = False\n file1[copy_files_to_archive.FILE_SUCCESS_KEY] = False\n self.assertEqual([file0, file1], result)\n", "method_code": "def get_files_from_records(records: List[Dict[str, Any]]) -> List[Dict[str, Union[str, bool]]]:\n \"\"\"\n Parses the input records and returns the files to be restored.\n Args:\n records: passed through from the handler.\n Returns:\n records, parsed into Dicts, with the additional KVP 'success' = False\n \"\"\"\n with open('schemas/sub_schemas/body.json', 'r') as raw_schema:\n schema = json.loads(raw_schema.read())\n validate = fastjsonschema.compile(schema)\n files = []\n for record in records:\n a_file = json.loads(record['body'])\n LOGGER.debug('Validating {file}', file=a_file)\n validate(a_file)\n a_file[FILE_SUCCESS_KEY] = False\n files.append(a_file)\n return files", "context": "def get_files_from_records(records: List[Dict[str, Any]]) -> List[Dict[str, Union[str, bool]]]: ...\ndef task(records: List[Dict[str, Any]], max_retries: int, retry_sleep_secs: float, db_queue_url: str) -> None: ...\ndef get_files_from_records(records: List[Dict[str, Any]]) -> List[Dict[str, Union[str, bool]]]: ...\ndef copy_object(s3_cli: BaseClient, src_bucket_name: str, src_object_name: str, dest_bucket_name: str, dest_object_name: str=None) -> Optional[str]: ...\ndef handler(event: Dict[str, Any], context: object) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002653.py"} {"focal_file": "tasks/db_deploy/create_db.py", "focal_class": null, "focal_method": "create_fresh_orca_install", "tests": "import unittest\n\nclass Test_create_fresh_orca_install(unittest.TestCase):\n @patch('create_db.create_recovery_objects')\n @patch('create_db.create_metadata_objects')\n @patch('create_db.set_search_path_and_role')\n @patch('create_db.create_app_schema_role_users')\n @patch('create_db.get_admin_connection')\n def test_create_fresh_orca_install_happy_path(self, mock_connection: MagicMock, mock_create_app_schema_roles: MagicMock, mock_set_search_path_role: MagicMock, mock_create_metadata: MagicMock, mock_create_recovery: MagicMock):\n \"\"\"\n Tests normal happy path of create_fresh_orca_install function.\n \"\"\"\n create_db.create_fresh_orca_install(self.config)\n mock_conn_enter = mock_connection().connect().__enter__()\n mock_create_app_schema_roles.assert_called_once_with(mock_conn_enter, self.config['app_user_password'])\n mock_set_search_path_role.assert_called_once_with(mock_conn_enter)\n mock_create_metadata.assert_called_once_with(mock_conn_enter)\n mock_create_recovery.assert_called_once_with(mock_conn_enter)\n mock_call_commit = mock_connection.mock_calls[3]\n mock_commit = call().connect().__enter__().commit()\n self.assertEqual(mock_call_commit, mock_commit)\n", "method_code": "def create_fresh_orca_install(config: Dict[str, str]) -> None:\n \"\"\"\n This task will create the ORCA roles, users, schema, and tables needed\n by the ORCA application as a fresh install.\n\n Args:\n config (Dict): Dictionary with database connection information\n\n Returns:\n None\n \"\"\"\n admin_app_connection = get_admin_connection(config, config['database'])\n with admin_app_connection.connect() as conn:\n create_app_schema_role_users(conn, config['app_user_password'])\n set_search_path_and_role(conn)\n create_metadata_objects(conn)\n create_recovery_objects(conn)\n conn.commit()", "context": "def create_fresh_orca_install(config: Dict[str, str]) -> None: ...\ndef create_fresh_orca_install(config: Dict[str, str]) -> None: ...\ndef create_app_schema_role_users(connection: Connection, app_password: str) -> None: ...\ndef set_search_path_and_role(connection: Connection) -> None: ...\ndef create_metadata_objects(connection: Connection) -> None: ...\ndef create_recovery_objects(connection: Connection) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002654.py"} {"focal_file": "tasks/db_deploy/create_db.py", "focal_class": null, "focal_method": "create_app_schema_role_users", "tests": "import unittest\n\nclass Test_create_app_schema_role_users(unittest.TestCase):\n @patch('create_db.app_user_sql')\n @patch('create_db.orca_schema_sql')\n @patch('create_db.app_role_sql')\n @patch('create_db.dbo_role_sql')\n def test_create_app_schema_user_role_users_happy_path(self, mock_dbo_role_sql: MagicMock, mock_app_role_sql: MagicMock, mock_schema_sql: MagicMock, mock_user_sql: MagicMock):\n \"\"\"\n Tests happy path of create_app_schema_role_users function.\n \"\"\"\n create_db.create_app_schema_role_users(self.mock_connection, self.config['app_user_password'])\n mock_dbo_role_sql.assert_called_once()\n mock_app_role_sql.assert_called_once()\n mock_schema_sql.assert_called_once()\n mock_user_sql.assert_called_once_with(self.config['app_user_password'])\n execution_order = [call.execute(mock_dbo_role_sql()), call.execute(mock_app_role_sql()), call.execute(mock_schema_sql()), call.execute(mock_user_sql(self.config['app_user_password']))]\n self.assertEqual(self.mock_connection.mock_calls, execution_order)\n", "method_code": "def create_app_schema_role_users(connection: Connection, app_password: str) -> None:\n \"\"\"\n Creates the ORCA application database schema, users and roles.\n\n Args:\n connection (sqlalchemy.future.Connection): Database connection.\n\n Returns:\n None\n \"\"\"\n logger.debug('Creating the ORCA dbo role ...')\n connection.execute(dbo_role_sql())\n logger.info('ORCA dbo role created.')\n logger.debug('Creating the ORCA app role ...')\n connection.execute(app_role_sql())\n logger.info('ORCA app role created.')\n logger.debug('Creating the ORCA schema ...')\n connection.execute(orca_schema_sql())\n logger.info('ORCA schema created.')\n logger.debug('Creating the ORCA application user ...')\n connection.execute(app_user_sql(app_password))\n logger.info('ORCA application user created.')", "context": "def create_app_schema_role_users(connection: Connection, app_password: str) -> None: ...\ndef create_fresh_orca_install(config: Dict[str, str]) -> None: ...\ndef create_app_schema_role_users(connection: Connection, app_password: str) -> None: ...\ndef set_search_path_and_role(connection: Connection) -> None: ...\ndef create_metadata_objects(connection: Connection) -> None: ...\ndef create_recovery_objects(connection: Connection) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002655.py"} {"focal_file": "tasks/db_deploy/create_db.py", "focal_class": null, "focal_method": "set_search_path_and_role", "tests": "import unittest\n\nclass Test_set_search_path_and_role(unittest.TestCase):\n @patch('create_db.text')\n def test_set_search_path_and_role(self, mock_text: MagicMock):\n \"\"\"\n Tests happy path of set_search_path_and_role function.\n \"\"\"\n create_db.set_search_path_and_role(self.mock_connection)\n mock_text.assert_any_call('SET ROLE orca_dbo;')\n mock_text.assert_any_call('SET search_path TO orca, public;')\n execution_order = [call.execute(mock_text('SET ROLE orca_dbo;')), call.execute(mock_text('SET search_path TO orca, public;'))]\n self.assertEqual(self.mock_connection.mock_calls, execution_order)\n", "method_code": "def set_search_path_and_role(connection: Connection) -> None:\n \"\"\"\n Sets the role to the dbo role to create/modify ORCA objects and sets the\n search_path to make the orca schema first. This must be run before any\n creations or modifications to ORCA objects in the ORCA schema.\n\n Args:\n connection (sqlalchemy.future.Connection): Database connection.\n\n Returns:\n None\n \"\"\"\n logger.debug('Changing to the dbo role to create objects ...')\n connection.execute(text('SET ROLE orca_dbo;'))\n logger.debug('Setting search path to the ORCA schema to create objects ...')\n connection.execute(text('SET search_path TO orca, public;'))", "context": "def set_search_path_and_role(connection: Connection) -> None: ...\ndef create_fresh_orca_install(config: Dict[str, str]) -> None: ...\ndef create_app_schema_role_users(connection: Connection, app_password: str) -> None: ...\ndef set_search_path_and_role(connection: Connection) -> None: ...\ndef create_metadata_objects(connection: Connection) -> None: ...\ndef create_recovery_objects(connection: Connection) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002656.py"} {"focal_file": "tasks/db_deploy/create_db.py", "focal_class": null, "focal_method": "create_metadata_objects", "tests": "import unittest\n\nclass Test_create_metadata_objects(unittest.TestCase):\n @patch('create_db.schema_versions_data_sql')\n @patch('create_db.schema_versions_table_sql')\n def test_create_metadata_objects(self, mock_schema_versions_table: MagicMock, mock_schema_versions_data: MagicMock):\n \"\"\"\n Tests happy path of create_metadata_objects function\n \"\"\"\n create_db.create_metadata_objects(self.mock_connection)\n mock_schema_versions_table.assert_called_once()\n mock_schema_versions_data.assert_called_once()\n execution_order = [call.execute(mock_schema_versions_table()), call.execute(mock_schema_versions_data())]\n self.assertEqual(self.mock_connection.mock_calls, execution_order)\n", "method_code": "def create_metadata_objects(connection: Connection) -> None:\n \"\"\"\n Create the ORCA application metadata tables used to manage application\n versions and other ORCA internal information in the proper order.\n - schema_versions\n\n Args:\n connection (sqlalchemy.future.Connection): Database connection.\n\n Returns:\n None\n \"\"\"\n logger.debug('Creating schema_versions table ...')\n connection.execute(schema_versions_table_sql())\n logger.info('schema_versions table created.')\n logger.debug('Populating the schema_versions table with data ...')\n connection.execute(schema_versions_data_sql())\n logger.info('Data added to the schema_versions table.')", "context": "def create_metadata_objects(connection: Connection) -> None: ...\ndef create_fresh_orca_install(config: Dict[str, str]) -> None: ...\ndef create_app_schema_role_users(connection: Connection, app_password: str) -> None: ...\ndef set_search_path_and_role(connection: Connection) -> None: ...\ndef create_metadata_objects(connection: Connection) -> None: ...\ndef create_recovery_objects(connection: Connection) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002657.py"} {"focal_file": "tasks/db_deploy/create_db.py", "focal_class": null, "focal_method": "create_recovery_objects", "tests": "import unittest\n\nclass Test_create_recovery_objects(unittest.TestCase):\n @patch('create_db.recovery_file_table_sql')\n @patch('create_db.recovery_job_table_sql')\n @patch('create_db.recovery_status_data_sql')\n @patch('create_db.recovery_status_table_sql')\n def test_create_recovery_objects(self, mock_recovery_status_table: MagicMock, mock_recovery_status_data: MagicMock, mock_recovery_job_table: MagicMock, mock_recovery_file_table: MagicMock):\n \"\"\"\n Tests happy path of the create_recovery_objects function\n \"\"\"\n create_db.create_recovery_objects(self.mock_connection)\n mock_recovery_status_table.assert_called_once()\n mock_recovery_status_data.assert_called_once()\n mock_recovery_job_table.assert_called_once()\n mock_recovery_file_table.assert_called_once()\n execution_order = [call.execute(mock_recovery_status_table()), call.execute(mock_recovery_status_data()), call.execute(mock_recovery_job_table()), call.execute(mock_recovery_file_table())]\n self.assertEqual(self.mock_connection.mock_calls, execution_order)\n", "method_code": "def create_recovery_objects(connection: Connection) -> None:\n \"\"\"\n Creates the ORCA recovery tables in the proper order.\n - recovery_status\n - recovery_job\n - recovery_table\n\n Args:\n connection (sqlalchemy.future.Connection): Database connection.\n\n Returns:\n None\n \"\"\"\n logger.debug('Creating recovery_status table ...')\n connection.execute(recovery_status_table_sql())\n logger.info('recovery_status table created.')\n logger.debug('Populating the recovery_status table with data ...')\n connection.execute(recovery_status_data_sql())\n logger.info('Data added to the recovery_status table.')\n logger.debug('Creating recovery_job table ...')\n connection.execute(recovery_job_table_sql())\n logger.info('recovery_job table created.')\n logger.debug('Creating recovery_file table ...')\n connection.execute(recovery_file_table_sql())\n logger.info('recovery_file table created.')", "context": "def create_recovery_objects(connection: Connection) -> None: ...\ndef create_fresh_orca_install(config: Dict[str, str]) -> None: ...\ndef create_app_schema_role_users(connection: Connection, app_password: str) -> None: ...\ndef set_search_path_and_role(connection: Connection) -> None: ...\ndef create_metadata_objects(connection: Connection) -> None: ...\ndef create_recovery_objects(connection: Connection) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002658.py"} {"focal_file": "tasks/db_deploy/db_deploy.py", "focal_class": null, "focal_method": "app_db_exists", "tests": "import unittest\n\nclass Test_app_db_exists(unittest.TestCase):\n def test_app_db_exists_happy_path(self):\n \"\"\"\n Does a happy path test for the function. No real logic to test.\n \"\"\"\n mock_conn = MagicMock()\n mock_conn.execute.return_value.fetchall.return_value = [[True]]\n db_exists = db_deploy.app_db_exists(mock_conn)\n self.assertEqual(db_exists, True)\n", "method_code": "def app_db_exists(connection: Connection) -> bool:\n \"\"\"\n Checks to see if the ORCA application database exists.\n\n Args:\n connection (sqlalchemy.future.Connection): Database connection object.\n\n Returns:\n True/False (bool): True if database exists.\n \"\"\"\n check_db_sql = text(\"\\n SELECT EXISTS(\\n SELECT\\n datname\\n FROM\\n pg_catalog.pg_database\\n WHERE\\n datname = 'disaster_recovery'\\n );\\n \")\n results = connection.execute(check_db_sql)\n for row in results.fetchall():\n db_exists = row[0]\n return db_exists", "context": "def app_db_exists(connection: Connection) -> bool: ...\ndef handler(event: Dict[str, Any], context: object) -> None: ...\ndef task(config: Dict[str, str]) -> None: ...\ndef app_db_exists(connection: Connection) -> bool: ...\ndef app_schema_exists(connection: Connection) -> bool: ...\ndef app_version_table_exists(connection: Connection) -> bool: ...\ndef get_migration_version(connection: Connection) -> int: ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_app_db_exists_happy_path", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002659.py"} {"focal_file": "tasks/db_deploy/db_deploy.py", "focal_class": null, "focal_method": "app_schema_exists", "tests": "import unittest\n\nclass Test_app_schema_exists(unittest.TestCase):\n def test_app_schema_exists_happy_path(self):\n \"\"\"\n Does a happy path test for the function. No real logic to test.\n \"\"\"\n mock_conn = MagicMock()\n mock_conn.execute.return_value.fetchall.return_value = [[True]]\n schema_exists = db_deploy.app_schema_exists(mock_conn)\n self.assertEqual(schema_exists, True)\n", "method_code": "def app_schema_exists(connection: Connection) -> bool:\n \"\"\"\n Checks to see if the ORCA application schema exists.\n\n Args:\n connection (sqlalchemy.future.Connection): Database connection object.\n\n Returns:\n True/False (bool): True if ORCA schema exists.\n \"\"\"\n check_schema_sql = text(\"\\n SELECT EXISTS(\\n SELECT\\n schema_name\\n FROM\\n information_schema.schemata\\n WHERE\\n schema_name in ('orca', 'dr')\\n );\\n \")\n results = connection.execute(check_schema_sql)\n for row in results.fetchall():\n schema_exists = row[0]\n return schema_exists", "context": "def app_schema_exists(connection: Connection) -> bool: ...\ndef handler(event: Dict[str, Any], context: object) -> None: ...\ndef task(config: Dict[str, str]) -> None: ...\ndef app_db_exists(connection: Connection) -> bool: ...\ndef app_schema_exists(connection: Connection) -> bool: ...\ndef app_version_table_exists(connection: Connection) -> bool: ...\ndef get_migration_version(connection: Connection) -> int: ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_app_schema_exists_happy_path", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002660.py"} {"focal_file": "tasks/db_deploy/db_deploy.py", "focal_class": null, "focal_method": "app_version_table_exists", "tests": "import unittest\n\nclass Test_app_version_table_exists(unittest.TestCase):\n def test_app_versions_table_exists_happy_path(self):\n \"\"\"\n Does a happy path test for the function. No real logic to test.\n \"\"\"\n mock_conn = MagicMock()\n mock_conn.execute.return_value.fetchall.return_value = [[True]]\n table_exists = db_deploy.app_version_table_exists(mock_conn)\n self.assertEqual(table_exists, True)\n", "method_code": "def app_version_table_exists(connection: Connection) -> bool:\n \"\"\"\n Checks to see if the orca.schema_version table exists.\n\n Args:\n connection (sqlalchemy.future.Connection): Database connection object.\n\n Returns:\n True/False (bool): True if ORCA schema_version table exists.\n \"\"\"\n check_versions_table_sql = text(\"\\n SELECT EXISTS (\\n SELECT\\n table_name\\n FROM\\n information_schema.tables\\n WHERE\\n table_schema = 'orca'\\n AND\\n table_name = 'schema_versions'\\n )\\n \")\n logger.debug('Checking for schema_versions table.')\n results = connection.execute(check_versions_table_sql)\n for row in results.fetchall():\n table_exists = row[0]\n logger.debug(f'schema_versions table exists {table_exists}')\n return table_exists", "context": "def app_version_table_exists(connection: Connection) -> bool: ...\ndef handler(event: Dict[str, Any], context: object) -> None: ...\ndef task(config: Dict[str, str]) -> None: ...\ndef app_db_exists(connection: Connection) -> bool: ...\ndef app_schema_exists(connection: Connection) -> bool: ...\ndef app_version_table_exists(connection: Connection) -> bool: ...\ndef get_migration_version(connection: Connection) -> int: ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_app_versions_table_exists_happy_path", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_002661.py"} {"focal_file": "tasks/db_deploy/db_deploy.py", "focal_class": null, "focal_method": "get_migration_version", "tests": "import unittest\n\nclass Test_get_migration_version(unittest.TestCase):\n @patch('db_deploy.app_version_table_exists')\n def test_get_migration_version_happy_path(self, mock_table_exists):\n \"\"\"\n Does a happy path test for the function. No real logic to test.\n \"\"\"\n mock_conn = MagicMock()\n table_exists_array = [True, False]\n mock_conn.execute.return_value.fetchall.return_value = [[2]]\n for table_exists in table_exists_array:\n with self.subTest(table_exists=table_exists):\n mock_table_exists.return_value = table_exists\n schema_version = db_deploy.get_migration_version(mock_conn)\n if table_exists:\n self.assertEqual(schema_version, 2)\n else:\n self.assertEqual(schema_version, 1)\n", "method_code": "def get_migration_version(connection: Connection) -> int:\n \"\"\"\n Queries the database version table and returns the latest version.\n\n Args:\n connection (sqlalchemy.future.Connection): Database connection object.\n\n Returns:\n Schema Version (int): Version number of the currently installed ORCA schema\n \"\"\"\n schema_version = 1\n orca_schema_version_sql = text('\\n SELECT\\n version_id\\n FROM\\n orca.schema_versions\\n WHERE\\n is_latest = True\\n ')\n if app_version_table_exists(connection):\n logger.debug('Getting current schema version from table.')\n results = connection.execute(orca_schema_version_sql)\n for row in results.fetchall():\n schema_version = row[0]\n return schema_version", "context": "def get_migration_version(connection: Connection) -> int: ...\ndef handler(event: Dict[str, Any], context: object) -> None: ...\ndef task(config: Dict[str, str]) -> None: ...\ndef app_db_exists(connection: Connection) -> bool: ...\ndef app_schema_exists(connection: Connection) -> bool: ...\ndef app_version_table_exists(connection: Connection) -> bool: ...\ndef get_migration_version(connection: Connection) -> int: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002662.py"} {"focal_file": "tasks/db_deploy/migrate_db.py", "focal_class": null, "focal_method": "perform_migration", "tests": "import unittest\n\nclass Test_perform_migration(unittest.TestCase):\n @patch('migrate_db.migrate_versions_1_to_2')\n def test_perform_migration_happy_path(self, mock_migrate_v1_to_v2: MagicMock):\n \"\"\"\n Tests the perform_migration function happy paths\n \"\"\"\n for version in [1, 2, 3]:\n with self.subTest(version=version):\n migrate_db.perform_migration(version, self.config)\n if version == 1:\n mock_migrate_v1_to_v2.assert_called_once_with(self.config, True)\n if version >= 2:\n mock_migrate_v1_to_v2.assert_not_called()\n mock_migrate_v1_to_v2.reset_mock()\n", "method_code": "def perform_migration(current_schema_version: int, config: Dict[str, str]) -> None:\n \"\"\"\n Performs a migration of the ORCA database. Determines the order and\n migrations to run.\n\n Args:\n current_schema_version (int): Current version of the ORCA schema\n config (Dict): Dictionary containing database connection information\n\n Returns:\n None\n \"\"\"\n if current_schema_version == 1:\n migrate_versions_1_to_2(config, True)", "context": "def perform_migration(current_schema_version: int, config: Dict[str, str]) -> None: ...\ndef perform_migration(current_schema_version: int, config: Dict[str, str]) -> None: ...\ndef migrate_versions_1_to_2(config: Dict[str, str], is_latest_version: bool) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002663.py"} {"focal_file": "tasks/db_deploy/migrate_db.py", "focal_class": null, "focal_method": "migrate_versions_1_to_2", "tests": "import unittest\n\nclass Test_migrate_versions_1_to_2(unittest.TestCase):\n @patch('migrate_db.schema_versions_data_sql')\n @patch('migrate_db.drop_druser_user_sql')\n @patch('migrate_db.drop_dbo_user_sql')\n @patch('migrate_db.drop_dr_role_sql')\n @patch('migrate_db.drop_drdbo_role_sql')\n @patch('migrate_db.drop_dr_schema_sql')\n @patch('migrate_db.drop_request_status_table_sql')\n @patch('migrate_db.migrate_recovery_file_data_sql')\n @patch('migrate_db.migrate_recovery_job_data_sql')\n @patch('migrate_db.recovery_status_data_sql')\n @patch('migrate_db.recovery_file_table_sql')\n @patch('migrate_db.recovery_job_table_sql')\n @patch('migrate_db.recovery_status_table_sql')\n @patch('migrate_db.schema_versions_table_sql')\n @patch('migrate_db.text')\n @patch('migrate_db.app_user_sql')\n @patch('migrate_db.orca_schema_sql')\n @patch('migrate_db.app_role_sql')\n @patch('migrate_db.dbo_role_sql')\n @patch('migrate_db.get_admin_connection')\n def test_migrate_versions_1_to_2_happy_path(self, mock_connection: MagicMock, mock_dbo_role_sql: MagicMock, mock_app_role_sql: MagicMock, mock_orca_schema_sql: MagicMock, mock_app_user_sql: MagicMock, mock_text: MagicMock, mock_schema_versions_table: MagicMock, mock_recovery_status_table: MagicMock, mock_recovery_job_table: MagicMock, mock_recovery_file_table: MagicMock, mock_recovery_status_data: MagicMock, mock_recovery_job_data: MagicMock, mock_recovery_file_data: MagicMock, mock_drop_request_status_table: MagicMock, mock_drop_dr_schema: MagicMock, mock_drop_drdbo_role: MagicMock, mock_drop_dr_role: MagicMock, mock_drop_dbo_user: MagicMock, mock_drop_druser_user: MagicMock, mock_schema_versions_data: MagicMock):\n \"\"\"\n Tests the migrate_versions_1_to_2 function happy path\n \"\"\"\n for latest_version in [True, False]:\n with self.subTest(latest_version=latest_version):\n mock_conn_enter = mock_connection().connect().__enter__()\n migrate_db.migrate_versions_1_to_2(self.config, latest_version)\n mock_connection.assert_any_call(self.config, self.config['database'])\n mock_dbo_role_sql.assert_called_once()\n mock_app_role_sql.assert_called_once()\n mock_orca_schema_sql.assert_called_once()\n mock_app_user_sql.assert_called_once_with(self.config['app_user_password'])\n mock_schema_versions_table.assert_called_once()\n mock_recovery_status_table.assert_called_once()\n mock_recovery_job_table.assert_called_once()\n mock_recovery_file_table.assert_called_once()\n mock_recovery_status_data.assert_called_once()\n mock_recovery_job_data.assert_called_once()\n mock_recovery_file_data.assert_called_once()\n mock_drop_request_status_table.assert_called_once()\n mock_drop_dr_schema.assert_called_once()\n mock_drop_drdbo_role.assert_called_once()\n mock_drop_dr_role.assert_called_once()\n mock_drop_dbo_user.assert_called_once()\n mock_drop_druser_user.assert_called_once()\n text_calls = [call('SET ROLE orca_dbo;'), call('SET search_path TO orca, public;'), call('RESET ROLE;'), call('SET search_path TO orca, dr, public;'), call('SET ROLE dbo;'), call('RESET ROLE;')]\n mock_text.assert_has_calls(text_calls, any_order=False)\n if latest_version:\n mock_schema_versions_data.assert_called_once()\n execution_order = [call.execute(mock_dbo_role_sql()), call.execute(mock_app_role_sql()), call.execute(mock_orca_schema_sql()), call.execute(mock_app_user_sql(self.config['app_user_password'])), call.execute(mock_text('SET ROLE orca_dbo;')), call.execute(mock_text('SET search_path TO orca, public;')), call.execute(mock_schema_versions_table()), call.execute(mock_recovery_status_table()), call.execute(mock_recovery_job_table()), call.execute(mock_recovery_file_table()), call.commit(), call.execute(mock_text('RESET ROLE;')), call.execute(mock_text('SET search_path TO orca, dr, public;')), call.execute(mock_recovery_status_data()), call.execute(mock_recovery_job_data()), call.execute(mock_recovery_file_data()), call.execute(mock_drop_request_status_table()), call.execute(mock_text('SET ROLE dbo;')), call.execute(mock_drop_dr_schema()), call.execute(mock_text('RESET ROLE;')), call.execute(mock_drop_drdbo_role()), call.execute(mock_drop_dr_role()), call.execute(mock_drop_dbo_user()), call.execute(mock_drop_druser_user()), call.execute(mock_schema_versions_data()), call.commit()]\n else:\n mock_schema_versions_data.assert_not_called()\n execution_order = [call.execute(mock_dbo_role_sql()), call.execute(mock_app_role_sql()), call.execute(mock_orca_schema_sql()), call.execute(mock_app_user_sql(self.config['app_user_password'])), call.execute(mock_text('SET ROLE orca_dbo;')), call.execute(mock_text('SET search_path TO orca, public;')), call.execute(mock_schema_versions_table()), call.execute(mock_recovery_status_table()), call.execute(mock_recovery_job_table()), call.execute(mock_recovery_file_table()), call.commit(), call.execute(mock_text('RESET ROLE;')), call.execute(mock_text('SET search_path TO orca, dr, public;')), call.execute(mock_recovery_status_data()), call.execute(mock_recovery_job_data()), call.execute(mock_recovery_file_data()), call.execute(mock_drop_request_status_table()), call.execute(mock_text('SET ROLE dbo;')), call.execute(mock_drop_dr_schema()), call.execute(mock_text('RESET ROLE;')), call.execute(mock_drop_drdbo_role()), call.execute(mock_drop_dr_role()), call.execute(mock_drop_dbo_user()), call.execute(mock_drop_druser_user()), call.commit()]\n mock_conn_enter.assert_has_calls(execution_order, any_order=False)\n mock_connection.reset_mock()\n mock_dbo_role_sql.reset_mock()\n mock_app_role_sql.reset_mock()\n mock_orca_schema_sql.reset_mock()\n mock_app_user_sql.reset_mock()\n mock_schema_versions_table.reset_mock()\n mock_recovery_status_table.reset_mock()\n mock_recovery_job_table.reset_mock()\n mock_recovery_file_table.reset_mock()\n mock_recovery_status_data.reset_mock()\n mock_recovery_job_data.reset_mock()\n mock_recovery_file_data.reset_mock()\n mock_drop_request_status_table.reset_mock()\n mock_drop_dr_schema.reset_mock()\n mock_drop_drdbo_role.reset_mock()\n mock_drop_dr_role.reset_mock()\n mock_drop_dbo_user.reset_mock()\n mock_drop_druser_user.reset_mock()\n mock_schema_versions_data.reset_mock()\n mock_text.reset_mock()\n", "method_code": "def migrate_versions_1_to_2(config: Dict[str, str], is_latest_version: bool) -> None:\n \"\"\"\n Performs the migration of the ORCA schema from version 1 to version 2 of\n the ORCA schema.\n\n Args:\n config (Dict): Connection information for the database.\n is_latest_version (bool): Flag to dtermine if version 2 is the latest schema version.\n\n Returns:\n None\n \"\"\"\n admin_app_connection = get_admin_connection(config, config['database'])\n with admin_app_connection.connect() as connection:\n logger.debug('Creating the ORCA dbo role ...')\n connection.execute(dbo_role_sql())\n logger.info('ORCA dbo role created.')\n logger.debug('Creating the ORCA app role ...')\n connection.execute(app_role_sql())\n logger.info('ORCA app role created.')\n logger.debug('Creating the ORCA schema ...')\n connection.execute(orca_schema_sql())\n logger.info('ORCA schema created.')\n logger.debug('Creating the ORCA application user ...')\n connection.execute(app_user_sql(config['app_user_password']))\n logger.info('ORCA application user created.')\n logger.debug('Changing to the dbo role to create objects ...')\n connection.execute(text('SET ROLE orca_dbo;'))\n logger.debug('Setting search path to the ORCA schema to create objects ...')\n connection.execute(text('SET search_path TO orca, public;'))\n logger.debug('Creating schema_versions table ...')\n connection.execute(schema_versions_table_sql())\n logger.info('schema_versions table created.')\n logger.debug('Creating recovery_status table ...')\n connection.execute(recovery_status_table_sql())\n logger.info('recovery_status table created.')\n logger.debug('Creating recovery_job table ...')\n connection.execute(recovery_job_table_sql())\n logger.info('recovery_job table created.')\n logger.debug('Creating recovery_file table ...')\n connection.execute(recovery_file_table_sql())\n logger.info('recovery_file table created.')\n connection.commit()\n with admin_app_connection.connect() as connection:\n logger.debug('Changing to the postgres role ...')\n connection.execute(text('RESET ROLE;'))\n logger.debug('Setting search path to the ORCA and dr schema ...')\n connection.execute(text('SET search_path TO orca, dr, public;'))\n logger.debug('Populating the recovery_status table with data ...')\n connection.execute(recovery_status_data_sql())\n logger.info('Data added to the recovery_status table.')\n logger.debug('Migrating data from request_status to recovery_job ...')\n connection.execute(migrate_recovery_job_data_sql())\n logger.info('Data migrated to recovery_job table.')\n logger.debug('Migrating data from request_status to recovery_file ...')\n connection.execute(migrate_recovery_file_data_sql())\n logger.info('Data migrated to recovery_file table.')\n logger.debug('Dropping dr.request_status table ...')\n connection.execute(drop_request_status_table_sql())\n logger.info('dr.request_status table removed.')\n logger.debug('Changing to the dbo role ...')\n connection.execute(text('SET ROLE dbo;'))\n logger.debug('Dropping dr schema ...')\n connection.execute(drop_dr_schema_sql())\n logger.info('dr schema removed.')\n logger.debug('Changing to the postgres role ...')\n connection.execute(text('RESET ROLE;'))\n logger.debug('Dropping drdbo_role role ...')\n connection.execute(drop_drdbo_role_sql())\n logger.info('drdbo_role role removed.')\n logger.debug('Dropping dr_role role ...')\n connection.execute(drop_dr_role_sql())\n logger.info('dr_role role removed.')\n logger.debug('Dropping dbo user ...')\n connection.execute(drop_dbo_user_sql())\n logger.info('dbo user removed')\n logger.debug('Dropping druser user ...')\n connection.execute(drop_druser_user_sql())\n logger.info('druser user removed.')\n if is_latest_version:\n logger.debug('Populating the schema_versions table with data ...')\n connection.execute(schema_versions_data_sql())\n logger.info('Data added to the schema_versions table.')\n connection.commit()", "context": "def migrate_versions_1_to_2(config: Dict[str, str], is_latest_version: bool) -> None: ...\ndef perform_migration(current_schema_version: int, config: Dict[str, str]) -> None: ...\ndef migrate_versions_1_to_2(config: Dict[str, str], is_latest_version: bool) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002664.py"} {"focal_file": "tasks/db_deploy/orca_sql.py", "focal_class": null, "focal_method": "app_user_sql", "tests": "import unittest\n\nclass Test_app_user_sql(unittest.TestCase):\n def test_app_user_sql_happy_path(self) -> None:\n \"\"\"\n Tests the happy path for the app_user_sql function and validates the\n user password is a part of the SQL.\n \"\"\"\n user_pass = 'MySup3rL0ngPassForAUser'\n user_sql = orca_sql.app_user_sql(user_pass)\n self.assertIn(user_pass, user_sql.text)\n self.assertEqual(type(user_sql), TextClause)\n\n def test_app_user_sql_exceptions(self) -> None:\n \"\"\"\n Tests that an exception is thrown if the password is not set or is not\n a minimum of 12 characters.\n \"\"\"\n bad_passwords = [None, '', 'abc123', '1234567890', 'AbCdEfG1234']\n message = 'Password not long enough.'\n for bad_password in bad_passwords:\n with self.subTest(bad_password=bad_password):\n with self.assertRaises(Exception) as ex:\n orca_sql.app_user_sql(bad_password)\n self.assertEquals(ex.message, message)\n", "method_code": "def app_user_sql(user_password: str) -> TextClause:\n \"\"\"\n Full SQL for creating the ORCA application database user. Must be created\n after the app_role_sql and orca_schema_sql.\n\n Args:\n user_password (str): Password for the application user\n\n Returns:\n (sqlalchemy.sql.element.TextClause): SQL for creating orcauser user.\n \"\"\"\n if user_password is None or len(user_password) < 12:\n logger.critical('User password must be at least 12 characters long.')\n raise Exception('Password not long enough.')\n return text(f\"\\n DO\\n $$\\n BEGIN\\n IF NOT EXISTS (SELECT 1 FROM pg_user WHERE usename = 'orcauser' ) THEN\\n -- Create orcauser\\n CREATE ROLE orcauser\\n LOGIN\\n INHERIT\\n ENCRYPTED PASSWORD '{user_password}'\\n IN ROLE orca_app;\\n\\n -- Add comment\\n COMMENT ON ROLE orcauser\\n IS 'ORCA application user.';\\n\\n RAISE NOTICE 'USER CREATED orcauser. PLEASE UPDATE THE USERS PASSWORD!';\\n\\n END IF;\\n\\n -- Alter the roles search path so on login it has what it needs for a path\\n ALTER ROLE orcauser SET search_path = orca, public;\\n END\\n $$;\\n \")", "context": "def app_user_sql(user_password: str) -> TextClause: ...\ndef app_database_sql() -> TextClause: ...\ndef dbo_role_sql() -> TextClause: ...\ndef app_role_sql() -> TextClause: ...\ndef orca_schema_sql() -> TextClause: ...\ndef app_user_sql(user_password: str) -> TextClause: ...\ndef schema_versions_table_sql() -> TextClause: ...\ndef schema_versions_data_sql() -> TextClause: ...\ndef recovery_status_table_sql() -> TextClause: ...\ndef recovery_status_data_sql() -> TextClause: ...\ndef recovery_job_table_sql() -> TextClause: ...\ndef recovery_file_table_sql() -> TextClause: ...\ndef migrate_recovery_job_data_sql() -> TextClause: ...\ndef migrate_recovery_file_data_sql() -> TextClause: ...\ndef drop_request_status_table_sql() -> TextClause: ...\ndef drop_dr_schema_sql() -> TextClause: ...\ndef drop_druser_user_sql() -> TextClause: ...\ndef drop_dbo_user_sql() -> TextClause: ...\ndef drop_dr_role_sql() -> TextClause: ...\ndef drop_drdbo_role_sql() -> TextClause: ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_app_user_sql_happy_path", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002665.py"} {"focal_file": "tasks/pg_utils/database.py", "focal_class": null, "focal_method": "get_utc_now_iso", "tests": "import unittest\n\nclass Test_get_utc_now_iso(unittest.TestCase):\n def test_get_utc_now_iso(self):\n \"\"\"\n Tests the get_utc_now_iso function\n \"\"\"\n utc_now_exp = '2019-07-17T17:36:38.494918'\n utc_now_exp = datetime.datetime.utcnow().isoformat()\n database.get_utc_now_iso = Mock(return_value=utc_now_exp)\n self.assertEqual(utc_now_exp, database.get_utc_now_iso())\n", "method_code": "def get_utc_now_iso() -> str:\n \"\"\"\n Takes the current utc timestamp and returns it an isoformat string.\n\n Returns:\n An isoformat string.\n ex. '2019-07-17T17:36:38.494918'\n \"\"\"\n return datetime.datetime.utcnow().isoformat()", "context": "def get_utc_now_iso() -> str: ...\ndef get_utc_now_iso() -> str: ...\ndef uuid_generator() -> str: ...\ndef result_to_json(result_rows): ...\ndef myconverter(obj: any) -> Optional[str]: ...\ndef get_connection(dbconnect_info: Dict[str, Union[str, int]]) -> connection: ...\ndef get_cursor(dbconnect_info: Dict[str, Union[str, int]]) -> cursor: ...\ndef single_query(sql_stmt, dbconnect_info: Dict[str, Union[str, int]], params=None) -> List[Tuple]: ...\ndef read_db_connect_info(param_source): ...\ndef get_db_connect_info(env_or_secretsmanager: str, param_name: str) -> str: ...\ndef multi_query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef _query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef return_connection(dbconnect_info) -> connection: ...\ndef return_cursor(conn: connection) -> cursor: ...\ndef query_no_params(db_cursor: cursor, sql_stmt) -> str: ...\ndef query_from_file(db_cursor: cursor, sql_file): ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_get_utc_now_iso", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002666.py"} {"focal_file": "tasks/pg_utils/database.py", "focal_class": null, "focal_method": "uuid_generator", "tests": "import unittest\n\nclass Test_uuid_generator(unittest.TestCase):\n def test_uuid_generator(self):\n \"\"\"\n Tests the uuid_generator function\n \"\"\"\n database.uuid_generator = Mock(return_value=UUID1)\n self.assertEqual(UUID1, database.uuid_generator())\n", "method_code": "def uuid_generator() -> str:\n \"\"\"\n Generates a unique UUID.\n\n Returns:\n A string representing a UUID.\n ex. '0000a0a0-a000-00a0-00a0-0000a0000000'\n \"\"\"\n my_uuid = uuid.uuid4()\n return str(my_uuid)", "context": "def uuid_generator() -> str: ...\ndef get_utc_now_iso() -> str: ...\ndef uuid_generator() -> str: ...\ndef result_to_json(result_rows): ...\ndef myconverter(obj: any) -> Optional[str]: ...\ndef get_connection(dbconnect_info: Dict[str, Union[str, int]]) -> connection: ...\ndef get_cursor(dbconnect_info: Dict[str, Union[str, int]]) -> cursor: ...\ndef single_query(sql_stmt, dbconnect_info: Dict[str, Union[str, int]], params=None) -> List[Tuple]: ...\ndef read_db_connect_info(param_source): ...\ndef get_db_connect_info(env_or_secretsmanager: str, param_name: str) -> str: ...\ndef multi_query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef _query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef return_connection(dbconnect_info) -> connection: ...\ndef return_cursor(conn: connection) -> cursor: ...\ndef query_no_params(db_cursor: cursor, sql_stmt) -> str: ...\ndef query_from_file(db_cursor: cursor, sql_file): ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_uuid_generator", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002667.py"} {"focal_file": "tasks/pg_utils/database.py", "focal_class": null, "focal_method": "get_connection", "tests": "import unittest\n\nclass Test_get_connection(unittest.TestCase):\n def test_get_connection(self):\n \"\"\"\n Tests getting a database connection\n \"\"\"\n db_connect_info = {'db_host': os.environ['DATABASE_HOST'], 'db_port': os.environ['DATABASE_PORT'], 'db_name': os.environ['DATABASE_NAME'], 'db_user': os.environ['DATABASE_USER'], 'db_pw': os.environ['DATABASE_PW']}\n con = database.get_connection(db_connect_info)\n self.assertIsNotNone(con)\n", "method_code": "def get_connection(dbconnect_info: Dict[str, Union[str, int]]) -> connection:\n \"\"\"\n Retrieves a connection from the connection pool and yields it.\n\n Args:\n dbconnect_info: A dictionary with the following keys:\n db_port (str): The database port. Default is 5432.\n db_host (str): The database host.\n db_name (str): The database name.\n db_user (str): The username to connect to the database with.\n db_pw (str): The password to connect to the database with.\n \"\"\"\n try:\n db_port = dbconnect_info['db_port']\n except ValueError:\n db_port = 5432\n new_connection = None\n try:\n new_connection = psycopg2.connect(host=dbconnect_info['db_host'], port=db_port, database=dbconnect_info['db_name'], user=dbconnect_info['db_user'], password=dbconnect_info['db_pw'])\n yield new_connection\n except Exception as ex:\n raise DbError(f'Database Error. {str(ex)}')\n finally:\n if new_connection:\n new_connection.close()", "context": "@contextmanager\ndef get_connection(dbconnect_info: Dict[str, Union[str, int]]) -> connection: ...\ndef get_utc_now_iso() -> str: ...\ndef uuid_generator() -> str: ...\ndef result_to_json(result_rows): ...\ndef myconverter(obj: any) -> Optional[str]: ...\ndef get_connection(dbconnect_info: Dict[str, Union[str, int]]) -> connection: ...\ndef get_cursor(dbconnect_info: Dict[str, Union[str, int]]) -> cursor: ...\ndef single_query(sql_stmt, dbconnect_info: Dict[str, Union[str, int]], params=None) -> List[Tuple]: ...\ndef read_db_connect_info(param_source): ...\ndef get_db_connect_info(env_or_secretsmanager: str, param_name: str) -> str: ...\ndef multi_query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef _query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef return_connection(dbconnect_info) -> connection: ...\ndef return_cursor(conn: connection) -> cursor: ...\ndef query_no_params(db_cursor: cursor, sql_stmt) -> str: ...\ndef query_from_file(db_cursor: cursor, sql_file): ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_get_connection", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002668.py"} {"focal_file": "tasks/pg_utils/database.py", "focal_class": null, "focal_method": "return_connection", "tests": "import unittest\n\nclass Test_return_connection(unittest.TestCase):\n @patch('psycopg2.connect')\n def test_return_connection(self, mock_connect: MagicMock):\n \"\"\"\n Tests getting a database connection\n \"\"\"\n db_connect_info = {'db_host': os.environ['DATABASE_HOST'], 'db_port': os.environ['DATABASE_PORT'], 'db_name': os.environ['DATABASE_NAME'], 'db_user': os.environ['DATABASE_USER'], 'db_pw': os.environ['DATABASE_PW']}\n expected = Mock()\n mock_connect.return_value = expected\n con = database.return_connection(db_connect_info)\n self.assertEqual(expected, con)\n mock_connect.assert_called_once_with(host=db_connect_info['db_host'], port=db_connect_info['db_port'], database=db_connect_info['db_name'], user=db_connect_info['db_user'], password=db_connect_info['db_pw'])\n", "method_code": "def return_connection(dbconnect_info) -> connection:\n \"\"\"\n Retrieves a connection from the connection pool.\n \"\"\"\n try:\n db_port = dbconnect_info['db_port']\n except ValueError:\n db_port = 5432\n try:\n return psycopg2.connect(host=dbconnect_info['db_host'], port=db_port, database=dbconnect_info['db_name'], user=dbconnect_info['db_user'], password=dbconnect_info['db_pw'])\n except Exception as ex:\n LOGGER.exception(f'Exception. {str(ex)}')\n raise DbError(f'Database Error. {str(ex)}')", "context": "def return_connection(dbconnect_info) -> connection: ...\ndef get_utc_now_iso() -> str: ...\ndef uuid_generator() -> str: ...\ndef result_to_json(result_rows): ...\ndef myconverter(obj: any) -> Optional[str]: ...\ndef get_connection(dbconnect_info: Dict[str, Union[str, int]]) -> connection: ...\ndef get_cursor(dbconnect_info: Dict[str, Union[str, int]]) -> cursor: ...\ndef single_query(sql_stmt, dbconnect_info: Dict[str, Union[str, int]], params=None) -> List[Tuple]: ...\ndef read_db_connect_info(param_source): ...\ndef get_db_connect_info(env_or_secretsmanager: str, param_name: str) -> str: ...\ndef multi_query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef _query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef return_connection(dbconnect_info) -> connection: ...\ndef return_cursor(conn: connection) -> cursor: ...\ndef query_no_params(db_cursor: cursor, sql_stmt) -> str: ...\ndef query_from_file(db_cursor: cursor, sql_file): ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002669.py"} {"focal_file": "tasks/pg_utils/database.py", "focal_class": null, "focal_method": "single_query", "tests": "import unittest\n\nclass Test_single_query(unittest.TestCase):\n def test_single_query(self):\n \"\"\"\n Tests the single_query function\n \"\"\"\n qresult = []\n row = self.build_row('key1', 'value2', 'value3')\n qresult.append(psycopg2.extras.RealDictRow(row))\n row = self.build_row('key2', 'value4', 'value5')\n qresult.append(psycopg2.extras.RealDictRow(row))\n empty_result = []\n database.single_query = Mock(side_effect=[qresult, empty_result])\n sql_stmt = 'Select * from mytable'\n rows = database.single_query(sql_stmt, self.dbconnect_info)\n self.assertEqual(qresult, rows)\n rows = database.single_query(sql_stmt, self.dbconnect_info)\n self.assertEqual(empty_result, rows)\n database.single_query.assert_called()\n\n def test_single_query_secretsmanager(self):\n \"\"\"\n Tests the single_query function\n \"\"\"\n dbconnect_info = {'db_host': 'my.db.host.gov', 'db_port': 5432, 'db_name': 'postgres', 'db_user': 'postgres', 'db_pw': 'secret'}\n sql_stmt = 'Select * from mytable'\n exp_err = 'Database Error. could not translate host name \"my.db.host.gov\" to address: Unknown host\\n'\n try:\n database.single_query(sql_stmt, dbconnect_info)\n except DbError as err:\n self.assertEqual(exp_err, str(err))\n", "method_code": "def single_query(sql_stmt, dbconnect_info: Dict[str, Union[str, int]], params=None) -> List[Tuple]:\n \"\"\"\n This is a convenience function for running single statement transactions\n against the database. It will automatically commit the transaction and\n return a list of the rows.\n\n For multi-query transactions, see multi_query().\n\n todo: other args\n Args:\n dbconnect_info: A dictionary with the following keys:\n db_port (str): The database port. Default is 5432.\n db_host (str): The database host.\n db_name (str): The database name.\n db_user (str): The username to connect to the database with.\n db_pw (str): The password to connect to the database with.\n \"\"\"\n with get_cursor(dbconnect_info) as db_cursor:\n rows = _query(sql_stmt, params, db_cursor)\n return rows", "context": "def single_query(sql_stmt, dbconnect_info: Dict[str, Union[str, int]], params=None) -> List[Tuple]: ...\ndef get_utc_now_iso() -> str: ...\ndef uuid_generator() -> str: ...\ndef result_to_json(result_rows): ...\ndef myconverter(obj: any) -> Optional[str]: ...\ndef get_connection(dbconnect_info: Dict[str, Union[str, int]]) -> connection: ...\ndef get_cursor(dbconnect_info: Dict[str, Union[str, int]]) -> cursor: ...\ndef single_query(sql_stmt, dbconnect_info: Dict[str, Union[str, int]], params=None) -> List[Tuple]: ...\ndef read_db_connect_info(param_source): ...\ndef get_db_connect_info(env_or_secretsmanager: str, param_name: str) -> str: ...\ndef multi_query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef _query(sql_stmt, params, db_cursor: cursor) -> List[Tuple]: ...\ndef return_connection(dbconnect_info) -> connection: ...\ndef return_cursor(conn: connection) -> cursor: ...\ndef query_no_params(db_cursor: cursor, sql_stmt) -> str: ...\ndef query_from_file(db_cursor: cursor, sql_file): ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_single_query", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002670.py"} {"focal_file": "tasks/post_copy_request_to_queue/post_copy_request_to_queue.py", "focal_class": null, "focal_method": "exponential_delay", "tests": "import unittest\n\nclass Test_exponential_delay(unittest.TestCase):\n def test_exponential_delay(self):\n \"\"\"\n tests delay function. Raises Exception when args are non-integer\n \"\"\"\n base_delay_values = [2, 'non-integer']\n exponential_backoff_values = ['non-integer', 2]\n for i in range(2):\n base_delay = base_delay_values[i]\n exponential_backoff = exponential_backoff_values[i]\n self.assertRaises(ValueError, exponential_delay, base_delay, exponential_backoff)\n base_delay = 2\n exponential_backoff = 2\n self.assertEqual(exponential_delay(base_delay, exponential_backoff), base_delay * exponential_backoff)\n", "method_code": "def exponential_delay(base_delay: int, exponential_backoff: int=2) -> int:\n \"\"\"\n Exponential delay function. This function is used for retries during failure.\n Args:\n base_delay: Number of seconds to wait between recovery failure retries.\n exponential_backoff: The multiplier by which the retry interval increases during each attempt.\n Returns:\n An integer which is multiplication of base_delay and exponential_backoff.\n Raises:\n None\n \"\"\"\n try:\n _base_delay = int(base_delay)\n _exponential_backoff = int(exponential_backoff)\n delay = _base_delay + random.randint(0, 1000) / 1000.0\n LOGGER.debug(f'Performing back off retry sleeping {delay} seconds')\n time.sleep(delay)\n return _base_delay * _exponential_backoff\n except ValueError as ve:\n LOGGER.error('arguments are not integer. Raised ValueError: {ve}', ve=ve)\n raise ve", "context": "def exponential_delay(base_delay: int, exponential_backoff: int=2) -> int: ...\ndef task(record: Dict[str, Any], db_queue_url: str, recovery_queue_url: str, max_retries: int, retry_sleep_secs: int, retry_backoff: int) -> None: ...\ndef get_metadata_sql(key_path: str) -> text: ...\ndef exponential_delay(base_delay: int, exponential_backoff: int=2) -> int: ...\ndef handler(event: Dict[str, Any], context: None) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_exponential_delay", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002671.py"} {"focal_file": "tasks/post_copy_request_to_queue/post_copy_request_to_queue.py", "focal_class": null, "focal_method": "get_metadata_sql", "tests": "import unittest\n\nclass Test_get_metadata_sql(unittest.TestCase):\n def test_get_metadata_sql_happy_path(self):\n key_path = uuid.uuid4().__str__()\n result = post_copy_request_to_queue.get_metadata_sql(key_path)\n self.assertEqual(f\"\\n SELECT\\n job_id, granule_id, filename, restore_destination\\n FROM\\n recovery_file\\n WHERE\\n key_path = '{key_path}'\\n AND\\n status_id = {shared_recovery.OrcaStatus.PENDING.value}\\n \", result.text)\n", "method_code": "def get_metadata_sql(key_path: str) -> text:\n \"\"\"\n Query for finding metadata based on key_path and PENDING status.\n\n Args:\n key_path (str): s3 key for the file less the bucket name\n\n Returns:\n (sqlalchemy.text): SQL statement\n \"\"\"\n return text(f\"\\n SELECT\\n job_id, granule_id, filename, restore_destination\\n FROM\\n recovery_file\\n WHERE\\n key_path = '{key_path}'\\n AND\\n status_id = {shared_recovery.OrcaStatus.PENDING.value}\\n \")", "context": "def get_metadata_sql(key_path: str) -> text: ...\ndef task(record: Dict[str, Any], db_queue_url: str, recovery_queue_url: str, max_retries: int, retry_sleep_secs: int, retry_backoff: int) -> None: ...\ndef get_metadata_sql(key_path: str) -> text: ...\ndef exponential_delay(base_delay: int, exponential_backoff: int=2) -> int: ...\ndef handler(event: Dict[str, Any], context: None) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_get_metadata_sql_happy_path", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002672.py"} {"focal_file": "tasks/request_files/request_files.py", "focal_class": null, "focal_method": "process_granule", "tests": "import unittest\n\nclass Test_process_granule(unittest.TestCase):\n @patch('time.sleep')\n @patch('request_files.restore_object')\n def test_process_granule_minimal_path(self, mock_restore_object: MagicMock, mock_sleep: MagicMock):\n mock_s3 = Mock()\n max_retries = randint(10, 999)\n glacier_bucket = uuid.uuid4().__str__()\n retry_sleep_secs = randint(0, 99)\n retrieval_type = uuid.uuid4().__str__()\n restore_expire_days = randint(0, 99)\n granule_id = uuid.uuid4().__str__()\n file_name_0 = uuid.uuid4().__str__()\n dest_bucket_0 = uuid.uuid4().__str__()\n file_name_1 = uuid.uuid4().__str__()\n dest_bucket_1 = uuid.uuid4().__str__()\n job_id = uuid.uuid4().__str__()\n db_queue_url = 'http://' + uuid.uuid4().__str__() + '.blah'\n granule = {request_files.GRANULE_GRANULE_ID_KEY: granule_id, request_files.GRANULE_RECOVER_FILES_KEY: [{'success': False, 'filename': os.path.basename(file_name_0), 'key_path': file_name_0, 'restore_destination': dest_bucket_0, 'status_id': 1}, {'success': False, 'filename': os.path.basename(file_name_1), 'key_path': file_name_1, 'restore_destination': dest_bucket_1, 'status_id': 1}]}\n request_files.process_granule(mock_s3, granule, glacier_bucket, restore_expire_days, max_retries, retry_sleep_secs, retrieval_type, job_id, db_queue_url)\n self.assertTrue(granule[request_files.GRANULE_RECOVER_FILES_KEY][0][request_files.FILE_SUCCESS_KEY])\n self.assertTrue(granule[request_files.GRANULE_RECOVER_FILES_KEY][1][request_files.FILE_SUCCESS_KEY])\n mock_restore_object.assert_has_calls([call(mock_s3, file_name_0, restore_expire_days, glacier_bucket, 1, job_id, retrieval_type), call(mock_s3, file_name_1, restore_expire_days, glacier_bucket, 1, job_id, retrieval_type)])\n self.assertEqual(2, mock_restore_object.call_count)\n mock_sleep.assert_not_called()\n\n @patch('time.sleep')\n @patch('request_files.restore_object')\n def test_process_granule_one_client_error_retries(self, mock_restore_object: MagicMock, mock_sleep: MagicMock):\n mock_s3 = Mock()\n max_retries = 5\n glacier_bucket = uuid.uuid4().__str__()\n retry_sleep_secs = randint(0, 99)\n retrieval_type = uuid.uuid4().__str__()\n restore_expire_days = randint(0, 99)\n granule_id = uuid.uuid4().__str__()\n file_name_0 = uuid.uuid4().__str__()\n dest_bucket_0 = uuid.uuid4().__str__()\n job_id = uuid.uuid4().__str__()\n db_queue_url = 'http://' + uuid.uuid4().__str__() + '.blah'\n granule = {request_files.GRANULE_GRANULE_ID_KEY: granule_id, request_files.GRANULE_RECOVER_FILES_KEY: [{'filename': os.path.basename(file_name_0), 'key_path': file_name_0, 'restore_destination': dest_bucket_0, 'success': False, 'status_id': 1}]}\n mock_restore_object.side_effect = [ClientError({}, ''), None]\n request_files.process_granule(mock_s3, granule, glacier_bucket, restore_expire_days, max_retries, retry_sleep_secs, retrieval_type, job_id, db_queue_url)\n self.assertTrue(granule[request_files.GRANULE_RECOVER_FILES_KEY][0][request_files.FILE_SUCCESS_KEY])\n files = [{'filename': file_name_0, 'key_path': file_name_0, 'restore_destination': dest_bucket_0, 'status_id': request_files.shared_recovery.OrcaStatus.PENDING.value, 'error_message': None, 'request_time': mock.ANY, 'last_update': mock.ANY, 'completion_time': None}]\n mock_restore_object.assert_has_calls([call(mock_s3, file_name_0, restore_expire_days, glacier_bucket, 1, job_id, retrieval_type), call(mock_s3, file_name_0, restore_expire_days, glacier_bucket, 2, job_id, retrieval_type)])\n self.assertEqual(2, mock_restore_object.call_count)\n mock_sleep.assert_called_once_with(retry_sleep_secs)\n", "method_code": "def process_granule(s3: BaseClient, granule: Dict[str, Union[str, List[Dict]]], glacier_bucket: str, restore_expire_days: int, max_retries: int, retry_sleep_secs: float, retrieval_type: str, job_id: str, db_queue_url: str) -> None:\n \"\"\"Call restore_object for the files in the granule_list. Modifies granule for output.\n Args:\n s3: An instance of boto3 s3 client\n granule: A dict with the following keys:\n 'granuleId' (str): The id of the granule being restored.\n 'recover_files' (list(dict)): A list of dicts with the following keys:\n 'key' (str): Name of the file within the granule.\n 'dest_bucket' (str): The bucket the restored file will be moved\n to after the restore completes\n 'success' (bool): Should enter this method set to False. Modified to 'True' by method end.\n 'err_msg' (str): Will be modified if error occurs.\n\n\n glacier_bucket: The S3 glacier bucket name.\n restore_expire_days:\n The number of days the restored file will be accessible in the S3 bucket before it expires.\n max_retries: todo\n retry_sleep_secs: todo\n retrieval_type: todo\n db_queue_url: todo\n job_id: The unique identifier used for tracking requests.\n\n Raises: RestoreRequestError if any file restore could not be initiated.\n \"\"\"\n attempt = 1\n granule_id = granule[GRANULE_GRANULE_ID_KEY]\n while attempt <= max_retries + 1:\n for a_file in granule[GRANULE_RECOVER_FILES_KEY]:\n if not a_file[FILE_SUCCESS_KEY]:\n try:\n restore_object(s3, a_file['key_path'], restore_expire_days, glacier_bucket, attempt, job_id, retrieval_type)\n a_file[FILE_SUCCESS_KEY] = True\n except ClientError as err:\n msg = 'Failed to restore {file} from {glacier_bucket}. Encountered error [ {err} ].'\n LOGGER.error(msg, file=a_file['key_path'], glacier_bucket=glacier_bucket, err=err)\n a_file[FILE_ERROR_MESSAGE_KEY] = str(err)\n attempt = attempt + 1\n if attempt <= max_retries + 1:\n if all((a_file[FILE_SUCCESS_KEY] for a_file in granule[GRANULE_RECOVER_FILES_KEY])):\n break\n time.sleep(retry_sleep_secs)\n any_error = False\n failed_files = []\n for a_file in granule[GRANULE_RECOVER_FILES_KEY]:\n if not a_file[FILE_SUCCESS_KEY]:\n any_error = True\n a_file['status_id'] = shared_recovery.OrcaStatus.FAILED.value\n a_file['completion_time'] = datetime.now(timezone.utc).isoformat()\n LOGGER.debug('Sending status update information for {filename} to the QUEUE', filename=a_file['filename'])\n for retry in range(max_retries + 1):\n try:\n shared_recovery.update_status_for_file(job_id, granule_id, a_file['filename'], shared_recovery.OrcaStatus.FAILED, a_file['error_message'], db_queue_url)\n break\n except Exception as ex:\n msg = f'Ran into error posting to SQS {retry + 1} time(s) with exception'\n msg = msg + ' {ex}'\n LOGGER.error(msg, ex=str(ex))\n time.sleep(retry_sleep_secs)\n continue\n else:\n message = f'Unable to send message to QUEUE {db_queue_url}'\n LOGGER.critical(message, exec_info=True)\n raise Exception(message)\n failed_files.append(a_file)\n granule[GRANULE_RECOVER_FILES_KEY] = failed_files\n if any_error:\n msg = f'One or more files failed to be requested from {glacier_bucket}.'\n LOGGER.error(msg + ' GRANULE: {granule}', granule=json.dumps(granule))\n raise RestoreRequestError(f'One or more files failed to be requested from {glacier_bucket}.')", "context": "def process_granule(s3: BaseClient, granule: Dict[str, Union[str, List[Dict]]], glacier_bucket: str, restore_expire_days: int, max_retries: int, retry_sleep_secs: float, retrieval_type: str, job_id: str, db_queue_url: str) -> None: ...\ndef task(event: Dict, context: object) -> Dict[str, Any]: ...\ndef inner_task(event: Dict, max_retries: int, retry_sleep_secs: float, retrieval_type: str, restore_expire_days: int, db_queue_url: str) -> Dict[str, Any]: ...\ndef process_granule(s3: BaseClient, granule: Dict[str, Union[str, List[Dict]]], glacier_bucket: str, restore_expire_days: int, max_retries: int, retry_sleep_secs: float, retrieval_type: str, job_id: str, db_queue_url: str) -> None: ...\ndef object_exists(s3_cli: BaseClient, glacier_bucket: str, file_key: str) -> bool: ...\ndef restore_object(s3_cli: BaseClient, key: str, days: int, db_glacier_bucket_key: str, attempt: int, job_id: str, retrieval_type: str='Standard') -> None: ...\ndef handler(event: Dict[str, Any], context): ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002673.py"} {"focal_file": "tasks/request_files/request_files.py", "focal_class": null, "focal_method": "object_exists", "tests": "import unittest\n\nclass Test_object_exists(unittest.TestCase):\n def test_object_exists_happy_path(self):\n mock_s3_cli = Mock()\n mock_s3_cli.head_object.side_effect = None\n glacier_bucket = uuid.uuid4().__str__()\n file_key = uuid.uuid4().__str__()\n result = request_files.object_exists(mock_s3_cli, glacier_bucket, file_key)\n self.assertTrue(result)\n\n def test_object_exists_client_error_raised(self):\n expected_error = ClientError({'Error': {'Code': 'Teapot', 'Message': 'test'}}, '')\n mock_s3_cli = Mock()\n mock_s3_cli.head_object.side_effect = expected_error\n glacier_bucket = uuid.uuid4().__str__()\n file_key = uuid.uuid4().__str__()\n try:\n request_files.object_exists(mock_s3_cli, glacier_bucket, file_key)\n self.fail('Error not raised.')\n except ClientError as err:\n self.assertEqual(expected_error, err)\n", "method_code": "def object_exists(s3_cli: BaseClient, glacier_bucket: str, file_key: str) -> bool:\n \"\"\"Check to see if an object exists in S3 Glacier.\n Args:\n s3_cli: An instance of boto3 s3 client\n glacier_bucket: The S3 glacier bucket name\n file_key: The key of the Glacier object\n Returns:\n True if the object exists, otherwise False.\n \"\"\"\n try:\n s3_cli.head_object(Bucket=glacier_bucket, Key=file_key)\n return True\n except ClientError as err:\n LOGGER.error(err)\n code = err.response['Error']['Code']\n message = err.response['Error']['Message']\n if message == 'NoSuchKey' or message == 'Not Found' or code == '404':\n return False\n raise", "context": "def object_exists(s3_cli: BaseClient, glacier_bucket: str, file_key: str) -> bool: ...\ndef task(event: Dict, context: object) -> Dict[str, Any]: ...\ndef inner_task(event: Dict, max_retries: int, retry_sleep_secs: float, retrieval_type: str, restore_expire_days: int, db_queue_url: str) -> Dict[str, Any]: ...\ndef process_granule(s3: BaseClient, granule: Dict[str, Union[str, List[Dict]]], glacier_bucket: str, restore_expire_days: int, max_retries: int, retry_sleep_secs: float, retrieval_type: str, job_id: str, db_queue_url: str) -> None: ...\ndef object_exists(s3_cli: BaseClient, glacier_bucket: str, file_key: str) -> bool: ...\ndef restore_object(s3_cli: BaseClient, key: str, days: int, db_glacier_bucket_key: str, attempt: int, job_id: str, retrieval_type: str='Standard') -> None: ...\ndef handler(event: Dict[str, Any], context): ...\n", "repository": "nasa/cumulus-orca", "test_name": "test_object_exists_happy_path", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002674.py"} {"focal_file": "tasks/request_files/request_files.py", "focal_class": null, "focal_method": "restore_object", "tests": "import unittest\n\nclass Test_restore_object(unittest.TestCase):\n @patch('cumulus_logger.CumulusLogger.info')\n def test_restore_object_happy_path(self, mock_logger_info: MagicMock):\n glacier_bucket = uuid.uuid4().__str__()\n key = uuid.uuid4().__str__()\n restore_expire_days = randint(0, 99)\n retrieval_type = uuid.uuid4().__str__()\n mock_s3_cli = Mock()\n request_files.restore_object(mock_s3_cli, key, restore_expire_days, glacier_bucket, randint(0, 99), uuid.uuid4().__str__(), retrieval_type)\n mock_s3_cli.restore_object.assert_called_once_with(Bucket=glacier_bucket, Key=key, RestoreRequest={'Days': restore_expire_days, 'GlacierJobParameters': {'Tier': retrieval_type}})\n\n @patch('cumulus_logger.CumulusLogger.info')\n def test_restore_object_client_error_raises(self, mock_logger_info: MagicMock):\n job_id = uuid.uuid4().__str__()\n glacier_bucket = uuid.uuid4().__str__()\n key = uuid.uuid4().__str__()\n restore_expire_days = randint(0, 99)\n retrieval_type = uuid.uuid4().__str__()\n expected_error = ClientError({}, '')\n mock_s3_cli = Mock()\n mock_s3_cli.restore_object.side_effect = expected_error\n try:\n request_files.restore_object(mock_s3_cli, key, restore_expire_days, glacier_bucket, 1, job_id, retrieval_type)\n self.fail('Error not Raised.')\n except ClientError as error:\n self.assertEqual(expected_error, error)\n mock_s3_cli.restore_object.assert_called_once_with(Bucket=glacier_bucket, Key=key, RestoreRequest={'Days': restore_expire_days, 'GlacierJobParameters': {'Tier': retrieval_type}})\n", "method_code": "def restore_object(s3_cli: BaseClient, key: str, days: int, db_glacier_bucket_key: str, attempt: int, job_id: str, retrieval_type: str='Standard') -> None:\n \"\"\"Restore an archived S3 Glacier object in an Amazon S3 bucket.\n Args:\n s3_cli: An instance of boto3 s3 client.\n key: The key of the Glacier object being restored.\n days: How many days the restored file will be accessible in the S3 bucket before it expires.\n db_glacier_bucket_key: The S3 bucket name.\n attempt: The attempt number for logging purposes.\n job_id: The unique id of the job. Used for logging.\n retrieval_type: Glacier Tier. Valid values are 'Standard'|'Bulk'|'Expedited'. Defaults to 'Standard'.\n Raises:\n ClientError: Raises ClientErrors from restore_object.\n \"\"\"\n request = {'Days': days, 'GlacierJobParameters': {'Tier': retrieval_type}}\n try:\n s3_cli.restore_object(Bucket=db_glacier_bucket_key, Key=key, RestoreRequest=request)\n except ClientError as c_err:\n LOGGER.error(f'{c_err}. bucket: {db_glacier_bucket_key} file: {key} Job ID: {job_id}')\n raise c_err\n LOGGER.info(f'Restore {key} from {db_glacier_bucket_key} attempt {attempt} successful. Job ID: {job_id}')", "context": "def restore_object(s3_cli: BaseClient, key: str, days: int, db_glacier_bucket_key: str, attempt: int, job_id: str, retrieval_type: str='Standard') -> None: ...\ndef task(event: Dict, context: object) -> Dict[str, Any]: ...\ndef inner_task(event: Dict, max_retries: int, retry_sleep_secs: float, retrieval_type: str, restore_expire_days: int, db_queue_url: str) -> Dict[str, Any]: ...\ndef process_granule(s3: BaseClient, granule: Dict[str, Union[str, List[Dict]]], glacier_bucket: str, restore_expire_days: int, max_retries: int, retry_sleep_secs: float, retrieval_type: str, job_id: str, db_queue_url: str) -> None: ...\ndef object_exists(s3_cli: BaseClient, glacier_bucket: str, file_key: str) -> bool: ...\ndef restore_object(s3_cli: BaseClient, key: str, days: int, db_glacier_bucket_key: str, attempt: int, job_id: str, retrieval_type: str='Standard') -> None: ...\ndef handler(event: Dict[str, Any], context): ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002675.py"} {"focal_file": "tasks/shared_libraries/database/shared_db.py", "focal_class": null, "focal_method": "get_configuration", "tests": "import unittest\n\nclass Test_get_configuration(unittest.TestCase):\n @patch.dict(os.environ, {'PREFIX': 'orcatest', 'DATABASE_NAME': 'disaster_recovery', 'DATABASE_PORT': '5432', 'APPLICATION_USER': 'orcauser', 'ADMIN_USER': 'postgres', 'ADMIN_DATABASE': 'postgres', 'AWS_REGION': 'us-west-2'}, clear=True)\n def test_get_configuration_happy_path(self):\n \"\"\"\n Testing the rainbows and bunnies path of this call.\n \"\"\"\n check_config = {'host': 'aws.postgresrds.host', 'port': '5432', 'database': 'disaster_recovery', 'admin_database': 'postgres', 'app_user': 'orcauser', 'admin_user': 'postgres', 'app_user_password': 'MySecretUserPassword', 'admin_user_password': 'MySecretAdminPassword'}\n testing_config = shared_db.get_configuration()\n for key in check_config:\n self.assertIn(key, testing_config)\n self.assertEqual(check_config[key], testing_config[key])\n\n def test_get_configuration_no_prefix(self):\n \"\"\"\n Validate an error is thrown if PREFIX is not set.\n \"\"\"\n error_message = 'Environment variable PREFIX is not set.'\n with self.assertRaises(Exception) as ex:\n shared_db.get_configuration()\n self.assertEquals(ex.message, error_message)\n\n @patch.dict(os.environ, {'PREFIX': 'orcatest'}, clear=True)\n def test_get_configuration_no_aws_region(self):\n \"\"\"\n Validate an error is thrown if PREFIX is not set.\n \"\"\"\n error_message = 'Environment variable AWS_REGION is not set.'\n with self.assertRaises(Exception) as ex:\n shared_db.get_configuration()\n self.assertEquals(ex.message, error_message)\n\n @patch.dict(os.environ, {'PREFIX': 'orcatest', 'DATABASE_NAME': 'disaster_recovery', 'DATABASE_PORT': '5432', 'APPLICATION_USER': 'orcauser', 'ADMIN_USER': 'postgres', 'ADMIN_DATABASE': 'postgres', 'AWS_REGION': 'us-west-2'}, clear=True)\n def test_get_configuration_bad_env_required(self):\n \"\"\"\n Validate an error is thrown if an expected environment variable is not\n is not set.\n \"\"\"\n env_names = ['DATABASE_NAME', 'DATABASE_PORT', 'APPLICATION_USER']\n env_bad_values = [None, '']\n for name in env_names:\n good_value = os.getenv(name)\n for bad_value in env_bad_values:\n with self.subTest(name=name, bad_value=bad_value, good_value=good_value):\n if bad_value is None:\n del os.environ[name]\n else:\n os.environ[name] = bad_value\n message = f'Environment variable {name} is not set and is required'\n with self.assertRaises(Exception) as ex:\n shared_db.get_configuration()\n self.assertEquals(ex.message, message)\n os.environ[name] = good_value\n\n @patch.dict(os.environ, {'PREFIX': 'orcatest', 'DATABASE_NAME': 'disaster_recovery', 'DATABASE_PORT': '5432', 'APPLICATION_USER': 'orcauser', 'ADMIN_USER': 'postgres', 'ADMIN_DATABASE': 'postgres', 'AWS_REGION': 'us-west-2'}, clear=True)\n @patch('shared_db.logger')\n def test_get_configuration_bad_env_optional(self, mock_logger: MagicMock):\n \"\"\"\n Validate an error is thrown if an expected environment variable is not\n is not set.\n \"\"\"\n env_names = ['ADMIN_USER', 'ADMIN_DATABASE']\n env_bad_values = [None, '']\n for name in env_names:\n good_value = os.getenv(name)\n for bad_value in env_bad_values:\n with self.subTest(name=name, bad_value=bad_value, good_value=good_value):\n if bad_value is None:\n del os.environ[name]\n else:\n os.environ[name] = bad_value\n message = f'Setting variable {name} value to postgres'\n test_config = shared_db.get_configuration()\n mock_logger.info.assert_called_with(message)\n self.assertEqual(test_config[name.lower()], 'postgres')\n os.environ[name] = good_value\n\n @patch.dict(os.environ, {'PREFIX': 'orcatest', 'DATABASE_NAME': 'disaster_recovery', 'DATABASE_PORT': '5432', 'APPLICATION_USER': 'orcauser', 'ADMIN_USER': 'postgres', 'ADMIN_DATABASE': 'postgres', 'AWS_REGION': 'us-west-2'}, clear=True)\n def test_get_configuration_bad_secret(self):\n \"\"\"\n Validates a secret is thrown if a secretmanager ID is invalid.\n \"\"\"\n secret_keys = ['orcatest-drdb-host', 'orcatest-drdb-admin-pass', 'orcatest-drdb-user-pass']\n message = 'Failed to retrieve secret manager value.'\n for secret_key in secret_keys:\n with self.subTest(secret_key=secret_key):\n self.test_sm.delete_secret(SecretId=secret_key, ForceDeleteWithoutRecovery=True)\n with self.assertRaises(Exception) as ex:\n shared_db.get_configuration()\n self.assertEquals(ex.message, message)\n self.test_sm.create_secret(Name=secret_key, SecretString='Some-Value-Here')\n", "method_code": "def get_configuration() -> Dict[str, str]:\n \"\"\"\n Create a dictionary of configuration values based on environment variables\n parameter store information and other items needed to create the database.\n\n ```\n Environment Variables:\n PREFIX (str): Deployment prefix used to pull the proper AWS secret.\n AWS_REGION (str): AWS reserved runtime variable used to set boto3 client region.\n DATABASE_PORT (str): The database port. The standard is 5432\n DATABASE_NAME (str): The name of the application database.\n APPLICATION_USER (str): The name of the database application user.\n ADMIN_USER (str): *OPTIONAL* The name of the database super user (postgres).\n ADMIN_DATABASE (str): *OPTIONAL* The name of the admin database for the instance (postgres).\n\n Parameter Store:\n -drdb-user-pass (string): The password for the application user (APPLICATION_USER).\n -drdb-host (string): The database host.\n -drdb-admin-pass: The password for the admin user\n ```\n\n Args:\n None\n\n Returns:\n Configuration (Dict): Dictionary with all of the configuration information.\n The schema for the output is available [here](schemas/output.json).\n\n Raises:\n Exception (Exception): When variables or secrets are not available.\n \"\"\"\n logger.debug('Getting environment variable PREFIX value.')\n prefix = os.getenv('PREFIX', None)\n if prefix is None or len(prefix) == 0:\n message = 'Environment variable PREFIX is not set.'\n logger.critical(message)\n raise Exception(message)\n logger.debug('Getting environment variable AWS_REGION value.')\n aws_region = os.getenv('AWS_REGION', None)\n if aws_region is None or len(aws_region) == 0:\n message = 'Runtime environment variable AWS_REGION is not set.'\n logger.critical(message)\n raise Exception(message)\n config = {}\n config_map = {'database': 'DATABASE_NAME', 'port': 'DATABASE_PORT', 'app_user': 'APPLICATION_USER', 'admin_user': 'ADMIN_USER', 'admin_database': 'ADMIN_DATABASE'}\n for key, value in config_map.items():\n logger.debug(f'Getting environment variable {value} value.')\n env_value = os.getenv(value, None)\n if env_value is None or len(env_value) == 0:\n if key in ['admin_user', 'admin_database']:\n env_value = 'postgres'\n logger.info(f'Setting variable {value} value to {env_value}')\n else:\n message = f'Environment variable {value} is not set and is required'\n logger.critical(message)\n raise Exception(message)\n config[key] = env_value\n try:\n logger.debug('Creating secretsmanager resource.')\n secretsmanager = boto3.client('secretsmanager', region_name=aws_region)\n logger.debug('Retrieving database application user password.')\n app_user_pw = secretsmanager.get_secret_value(SecretId=f'{prefix}-drdb-user-pass')\n config['app_user_password'] = app_user_pw['SecretString']\n logger.debug('Retrieving database root user password.')\n admin_user_pw = secretsmanager.get_secret_value(SecretId=f'{prefix}-drdb-admin-pass')\n config['admin_user_password'] = admin_user_pw['SecretString']\n logger.debug('Retrieving database host information.')\n db_host = secretsmanager.get_secret_value(SecretId=f'{prefix}-drdb-host')\n config['host'] = db_host['SecretString']\n except Exception as e:\n logger.critical('Failed to retrieve secret.', exc_info=True)\n raise Exception('Failed to retrieve secret manager value.')\n return config", "context": "def get_configuration() -> Dict[str, str]: ...\ndef get_configuration() -> Dict[str, str]: ...\ndef _create_connection(**kwargs: Any) -> Engine: ...\ndef get_admin_connection(config: Dict[str, str], database: str=None) -> Engine: ...\ndef get_user_connection(config: Dict[str, str]) -> Engine: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002676.py"} {"focal_file": "tasks/shared_libraries/database/shared_db.py", "focal_class": null, "focal_method": "get_admin_connection", "tests": "import unittest\n\nclass Test_get_admin_connection(unittest.TestCase):\n @patch.dict(os.environ, {'PREFIX': 'orcatest', 'DATABASE_NAME': 'disaster_recovery', 'DATABASE_PORT': '5432', 'APPLICATION_USER': 'orcauser', 'ADMIN_USER': 'postgres', 'ADMIN_DATABASE': 'postgres', 'AWS_REGION': 'us-west-2'}, clear=True)\n @patch('shared_db._create_connection')\n def test_get_admin_connection_database_values(self, mock_connection: MagicMock):\n \"\"\"\n Tests the function to make sure the correct database value is passed.\n \"\"\"\n root_db_call = {'host': 'aws.postgresrds.host', 'port': '5432', 'database': 'postgres', 'username': 'postgres', 'password': 'MySecretAdminPassword'}\n user_db_call = {'host': 'aws.postgresrds.host', 'port': '5432', 'database': 'disaster_recovery', 'username': 'postgres', 'password': 'MySecretAdminPassword'}\n config = shared_db.get_configuration()\n root_db_creds = shared_db.get_admin_connection(config)\n mock_connection.assert_called_with(**root_db_call)\n user_db_creds = shared_db.get_admin_connection(config, 'disaster_recovery')\n mock_connection.assert_called_with(**user_db_call)\n", "method_code": "def get_admin_connection(config: Dict[str, str], database: str=None) -> Engine:\n \"\"\"\n Creates a connection engine to a database as a superuser.\n\n Args:\n config (Dict): Configuration containing connection information.\n database (str): Database for the admin user to connect to. Defaults to admin_database.\n\n Returns\n Engine (sqlalchemy.future.Engine): engine object for creating database connections.\n \"\"\"\n if database is None or len(database) == 0:\n admin_database = config['admin_database']\n else:\n admin_database = database\n logger.debug('Creating admin user connection object.')\n logger.debug(f'Database set to {admin_database} for the connection.')\n connection = _create_connection(host=config['host'], port=config['port'], database=admin_database, username=config['admin_user'], password=config['admin_user_password'])\n return connection", "context": "def get_admin_connection(config: Dict[str, str], database: str=None) -> Engine: ...\ndef get_configuration() -> Dict[str, str]: ...\ndef _create_connection(**kwargs: Any) -> Engine: ...\ndef get_admin_connection(config: Dict[str, str], database: str=None) -> Engine: ...\ndef get_user_connection(config: Dict[str, str]) -> Engine: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002677.py"} {"focal_file": "tasks/shared_libraries/database/shared_db.py", "focal_class": null, "focal_method": "get_user_connection", "tests": "import unittest\n\nclass Test_get_user_connection(unittest.TestCase):\n @patch.dict(os.environ, {'PREFIX': 'orcatest', 'DATABASE_NAME': 'disaster_recovery', 'DATABASE_PORT': '5432', 'APPLICATION_USER': 'orcauser', 'ADMIN_USER': 'postgres', 'ADMIN_DATABASE': 'postgres', 'AWS_REGION': 'us-west-2'}, clear=True)\n @patch('shared_db._create_connection')\n def test_get_user_connection_database_values(self, mock_connection: MagicMock):\n \"\"\"\n Tests the function to make sure the correct database value is passed.\n \"\"\"\n user_db_call = {'host': 'aws.postgresrds.host', 'port': '5432', 'database': 'disaster_recovery', 'username': 'orcauser', 'password': 'MySecretUserPassword'}\n config = shared_db.get_configuration()\n user_db_creds = shared_db.get_user_connection(config)\n mock_connection.assert_called_with(**user_db_call)\n", "method_code": "def get_user_connection(config: Dict[str, str]) -> Engine:\n \"\"\"\n Creates a connection engine to the application database as the application\n database user.\n\n Args:\n config (Dict): Configuration containing connection information.\n\n Returns\n Engine (sqlalchemy.future.Engine): engine object for creating database connections.\n \"\"\"\n logger.debug('Creating application user connection object.')\n connection = _create_connection(host=config['host'], port=config['port'], database=config['database'], username=config['app_user'], password=config['app_user_password'])\n return connection", "context": "def get_user_connection(config: Dict[str, str]) -> Engine: ...\ndef get_configuration() -> Dict[str, str]: ...\ndef _create_connection(**kwargs: Any) -> Engine: ...\ndef get_admin_connection(config: Dict[str, str], database: str=None) -> Engine: ...\ndef get_user_connection(config: Dict[str, str]) -> Engine: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002678.py"} {"focal_file": "tasks/shared_libraries/database/shared_db.py", "focal_class": null, "focal_method": "_create_connection", "tests": "import unittest\n\nclass Test_create_connection(unittest.TestCase):\n @patch.dict(os.environ, {'PREFIX': 'orcatest', 'DATABASE_NAME': 'disaster_recovery', 'DATABASE_PORT': '5432', 'APPLICATION_USER': 'orcauser', 'ADMIN_USER': 'postgres', 'ADMIN_DATABASE': 'postgres', 'AWS_REGION': 'us-west-2'}, clear=True)\n @patch('shared_db.create_engine')\n def test__create_connection_call_values(self, mock_connection: MagicMock):\n \"\"\"\n Tests the function to make sure the correct database value is passed.\n \"\"\"\n user_db_call = {'host': 'aws.postgresrds.host', 'port': '5432', 'database': 'disaster_recovery', 'username': 'orcauser', 'password': 'MySecretUserPassword'}\n user_db_url = URL.create(drivername='postgresql', **user_db_call)\n user_db_creds = shared_db._create_connection(**user_db_call)\n mock_connection.assert_called_once_with(user_db_url, future=True)\n", "method_code": "def _create_connection(**kwargs: Any) -> Engine:\n \"\"\"\n Base function for creating a connection engine that can connect to a database.\n\n Args:\n host (str): Database host to connect to\n port (str): Database port to connect to\n database (str): Database name to connect to\n username (str): Database user to connect as\n password (str): Database password for the user\n\n Returns\n Engine (sqlalchemy.future.Engine): engine object for creating database connections.\n \"\"\"\n logger.debug('Creating URL object to connect to the database.')\n connection_url = URL.create(drivername='postgresql', **kwargs)\n return create_engine(connection_url, future=True)", "context": "def _create_connection(**kwargs: Any) -> Engine: ...\ndef get_configuration() -> Dict[str, str]: ...\ndef _create_connection(**kwargs: Any) -> Engine: ...\ndef get_admin_connection(config: Dict[str, str], database: str=None) -> Engine: ...\ndef get_user_connection(config: Dict[str, str]) -> Engine: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002679.py"} {"focal_file": "tasks/shared_libraries/recovery/shared_recovery.py", "focal_class": null, "focal_method": "post_entry_to_queue", "tests": "import unittest\n\nclass Test_post_entry_to_queue(unittest.TestCase):\n @patch.dict(os.environ, {'AWS_REGION': 'us-west-2'}, clear=True)\n def test_post_entry_to_queue_no_errors(self):\n \"\"\"\n *Happy Path*\n Test that sending a message to SQS queue using post_entry_to_queue()\n function returns the same expected message.\n \"\"\"\n new_data = {'name': 'test'}\n for request_method in self.request_methods:\n MessageAttributes = {'RequestMethod': {'DataType': 'String', 'StringValue': request_method.value}}\n with self.subTest(request_method=request_method):\n shared_recovery.post_entry_to_queue(new_data, request_method, self.db_queue_url)\n queue_contents = self.queue.receive_messages(MessageAttributeNames=['All'])\n queue_output_body = json.loads(queue_contents[0].body)\n self.assertEqual(queue_contents[0].attributes['MessageGroupId'], self.MessageGroupId)\n self.assertEqual(queue_contents[0].message_attributes, MessageAttributes)\n self.assertEqual(queue_output_body, new_data)\n", "method_code": "def post_entry_to_queue(new_data: Dict[str, Any], request_method: RequestMethod, db_queue_url: str) -> None:\n \"\"\"\n Posts messages to an SQS queue.\n Args:\n new_data: A dictionary representing the column/value pairs to write to the DB table.\n request_method: The method action for the database lambda to take when posting to the SQS queue.\n db_queue_url: The SQS queue URL defined by AWS.\n Raises:\n None\n \"\"\"\n body = json.dumps(new_data)\n LOGGER.debug('Creating SQS resource for {db_queue_url}', db_queue_url=db_queue_url)\n mysqs_resource = boto3.resource('sqs', region_name=get_aws_region())\n mysqs = mysqs_resource.Queue(db_queue_url)\n deduplication_id = request_method.value + hashlib.sha256(body.encode('utf8')).hexdigest()\n md5_body = hashlib.md5(body.encode('utf8')).hexdigest()\n LOGGER.debug('Sending message to the QUEUE')\n response = mysqs.send_message(QueueUrl=db_queue_url, MessageDeduplicationId=deduplication_id, MessageGroupId='request_files', MessageAttributes={'RequestMethod': {'DataType': 'String', 'StringValue': request_method.value}}, MessageBody=body)\n LOGGER.debug('SQS Message Response: {response}', response=json.dumps(response))\n return_status = response['ResponseMetadata']['HTTPStatusCode']\n if return_status < 200 or return_status > 299:\n raise Exception(f'Failed to send message to Queue. HTTP Response was {return_status}')\n sqs_md5 = response.get('MD5OfMessageBody')\n if md5_body != sqs_md5:\n raise Exception(f'Calculated MD5 of {md5_body} does not match SQS MD5 of {sqs_md5}')", "context": "def post_entry_to_queue(new_data: Dict[str, Any], request_method: RequestMethod, db_queue_url: str) -> None: ...\ndef get_aws_region() -> str: ...\ndef create_status_for_job(job_id: str, granule_id: str, archive_destination: str, files: List[Dict[str, Any]], db_queue_url: str): ...\ndef update_status_for_file(job_id: str, granule_id: str, filename: str, orca_status: OrcaStatus, error_message: Optional[str], db_queue_url: str): ...\ndef post_entry_to_queue(new_data: Dict[str, Any], request_method: RequestMethod, db_queue_url: str) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002680.py"} {"focal_file": "tasks/shared_libraries/recovery/shared_recovery.py", "focal_class": null, "focal_method": "create_status_for_job", "tests": "import unittest\n\nclass Test_create_status_for_job(unittest.TestCase):\n @patch.dict(os.environ, {'AWS_REGION': 'us-west-2'}, clear=True)\n def test_create_status_for_job_no_errors(self):\n \"\"\"\n *Happy Path*\n Tests that messages are correctly constructed by function and sent to\n the queue based on RequestMethod and Status values.\n \"\"\"\n MessageAttributes = {'RequestMethod': {'DataType': 'String', 'StringValue': shared_recovery.RequestMethod.NEW_JOB.value}}\n archive_destination = 's3://archive-bucket'\n with self.subTest(request_method=shared_recovery.RequestMethod.NEW_JOB):\n shared_recovery.create_status_for_job(self.job_id, self.granule_id, archive_destination, [], self.db_queue_url)\n queue_contents = self.queue.receive_messages(MessageAttributeNames=['All'])\n queue_output_body = json.loads(queue_contents[0].body)\n self.assertEqual(queue_contents[0].attributes['MessageGroupId'], self.MessageGroupId)\n self.assertEqual(queue_contents[0].message_attributes, MessageAttributes)\n self.assertEqual(queue_output_body['job_id'], self.job_id)\n self.assertEqual(queue_output_body['granule_id'], self.granule_id)\n self.assertIn('request_time', queue_output_body)\n new_request_time = datetime.fromisoformat(queue_output_body['request_time'])\n self.assertEqual(new_request_time.tzinfo, timezone.utc)\n self.assertEqual(queue_output_body['archive_destination'], archive_destination)\n", "method_code": "def create_status_for_job(job_id: str, granule_id: str, archive_destination: str, files: List[Dict[str, Any]], db_queue_url: str):\n \"\"\"\n Creates status information for a new job and its files, and posts to queue.\n Args:\n job_id: The unique identifier used for tracking requests.\n granule_id: The id of the granule being restored.\n archive_destination: The S3 bucket destination of where the data is archived.\n files: A List of Dicts with the following keys:\n 'filename' (str)\n 'key_path' (str)\n 'restore_destination' (str)\n 'status_id' (int)\n 'error_message' (str, Optional)\n 'request_time' (str)\n 'last_update' (str)\n 'completion_time' (str, Optional)\n db_queue_url: The SQS queue URL defined by AWS.\n \"\"\"\n new_data = {'job_id': job_id, 'granule_id': granule_id, 'request_time': datetime.now(timezone.utc).isoformat(), 'archive_destination': archive_destination, 'files': files}\n message = 'Sending the following data to queue: {new_data}'\n LOGGER.debug(message, new_data=new_data)\n post_entry_to_queue(new_data, RequestMethod.NEW_JOB, db_queue_url)", "context": "def create_status_for_job(job_id: str, granule_id: str, archive_destination: str, files: List[Dict[str, Any]], db_queue_url: str): ...\ndef get_aws_region() -> str: ...\ndef create_status_for_job(job_id: str, granule_id: str, archive_destination: str, files: List[Dict[str, Any]], db_queue_url: str): ...\ndef update_status_for_file(job_id: str, granule_id: str, filename: str, orca_status: OrcaStatus, error_message: Optional[str], db_queue_url: str): ...\ndef post_entry_to_queue(new_data: Dict[str, Any], request_method: RequestMethod, db_queue_url: str) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002681.py"} {"focal_file": "tasks/shared_libraries/recovery/shared_recovery.py", "focal_class": null, "focal_method": "update_status_for_file", "tests": "import unittest\n\nclass Test_update_status_for_file(unittest.TestCase):\n @patch.dict(os.environ, {'AWS_REGION': 'us-west-2'}, clear=True)\n def test_update_status_for_file_no_errors(self):\n \"\"\"\n *Happy Path*\n Test that sending a message to SQS queue using post_status_for_file\n function returns the same expected message.\n \"\"\"\n for status_id in self.statuses:\n MessageAttributes = {'RequestMethod': {'DataType': 'String', 'StringValue': shared_recovery.RequestMethod.UPDATE_FILE.value}}\n error_message = 'Access denied'\n filename = 'f1.doc'\n with self.subTest(request_method=shared_recovery.RequestMethod.UPDATE_FILE, status_id=status_id):\n shared_recovery.update_status_for_file(self.job_id, self.granule_id, filename, status_id, error_message, self.db_queue_url)\n queue_contents = self.queue.receive_messages(MessageAttributeNames=['All'])\n queue_output_body = json.loads(queue_contents[0].body)\n self.assertEqual(queue_contents[0].attributes['MessageGroupId'], self.MessageGroupId)\n self.assertEqual(queue_contents[0].message_attributes, MessageAttributes)\n self.assertEqual(queue_output_body['job_id'], self.job_id)\n self.assertEqual(queue_output_body['granule_id'], self.granule_id)\n self.assertEqual(queue_output_body['status_id'], status_id.value)\n self.assertEqual(queue_output_body['filename'], filename)\n self.assertNotIn('request_time', queue_output_body)\n self.assertNotIn('restore_destination', queue_output_body)\n self.assertNotIn('key_path', queue_output_body)\n completion_status = [shared_recovery.OrcaStatus.SUCCESS, shared_recovery.OrcaStatus.FAILED]\n if status_id in completion_status:\n self.assertIn('completion_time', queue_output_body)\n new_completion_time = datetime.fromisoformat(queue_output_body['completion_time'])\n self.assertEqual(new_completion_time.tzinfo, timezone.utc)\n else:\n self.assertNotIn('completion_time', queue_output_body)\n if status_id == shared_recovery.OrcaStatus.FAILED:\n self.assertEqual(queue_output_body['error_message'], error_message)\n else:\n self.assertNotIn('error_message', queue_output_body)\n", "method_code": "def update_status_for_file(job_id: str, granule_id: str, filename: str, orca_status: OrcaStatus, error_message: Optional[str], db_queue_url: str):\n \"\"\"\n Creates update information for a file's status entry, and posts to queue.\n Queue entry will be rejected by post_to_database if status for job_id + granule_id + filename does not exist.\n Args:\n job_id: The unique identifier used for tracking requests.\n granule_id: The id of the granule being restored.\n filename: The name of the file being copied.\n orca_status: Defines the status id used in the ORCA Recovery database.\n error_message: message displayed on error.\n db_queue_url: The SQS queue URL defined by AWS.\n \"\"\"\n last_update = datetime.now(timezone.utc).isoformat()\n new_data = {'job_id': job_id, 'granule_id': granule_id, 'filename': filename, 'last_update': last_update, 'status_id': orca_status.value}\n if orca_status == OrcaStatus.SUCCESS or orca_status == OrcaStatus.FAILED:\n new_data['completion_time'] = datetime.now(timezone.utc).isoformat()\n if orca_status == OrcaStatus.FAILED:\n if len(error_message) == 0 or error_message is None:\n raise Exception('error message is required.')\n new_data['error_message'] = error_message\n message = 'Sending the following data to queue: {new_data}'\n LOGGER.debug(message, new_data=new_data)\n post_entry_to_queue(new_data, RequestMethod.UPDATE_FILE, db_queue_url)", "context": "def update_status_for_file(job_id: str, granule_id: str, filename: str, orca_status: OrcaStatus, error_message: Optional[str], db_queue_url: str): ...\ndef get_aws_region() -> str: ...\ndef create_status_for_job(job_id: str, granule_id: str, archive_destination: str, files: List[Dict[str, Any]], db_queue_url: str): ...\ndef update_status_for_file(job_id: str, granule_id: str, filename: str, orca_status: OrcaStatus, error_message: Optional[str], db_queue_url: str): ...\ndef post_entry_to_queue(new_data: Dict[str, Any], request_method: RequestMethod, db_queue_url: str) -> None: ...\n", "repository": "nasa/cumulus-orca", "test_name": "", "smells": [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002682.py"} {"focal_file": "cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "start", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_start(unittest.TestCase):\n def test_start(self):\n b = wspbus.Bus()\n self.log(b)\n self.responses = []\n num = 3\n for index in range(num):\n b.subscribe('start', self.get_listener('start', index))\n b.start()\n try:\n self.assertEqual(set(self.responses), set([msg % (i, 'start', None) for i in range(num)]))\n self.assertEqual(b.state, b.states.STARTED)\n self.assertLog(['Bus STARTING', 'Bus STARTED'])\n finally:\n b.exit()\n", "method_code": " def start(self):\n \"\"\"Start all services.\"\"\"\n atexit.register(self._clean_exit)\n self.state = states.STARTING\n self.log('Bus STARTING')\n try:\n self.publish('start')\n self.state = states.STARTED\n self.log('Bus STARTED')\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n self.log('Shutting down due to error in start listener:', level=40, traceback=True)\n e_info = sys.exc_info()[1]\n try:\n self.exit()\n except:\n pass\n raise e_info\n ", "context": "class Bus(object):\n def start(self): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "05sonicblue/Gamez", "test_name": "test_start", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002683.py"} {"focal_file": "cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "stop", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_stop(unittest.TestCase):\n def test_stop(self):\n b = wspbus.Bus()\n self.log(b)\n self.responses = []\n num = 3\n for index in range(num):\n b.subscribe('stop', self.get_listener('stop', index))\n b.stop()\n self.assertEqual(set(self.responses), set([msg % (i, 'stop', None) for i in range(num)]))\n self.assertEqual(b.state, b.states.STOPPED)\n self.assertLog(['Bus STOPPING', 'Bus STOPPED'])\n", "method_code": " def stop(self):\n \"\"\"Stop all services.\"\"\"\n self.state = states.STOPPING\n self.log('Bus STOPPING')\n self.publish('stop')\n self.state = states.STOPPED\n self.log('Bus STOPPED')\n ", "context": "class Bus(object):\n def stop(self): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "05sonicblue/Gamez", "test_name": "test_stop", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002684.py"} {"focal_file": "cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "graceful", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_graceful(unittest.TestCase):\n def test_graceful(self):\n b = wspbus.Bus()\n self.log(b)\n self.responses = []\n num = 3\n for index in range(num):\n b.subscribe('graceful', self.get_listener('graceful', index))\n b.graceful()\n self.assertEqual(set(self.responses), set([msg % (i, 'graceful', None) for i in range(num)]))\n self.assertLog(['Bus graceful'])\n", "method_code": " def graceful(self):\n \"\"\"Advise all services to reload.\"\"\"\n self.log('Bus graceful')\n self.publish('graceful')\n ", "context": "class Bus(object):\n def graceful(self): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "05sonicblue/Gamez", "test_name": "test_graceful", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002685.py"} {"focal_file": "cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "exit", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_exit(unittest.TestCase):\n def test_exit(self):\n b = wspbus.Bus()\n self.log(b)\n self.responses = []\n num = 3\n for index in range(num):\n b.subscribe('stop', self.get_listener('stop', index))\n b.subscribe('exit', self.get_listener('exit', index))\n b.exit()\n self.assertEqual(set(self.responses), set([msg % (i, 'stop', None) for i in range(num)] + [msg % (i, 'exit', None) for i in range(num)]))\n self.assertEqual(b.state, b.states.EXITING)\n self.assertLog(['Bus STOPPING', 'Bus STOPPED', 'Bus EXITING', 'Bus EXITED'])\n", "method_code": " def exit(self):\n \"\"\"Stop all services and prepare to exit the process.\"\"\"\n exitstate = self.state\n try:\n self.stop()\n self.state = states.EXITING\n self.log('Bus EXITING')\n self.publish('exit')\n self.log('Bus EXITED')\n except:\n os._exit(70)\n if exitstate == states.STARTING:\n os._exit(70)\n ", "context": "class Bus(object):\n def exit(self): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "05sonicblue/Gamez", "test_name": "test_exit", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002686.py"} {"focal_file": "cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "wait", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_wait(unittest.TestCase):\n def test_wait(self):\n b = wspbus.Bus()\n\n def f(method):\n time.sleep(0.2)\n getattr(b, method)()\n for method, states in [('start', [b.states.STARTED]), ('stop', [b.states.STOPPED]), ('start', [b.states.STARTING, b.states.STARTED]), ('exit', [b.states.EXITING])]:\n threading.Thread(target=f, args=(method,)).start()\n b.wait(states)\n if b.state not in states:\n self.fail('State %r not in %r' % (b.state, states))\n", "method_code": " def wait(self, state, interval=0.1, channel=None):\n \"\"\"Poll for the given state(s) at intervals; publish to channel.\"\"\"\n if isinstance(state, (tuple, list)):\n states = state\n else:\n states = [state]\n \n def _wait():\n while self.state not in states:\n time.sleep(interval)\n self.publish(channel)\n try:\n sys.modules['psyco'].cannotcompile(_wait)\n except (KeyError, AttributeError):\n pass\n _wait()\n ", "context": "class Bus(object):\n def wait(self, state, interval=0.1, channel=None): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "05sonicblue/Gamez", "test_name": "test_wait", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002687.py"} {"focal_file": "cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "block", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_block(unittest.TestCase):\n def test_block(self):\n b = wspbus.Bus()\n self.log(b)\n\n def f():\n time.sleep(0.2)\n b.exit()\n\n def g():\n time.sleep(0.4)\n threading.Thread(target=f).start()\n threading.Thread(target=g).start()\n threads = [t for t in threading.enumerate() if not get_daemon(t)]\n self.assertEqual(len(threads), 3)\n b.block()\n self.assertEqual(b.state, b.states.EXITING)\n threads = [t for t in threading.enumerate() if not get_daemon(t)]\n self.assertEqual(len(threads), 1)\n self.assertEqual(self._log_entries[:-1], ['Bus STOPPING', 'Bus STOPPED', 'Bus EXITING', 'Bus EXITED', 'Waiting for child threads to terminate...'])\n", "method_code": " def block(self, interval=0.1):\n \"\"\"Wait for the EXITING state, KeyboardInterrupt or SystemExit.\n \n This function is intended to be called only by the main thread.\n After waiting for the EXITING state, it also waits for all threads\n to terminate, and then calls os.execv if self.execv is True. This\n design allows another thread to call bus.restart, yet have the main\n thread perform the actual execv call (required on some platforms).\n \"\"\"\n try:\n self.wait(states.EXITING, interval=interval, channel='main')\n except (KeyboardInterrupt, IOError):\n self.log('Keyboard Interrupt: shutting down bus')\n self.exit()\n except SystemExit:\n self.log('SystemExit raised: shutting down bus')\n self.exit()\n raise\n self.log('Waiting for child threads to terminate...')\n for t in threading.enumerate():\n if t != threading.currentThread() and t.isAlive():\n if hasattr(threading.Thread, 'daemon'):\n d = t.daemon\n else:\n d = t.isDaemon()\n if not d:\n self.log('Waiting for thread %s.' % t.getName())\n t.join()\n if self.execv:\n self._do_execv()\n ", "context": "class Bus(object):\n def block(self, interval=0.1): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "05sonicblue/Gamez", "test_name": "test_block", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002688.py"} {"focal_file": "cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "start_with_callback", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_start_with_callback(unittest.TestCase):\n def test_start_with_callback(self):\n b = wspbus.Bus()\n self.log(b)\n try:\n events = []\n\n def f(*args, **kwargs):\n events.append(('f', args, kwargs))\n\n def g():\n events.append('g')\n b.subscribe('start', g)\n b.start_with_callback(f, (1, 3, 5), {'foo': 'bar'})\n time.sleep(0.2)\n self.assertEqual(b.state, b.states.STARTED)\n self.assertEqual(events, ['g', ('f', (1, 3, 5), {'foo': 'bar'})])\n finally:\n b.exit()\n", "method_code": " def start_with_callback(self, func, args=None, kwargs=None):\n \"\"\"Start 'func' in a new thread T, then start self (and return T).\"\"\"\n if args is None:\n args = ()\n if kwargs is None:\n kwargs = {}\n args = (func,) + args\n \n def _callback(func, *a, **kw):\n self.wait(states.STARTED)\n func(*a, **kw)\n t = threading.Thread(target=_callback, args=args, kwargs=kwargs)\n t.setName('Bus Callback ' + t.getName())\n t.start()\n self.start()\n return t\n ", "context": "class Bus(object):\n def start_with_callback(self, func, args=None, kwargs=None): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def log(self, msg='', level=20, traceback=False): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "05sonicblue/Gamez", "test_name": "test_start_with_callback", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002689.py"} {"focal_file": "cherrypy/process/wspbus.py", "focal_class": "cherrypy.process.wspbus.Bus", "focal_method": "log", "tests": "import unittest\n\nclass Test_cherrypy_process_wspbus_Bus_log(unittest.TestCase):\n def test_log(self):\n b = wspbus.Bus()\n self.log(b)\n self.assertLog([])\n expected = []\n for msg in [\"O mah darlin'\"] * 3 + ['Clementiiiiiiiine']:\n b.log(msg)\n expected.append(msg)\n self.assertLog(expected)\n try:\n foo\n except NameError:\n b.log('You are lost and gone forever', traceback=True)\n lastmsg = self._log_entries[-1]\n if 'Traceback' not in lastmsg or 'NameError' not in lastmsg:\n self.fail('Last log message %r did not contain the expected traceback.' % lastmsg)\n else:\n self.fail('NameError was not raised as expected.')\n", "method_code": " def log(self, msg='', level=20, traceback=False):\n \"\"\"Log the given message. Append the last traceback if requested.\"\"\"\n if traceback:\n msg += '\\n' + ''.join(_traceback.format_exception(*sys.exc_info()))\n self.publish('log', msg, level)\n ", "context": "class Bus(object):\n def log(self, msg='', level=20, traceback=False): ...\n def __init__(self): ...\n def subscribe(self, channel, callback, priority=None): ...\n def unsubscribe(self, channel, callback): ...\n def publish(self, channel, *args, **kwargs): ...\n def _clean_exit(self): ...\n def start(self): ...\n def exit(self): ...\n def restart(self): ...\n def graceful(self): ...\n def block(self, interval=0.1): ...\n def wait(self, state, interval=0.1, channel=None): ...\n def _do_execv(self): ...\n def _set_cloexec(self): ...\n def stop(self): ...\n def start_with_callback(self, func, args=None, kwargs=None): ...\n\n self.execv = False\n self.state = states.STOPPED\n self.listeners = dict([(channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])\n self._priorities = {}\n\n states = states\n state = states.STOPPED\n execv = False\n max_cloexec_files = max_files\n", "repository": "05sonicblue/Gamez", "test_name": "test_log", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002690.py"} {"focal_file": "cherrypy/lib/httputil.py", "focal_class": null, "focal_method": "urljoin", "tests": "import unittest\n\nclass Test_urljoin(unittest.TestCase):\n def test_urljoin(self):\n self.assertEqual(httputil.urljoin('/sn/', '/pi/'), '/sn/pi/')\n self.assertEqual(httputil.urljoin('/sn/', '/pi'), '/sn/pi')\n self.assertEqual(httputil.urljoin('/sn/', '/'), '/sn/')\n self.assertEqual(httputil.urljoin('/sn/', ''), '/sn/')\n self.assertEqual(httputil.urljoin('/sn', '/pi/'), '/sn/pi/')\n self.assertEqual(httputil.urljoin('/sn', '/pi'), '/sn/pi')\n self.assertEqual(httputil.urljoin('/sn', '/'), '/sn/')\n self.assertEqual(httputil.urljoin('/sn', ''), '/sn')\n self.assertEqual(httputil.urljoin('/', '/pi/'), '/pi/')\n self.assertEqual(httputil.urljoin('/', '/pi'), '/pi')\n self.assertEqual(httputil.urljoin('/', '/'), '/')\n self.assertEqual(httputil.urljoin('/', ''), '/')\n self.assertEqual(httputil.urljoin('', '/pi/'), '/pi/')\n self.assertEqual(httputil.urljoin('', '/pi'), '/pi')\n self.assertEqual(httputil.urljoin('', '/'), '/')\n self.assertEqual(httputil.urljoin('', ''), '/')\n", "method_code": "def urljoin(*atoms):\n \"\"\"Return the given path \\\\*atoms, joined into a single URL.\n \n This will correctly join a SCRIPT_NAME and PATH_INFO into the\n original URL, even if either atom is blank.\n \"\"\"\n url = '/'.join([x for x in atoms if x])\n while '//' in url:\n url = url.replace('//', '/')\n return url or '/'", "context": "def urljoin(*atoms): ...\ndef urljoin(*atoms): ...\ndef urljoin_bytes(*atoms): ...\ndef protocol_from_http(protocol_str): ...\ndef get_ranges(headervalue, content_length): ...\ndef header_elements(fieldname, fieldvalue): ...\ndef decode_TEXT(value): ...\ndef valid_status(status): ...\ndef _parse_qs(qs, keep_blank_values=0, strict_parsing=0, encoding='utf-8'): ...\ndef parse_query_string(query_string, keep_blank_values=True, encoding='utf-8'): ...\n", "repository": "05sonicblue/Gamez", "test_name": "test_urljoin", "smells": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002691.py"} {"focal_file": "bigbang/api/controller/base.py", "focal_class": null, "focal_method": "__json__", "tests": "import unittest\n\nclass Test_json(unittest.TestCase):\n def test_assign_field(self):\n test_api = self.test_api_cls()\n test_api.test = 'test_value'\n expected_value = {'test': 'test_value'}\n self.assertEqual(expected_value, test_api.__json__())\n\n def test_assign_nonexist_field(self):\n test_api = self.test_api_cls()\n test_api.nonexist = 'test_value'\n expected_value = {}\n self.assertEqual(expected_value, test_api.__json__())\n", "method_code": " def __json__(self):\n return self.as_dict()\n ", "context": "class APIBase(object):\n def __json__(self): ...\n def __init__(self, **kwargs): ...\n def __setattr__(self, field, value): ...\n def as_dict(self): ...\n def unset_fields_except(self, except_list=None): ...\n", "repository": "pythonmao/openstack-framework", "test_name": "test_assign_field", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002692.py"} {"focal_file": "oss_bot/Deploy.py", "focal_class": null, "focal_method": "deploy_lambda__oss_bot", "tests": "import unittest\n\nclass Test_deploy_lambda_oss_bot(unittest.TestCase):\n def test_deploy_lambda__oss_bot(self):\n self.deploy.deploy_lambda__oss_bot()\n", "method_code": " def deploy_lambda__oss_bot(self):\n return self.get_package('oss_bot.lambdas.oss_bot').update_code()\n ", "context": "class Deploy():\n def deploy_lambda__oss_bot(self): ...\n def __init__(self): ...\n def setup(self): ...\n def get_package(self, lambda_name): ...\n def deploy_lambda__git_lambda(self): ...\n def deploy_lambda__browser(self): ...\n def deploy_lambda__slack_message(self): ...\n def deploy_lambda_log_to_elk(self): ...\n def deploy_lambda_png_to_slack(self): ...\n def deploy_lambda_puml_to_png(self): ...\n def deploy_lambda__slack_web(self): ...\n\n self.oss_setup = OSS_Setup()\n", "repository": "OpenSecuritySummit/OSS-Bot", "test_name": "test_deploy_lambda__oss_bot", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002693.py"} {"focal_file": "oss_bot/Deploy.py", "focal_class": null, "focal_method": "deploy_lambda__browser", "tests": "import unittest\n\nclass Test_deploy_lambda_browser(unittest.TestCase):\n def test_deploy_lambda__browser(self):\n self.result = self.deploy.deploy_lambda__browser()\n", "method_code": " def deploy_lambda__browser(self):\n package = self.get_package('osbot_browser.lambdas.lambda_browser')\n source_folder = Files.path_combine(__file__, '../../modules/OSBot-Browser/osbot_browser')\n package.add_folder(source_folder)\n package.add_module('osbot_aws')\n package.add_pbx_gs_python_utils()\n package.update()\n return package\n ", "context": "class Deploy():\n def deploy_lambda__browser(self): ...\n def __init__(self): ...\n def setup(self): ...\n def get_package(self, lambda_name): ...\n def deploy_lambda__oss_bot(self): ...\n def deploy_lambda__git_lambda(self): ...\n def deploy_lambda__slack_message(self): ...\n def deploy_lambda_log_to_elk(self): ...\n def deploy_lambda_png_to_slack(self): ...\n def deploy_lambda_puml_to_png(self): ...\n def deploy_lambda__slack_web(self): ...\n\n self.oss_setup = OSS_Setup()\n", "repository": "OpenSecuritySummit/OSS-Bot", "test_name": "test_deploy_lambda__browser", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002694.py"} {"focal_file": "oss_bot/Deploy.py", "focal_class": null, "focal_method": "deploy_lambda__slack_message", "tests": "import unittest\n\nclass Test_deploy_lambda_slack_message(unittest.TestCase):\n def test_deploy_lambda__slack_message(self):\n result = self.deploy.deploy_lambda__slack_message()\n Dev.pprint(result)\n", "method_code": " def deploy_lambda__slack_message(self):\n package = self.get_package('pbx_gs_python_utils_lambdas_utils_slack_message')\n package._lambda.handler = 'oss_bot.lambdas.slack_message.run'\n package.add_module('oss_bot')\n package.add_module('osbot_aws')\n package.add_pbx_gs_python_utils()\n package.delete()\n package.update()\n ", "context": "class Deploy():\n def deploy_lambda__slack_message(self): ...\n def __init__(self): ...\n def setup(self): ...\n def get_package(self, lambda_name): ...\n def deploy_lambda__oss_bot(self): ...\n def deploy_lambda__git_lambda(self): ...\n def deploy_lambda__browser(self): ...\n def deploy_lambda_log_to_elk(self): ...\n def deploy_lambda_png_to_slack(self): ...\n def deploy_lambda_puml_to_png(self): ...\n def deploy_lambda__slack_web(self): ...\n\n self.oss_setup = OSS_Setup()\n", "repository": "OpenSecuritySummit/OSS-Bot", "test_name": "test_deploy_lambda__slack_message", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002695.py"} {"focal_file": "oss_bot/Deploy.py", "focal_class": null, "focal_method": "deploy_lambda_log_to_elk", "tests": "import unittest\n\nclass Test_deploy_lambda_log_to_elk(unittest.TestCase):\n def test_deploy_lambda_log_to_elk(self):\n lambda_package = self.deploy.deploy_lambda_log_to_elk()\n self.result = lambda_package._lambda.invoke()\n", "method_code": " def deploy_lambda_log_to_elk(self):\n lambda_name = 'pbx_gs_python_utils_lambdas_utils_log_to_elk'\n package = self.get_package(lambda_name)\n package._lambda.handler = 'oss_bot.lambdas.log_to_elk.run'\n package.add_module('oss_bot')\n package.add_pbx_gs_python_utils()\n package.update()\n return package\n ", "context": "class Deploy():\n def deploy_lambda_log_to_elk(self): ...\n def __init__(self): ...\n def setup(self): ...\n def get_package(self, lambda_name): ...\n def deploy_lambda__oss_bot(self): ...\n def deploy_lambda__git_lambda(self): ...\n def deploy_lambda__browser(self): ...\n def deploy_lambda__slack_message(self): ...\n def deploy_lambda_png_to_slack(self): ...\n def deploy_lambda_puml_to_png(self): ...\n def deploy_lambda__slack_web(self): ...\n\n self.oss_setup = OSS_Setup()\n", "repository": "OpenSecuritySummit/OSS-Bot", "test_name": "test_deploy_lambda_log_to_elk", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002696.py"} {"focal_file": "cms/test_utils/util/static_analysis.py", "focal_class": null, "focal_method": "pyflakes", "tests": "import unittest\n\nclass Test_pyflakes(unittest.TestCase):\n def test_pyflakes(self):\n import cms\n import menus\n errors, message = pyflakes((cms, menus))\n self.assertEqual(errors, 0, message)\n", "method_code": "def pyflakes(packages):\n \"\"\"\n Unfortunately, pyflakes does not have a way to suppress certain errors or\n a way to configure the checker class, so we have to monkey patch it.\n\n Returns number of warnings\n \"\"\"\n Checker.___init___ = Checker.__init__\n Checker.__init__ = _pyflakes_no_migrations\n Checker.report = _pyflakes_report_with_nopyflakes\n out = six.StringIO()\n reporter = Reporter(out, out)\n paths = [os.path.dirname(package.__file__) for package in packages]\n return (_check_recursive(paths, reporter), out.getvalue())", "context": "def pyflakes(packages): ...\ndef _pyflakes_report_with_nopyflakes(self, messageClass, node, *args, **kwargs): ...\ndef _pyflakes_no_migrations(self, tree, filename='(none)', builtins=None): ...\ndef _check_recursive(paths, reporter): ...\ndef pyflakes(packages): ...\n", "repository": "xiongzhe90/django-cms", "test_name": "test_pyflakes", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002697.py"} {"focal_file": "src/fieldz/msg_impl.py", "focal_class": null, "focal_method": "make_msg_class", "tests": "import unittest\n\nclass Test_make_msg_class(unittest.TestCase):\n def test_msg_impl(self):\n self.assertIsNotNone(self.str_obj_model)\n self.assertTrue(isinstance(self.str_obj_model, M.ProtoSpec))\n self.assertEqual('org.xlattice.zoggery', self.str_obj_model.name)\n self.assertEqual(0, len(self.str_obj_model.enums))\n self.assertEqual(1, len(self.str_obj_model.msgs))\n self.assertEqual(0, len(self.str_obj_model.seqs))\n msg_spec = self.str_obj_model.msgs[0]\n self.assertEqual(msg_spec.name, 'logEntry')\n chan = Channel(BUFSIZE)\n buf = chan.buffer\n self.assertEqual(BUFSIZE, len(buf))\n log_entry_msg_cls = make_msg_class(self.str_obj_model, msg_spec.name)\n values = self.le_msg_values()\n le_msg = log_entry_msg_cls(values)\n self.assertIsNotNone(le_msg)\n if False:\n try:\n le_msg.foo = 42\n self.fail('ERROR: attempt to assign new instance attribute succeeded')\n except AttributeError as a_exc:\n print('ATTR ERROR ATTEMPTING TO SET le_ms.foo: ' + str(a_exc))\n self.assertIsNotNone(le_msg.mname)\n print('LE_MSG._NAME IS ', le_msg.mname)\n if False:\n try:\n le_msg.name = 'boo'\n self.fail('ERROR: attempt to change message name succeeded')\n except AttributeError:\n pass\n self.assertEqual(msg_spec.mname, le_msg.mname)\n self.assertEqual(0, len(le_msg.enums))\n self.assertEqual(0, len(le_msg.msgs))\n self.assertEqual(6, len(le_msg.field_classes))\n self.assertEqual(6, len(le_msg))\n for field in le_msg.fieldClasses:\n print('FIELD: %s = %s ' % (field.fname, field.value))\n timestamp, node_id, key, length, by_, path = tuple(values)\n self.assertEqual(timestamp, le_msg.timestamp)\n self.assertEqual(node_id, le_msg.node_id)\n self.assertEqual(key, le_msg.key)\n self.assertEqual(length, le_msg.length)\n self.assertEqual(by_, le_msg.by_)\n self.assertEqual(path, le_msg.path)\n expected_msg_len = le_msg.wire_len()\n print('EXPECTED LENGTH OF SERIALIZED OBJECT: %u' % expected_msg_len)\n buf = chan.buffer\n chan.clear()\n nnn = le_msg.write_stand_alone(chan)\n old_position = chan.position\n chan.flip()\n self.assertEqual(old_position, chan.limit)\n self.assertEqual(0, chan.position)\n actual = chan.limit\n read_back, nn2 = MsgImpl.read(chan, self.str_obj_model)\n self.assertIsNotNone(read_back)\n self.assertTrue(le_msg.__eq__(read_back))\n self.assertEqual(nnn, nn2)\n le_msg2 = log_entry_msg_cls(values)\n chan2 = Channel(BUFSIZE)\n nnn = le_msg2.write_stand_alone(chan2)\n chan2.flip()\n copy2, nn3 = log_entry_msg_cls.read(chan2, self.str_obj_model)\n self.assertTrue(le_msg.__eq__(copy2))\n self.assertTrue(le_msg2.__eq__(copy2))\n", "method_code": "def make_msg_class(parent, name):\n \"\"\" construct a MsgClass given a msg name known to the parent \"\"\"\n print(\"\\nMAKE_MSG_CLASS: parent '%s', name '%s'\" % (parent, name))\n msg_spec = parent.get_msg_spec(name)\n return _make_msg_class(parent, msg_spec)", "context": "def make_msg_class(parent, name): ...\ndef impl_len(msg, nnn): ...\ndef _check_position(chan, end): ...\ndef write(self): ...\ndef my_getter(self): ...\ndef my_wire_len(self): ...\ndef my_p_wire_len(self, nnn): ...\ndef my_enums(self): ...\ndef my_msgs(self): ...\ndef my_field_classes(self): ...\ndef msg_initter(cls, *args, **attrs): ...\ndef make_msg_class(parent, name): ...\ndef _make_msg_class(parent, msg_spec): ...\n", "repository": "jddixon/fieldz", "test_name": "test_msg_impl", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_002698.py"} {"focal_file": "src/fieldz/msg_spec.py", "focal_class": null, "focal_method": "f_name", "tests": "import unittest\n\nclass Test_f_name(unittest.TestCase):\n def test_msg_spec(self):\n \"\"\" this is in fact the current spec for a log entry \"\"\"\n protocol = 'org.xlattice.upax'\n node_reg, proto_reg, msg_reg = self.make_registries(protocol)\n parent = M.ProtoSpec(protocol, proto_reg)\n enum = M.EnumSpec.create('Joe', [('oh', 92), ('hello', 47), ('there', 322)])\n fields = [M.FieldSpec(msg_reg, 'timestamp', FieldTypes.F_UINT32, Quants.REQUIRED, 0), M.FieldSpec(msg_reg, 'node_id', FieldTypes.F_BYTES20, Quants.REQUIRED, 1), M.FieldSpec(msg_reg, 'key', FieldTypes.F_BYTES20, Quants.REQUIRED, 2), M.FieldSpec(msg_reg, 'by', FieldTypes.L_STRING, Quants.REQUIRED, 3), M.FieldSpec(msg_reg, 'path', FieldTypes.L_STRING, Quants.REQUIRED, 4)]\n name = 'logEntry'\n msg_spec = M.MsgSpec(name, msg_reg, protocol)\n for fld in fields:\n msg_spec.add_field(fld)\n msg_spec.add_enum(enum)\n self.assertEqual(name, msg_spec.name)\n self.assertEqual(len(fields), len(msg_spec))\n for i in range(len(msg_spec)):\n self.assertEqual(fields[i].name, msg_spec.f_name(i))\n self.assertEqual(fields[i].field_type_name, msg_spec.field_type_name(i))\n self.assertEqual(len(fields), len(msg_spec))\n i = 0\n for field in msg_spec:\n self.assertEqual(fields[i].name, field.name)\n self.assertEqual(fields[i].field_type, field.field_type)\n i += 1\n self.round_trip_msg_spec_via_str(msg_spec, protocol)\n", "method_code": " def f_name(self, i):\n if self.__len__() == 0:\n raise FieldzError('INTERNAL ERROR: message has no fields')\n if i < 0 or i >= self.__len__():\n raise FieldzError('field number %d out of range' % i)\n return self._fields[i].fname\n ", "context": "class MsgSpec(SuperSpec):\n def f_name(self, i): ...\n def __init__(self, mname, reg, parent): ...\n def mname(self): ...\n def fields(self): ...\n def add_field(self, fld): ...\n def __len__(self): ...\n def __getitem__(self, k): ...\n def field_type_name(self, i): ...\n def field_type_from_nbr(self, nbr): ...\n def field_default(self, i): ...\n def __eq__(self, other): ...\n def indented_str(self, indent, step): ...\n def __str__(self): ...\n def __repr__(self): ...\n\n self._mname = mname\n self._fields = []\n self._last_field_nbr = -1\n self.field_name_to_ndx = {}\n self._field_ndx = 0\n\n __slots__ = ['_mname', '_fields', '_last_field_nbr', 'field_name_to_ndx', '_field_ndx']\n", "repository": "jddixon/fieldz", "test_name": "test_msg_spec", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002699.py"} {"focal_file": "src/fieldz/tfbuffer.py", "focal_class": null, "focal_method": "create", "tests": "import unittest\n\nclass Test_create(unittest.TestCase):\n def test_buffer_creator(self):\n tf_buf = TFBuffer.create(TEST_MSG_SPEC, BUFSIZE)\n self.assertTrue(isinstance(tf_buf, TFBuffer))\n self.assertEqual(0, tf_buf.position)\n self.assertEqual(BUFSIZE, tf_buf.capacity)\n\n def test_reader_creator(self):\n tf_reader = TFReader.create(TEST_MSG_SPEC, BUFSIZE)\n self.assertTrue(isinstance(tf_reader, TFReader))\n self.assertEqual(0, tf_reader.position)\n self.assertEqual(BUFSIZE, tf_reader.capacity)\n", "method_code": " def create(cls, msg_spec, nnn):\n if nnn <= 0:\n raise FieldzError('buffer size must be a positive number')\n buffer = bytearray(nnn)\n return cls(msg_spec, nnn, buffer)\n ", "context": "class TFBuffer(wireops.chan.Channel):\n @classmethod\n def create(cls, msg_spec, nnn): ...\n def __init__(self, msg_spec, nnn=1024, buffer=None): ...\n\n self._msg_spec = msg_spec\n", "repository": "jddixon/fieldz", "test_name": "test_buffer_creator", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002700.py"} {"focal_file": "easyargs/parsers.py", "focal_class": null, "focal_method": "parser_help_text", "tests": "import unittest\n\nclass Test_parser_help_text(unittest.TestCase):\n def test_no_params_help(self):\n input = 'A simple greeting program\\n '\n main_text, params_help = parser_help_text(input)\n self.assertEqual(main_text, 'A simple greeting program')\n self.assertEqual(params_help, {})\n", "method_code": "def parser_help_text(help_text):\n \"\"\"Takes the help text supplied as a doc string and extraxts the\n description and any param arguments.\"\"\"\n if help_text is None:\n return (None, {})\n main_text = ''\n params_help = {}\n for line in help_text.splitlines():\n line = line.strip()\n match = re.search(':\\\\s*param\\\\s*(?P\\\\w+)\\\\s*:(?P.*)$', line)\n if match:\n params_help[match.group('param')] = match.group('help').strip()\n else:\n main_text += line + ' '\n main_text = main_text.strip()\n return (main_text, params_help)", "context": "def parser_help_text(help_text): ...\ndef handle_parser(parser): ...\ndef parser_help_text(help_text): ...\ndef create_base_parser(obj): ...\ndef calculate_default_type(arg, has_default, default_value, params_help): ...\ndef function_parser(function, parser): ...\ndef filter_private_methods(method): ...\ndef class_parser(klass, parser, method_filter=filter_private_methods): ...\n", "repository": "stedmeister/easyargs", "test_name": "test_no_params_help", "smells": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002701.py"} {"focal_file": "dumbo/mapredtest.py", "focal_class": "ReduceDriver", "focal_method": "with_params", "tests": "import unittest\n\nclass Test_ReduceDriver_with_params(unittest.TestCase):\n def testreducer_with_params(self):\n input = [(0, 'test me'), (1, 'hello')]\n output = [('foo', 'bar'), ('one', '1')] * 2\n params = [('foo', 'bar'), ('one', '1')]\n ReduceDriver(reducer_with_params).with_params(params).with_input(input).with_output(output).run()\n", "method_code": " def with_params(self, params):\n for k, v in params:\n os.environ[k] = v\n return self\n ", "context": "class BaseDriver(object):\n def with_params(self, params): ...\n def __init__(self, kallable): ...\n def with_input(self, input_source): ...\n def with_output(self, output_source): ...\n def run(self): ...\n def _instrument_class(self, cls): ...\n\n self._input_source = None\n self._output_source = None\n", "repository": "klbostee/dumbo", "test_name": "testreducer_with_params", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_002702.py"} {"focal_file": "dumbo/lib/rawreducer.py", "focal_class": null, "focal_method": "chunkedread", "tests": "import unittest\n\nclass Test_chunkedread(unittest.TestCase):\n def test_chunkedread_on_fileobject(self):\n fo = StringIO('one\\nbig\\nchunk\\nof\\ndata\\n')\n chunks = chunkedread(fo, chunksize=10)\n self.assertEqual(chunks.next(), 'one\\nbig\\nch')\n self.assertEqual(chunks.next(), 'unk\\nof\\ndat')\n self.assertEqual(chunks.next(), 'a\\n')\n self.assertRaises(StopIteration, chunks.next)\n fo.close()\n\n def test_chunkedread_on_filename(self):\n fn = mkstemp()[1]\n try:\n fo = open(fn, 'wb')\n fo.write('one\\nbig\\nchunk\\nof\\ndata\\n')\n fo.close()\n chunks = chunkedread(fn, chunksize=10)\n self.assertEqual(chunks.next(), 'one\\nbig\\nch')\n self.assertEqual(chunks.next(), 'unk\\nof\\ndat')\n self.assertEqual(chunks.next(), 'a\\n')\n self.assertRaises(StopIteration, chunks.next)\n finally:\n os.unlink(fn)\n", "method_code": "def chunkedread(filename_or_fileobj, chunksize=CHUNKSIZE):\n \"\"\"Returns a generator that reads a file in chunks\"\"\"\n if hasattr(filename_or_fileobj, 'read'):\n fileobj = filename_or_fileobj\n needclose = False\n else:\n fileobj = open(filename_or_fileobj, 'rb')\n needclose = True\n try:\n content = fileobj.read(chunksize)\n while content:\n yield content\n content = fileobj.read(chunksize)\n finally:\n if needclose:\n fileobj.close()", "context": "def chunkedread(filename_or_fileobj, chunksize=CHUNKSIZE): ...\ndef chunkedread(filename_or_fileobj, chunksize=CHUNKSIZE): ...\n", "repository": "klbostee/dumbo", "test_name": "test_chunkedread_on_fileobject", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002703.py"} {"focal_file": "dumbo/util.py", "focal_class": null, "focal_method": "getopt", "tests": "import unittest\n\nclass Test_getopt(unittest.TestCase):\n def test_getopt(self):\n opts = []\n values = getopt(opts, 'input')\n self.assertEquals(values, [])\n self.assertEquals(opts, [])\n opts = [('param', 'p1'), ('param', 'p2'), ('input', '/dev/path')]\n values = getopt(opts, 'param')\n expected = ['p2', 'p1']\n self.assertEquals(set(values), set(expected))\n self.assertEquals(set(opts), set([('input', '/dev/path')]))\n opts = [('output', '/prod/path')]\n values = getopt(opts, 'output', delete=False)\n self.assertEquals(values, ['/prod/path'])\n self.assertEquals(opts, [('output', '/prod/path')])\n values = getopt(opts, 'output')\n self.assertEquals(values, ['/prod/path'])\n self.assertEquals(opts, [])\n", "method_code": "def getopt(opts, key, delete=True):\n warnings.warn('getopts will be deprecated. use dumbo.util.Options', DeprecationWarning)\n o = Options(opts)\n if key not in o:\n return []\n values = o.get(key)\n if delete:\n for val in values:\n opts.remove((key, val))\n o.remove(key)\n return values", "context": "def getopt(opts, key, delete=True): ...\ndef sorted(iterable, piecesize=None, key=None, reverse=False): ...\ndef incrcounter(group, counter, amount): ...\ndef setstatus(message): ...\ndef dumpcode(outputs): ...\ndef loadcode(inputs): ...\ndef dumptext(outputs): ...\ndef loadtext(inputs): ...\ndef parseargs(args): ...\ndef getopts(opts, keys, delete=True): ...\ndef getopt(opts, key, delete=True): ...\ndef configopts(section, prog=None, opts=None): ...\ndef execute(cmd, opts=None, precmd='', printcmd=True, stdout=sys.stdout, stderr=sys.stderr): ...\ndef system(cmd, stdout=sys.stdout, stderr=sys.stderr): ...\ndef findhadoop(optval): ...\ndef findjar(hadoop, name, libdirs=None): ...\ndef envdef(varname, files, optname=None, opts=None, commasep=False, shortcuts={}, quote=True, trim=False, extrapaths=None): ...\ndef getclassname(cls): ...\ndef loadclassname(name): ...\n", "repository": "klbostee/dumbo", "test_name": "test_getopt", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002704.py"} {"focal_file": "dumbo/util.py", "focal_class": null, "focal_method": "getopts", "tests": "import unittest\n\nclass Test_getopts(unittest.TestCase):\n def test_getopts(self):\n opts = []\n values = getopts(opts, ['input'])\n self.assertEquals(values, {})\n self.assertEquals(opts, [])\n opts = [('param', 'p1'), ('param', 'p2'), ('input', '/dev/path'), ('output', '/prod/path')]\n values = getopts(opts, ['param', 'input'])\n expected = {'input': ['/dev/path'], 'param': ['p2', 'p1']}\n settize = lambda _dict: set([(k, tuple(sorted(v))) for k, v in _dict.items()])\n self.assertEquals(settize(values), settize(expected))\n self.assertEquals(set(opts), set([('output', '/prod/path')]))\n opts = [('output', '/prod/path')]\n values = getopts(opts, ['output'], delete=False)\n self.assertEquals(values, {'output': ['/prod/path']})\n self.assertEquals(opts, [('output', '/prod/path')])\n values = getopts(opts, ['output'])\n self.assertEquals(values, {'output': ['/prod/path']})\n self.assertEquals(opts, [])\n", "method_code": "def getopts(opts, keys, delete=True):\n warnings.warn('getopts will be deprecated. use dumbo.util.Options', DeprecationWarning)\n o = Options(opts)\n result = o.filter(keys).to_dict()\n if delete:\n for k in keys:\n for v in o.get(k):\n opts.remove((k, v))\n if k in o:\n o.remove(k)\n return result", "context": "def getopts(opts, keys, delete=True): ...\ndef sorted(iterable, piecesize=None, key=None, reverse=False): ...\ndef incrcounter(group, counter, amount): ...\ndef setstatus(message): ...\ndef dumpcode(outputs): ...\ndef loadcode(inputs): ...\ndef dumptext(outputs): ...\ndef loadtext(inputs): ...\ndef parseargs(args): ...\ndef getopts(opts, keys, delete=True): ...\ndef getopt(opts, key, delete=True): ...\ndef configopts(section, prog=None, opts=None): ...\ndef execute(cmd, opts=None, precmd='', printcmd=True, stdout=sys.stdout, stderr=sys.stderr): ...\ndef system(cmd, stdout=sys.stdout, stderr=sys.stderr): ...\ndef findhadoop(optval): ...\ndef findjar(hadoop, name, libdirs=None): ...\ndef envdef(varname, files, optname=None, opts=None, commasep=False, shortcuts={}, quote=True, trim=False, extrapaths=None): ...\ndef getclassname(cls): ...\ndef loadclassname(name): ...\n", "repository": "klbostee/dumbo", "test_name": "test_getopts", "smells": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_002705.py"}